ccc2sage.js 476 KB
var pvc=def.globalSpace('pvc',{debug:0});(function(){(function(){if((typeof window.location)!=='undefined'){var url=window.location.href;if(url&&(/\bdebug=true\b/).test(url)){var m=/\bdebugLevel=(\d+)/.exec(url);pvc.debug=m?(+m[1]):3}}}());pvc.invisibleFill='rgba(127,127,127,0.00001)';pvc.logSeparator="------------------------------------------";var arraySlice=pvc.arraySlice=Array.prototype.slice;pvc.setDebug=function(level){level=+level;pvc.debug=isNaN(level)?0:level;installPvcLog();syncTipsyLog();return pvc.debug};pvc._installLog=function(o,pto,pfrom,prompt){if(!pfrom){pfrom=pto}var c=console;var m=c[pfrom]||c.log;var fun;if(m){var mask=prompt+": %s";if(!def.fun.is(m)){var apply=Function.prototype.apply;fun=function(){apply.call(m,c,def.array.append([mask],arguments))}}else{fun=m.bind(console,mask)}}o[pto]=fun};function installPvcLog(){if(pvc.debug&&typeof console!=="undefined"){['log','info',['trace','debug'],'error','warn','group','groupEnd'].forEach(function(ps){ps=ps instanceof Array?ps:[ps,ps];pvc._installLog(pvc,ps[0],ps[1],'[pvChart]')})}else{if(pvc.debug>1){pvc.debug=1}['log','info','trace','warn','group','groupEnd'].forEach(function(p){pvc[p]=def.noop});pvc.error=function(e){if(e&&typeof e==='object'&&e.message){e=e.message}throw new Error("[pvChart ERROR]: "+e)}}}installPvcLog();pvc.logError=pvc.error;pv.error=pvc.error;function syncTipsyLog(){var tip=pv.Behavior.tipsy;if(tip&&tip.setDebug){tip.setDebug(pvc.debug);tip.log=pvc.log}}syncTipsyLog();pvc.defaultCompatVersion=function(compatVersion){var defaults=pvc.BaseChart.prototype.defaults;if(compatVersion!=null){return defaults.compatVersion=compatVersion}return defaults.compatVersion};pvc.cloneMatrix=function(m){return m.map(function(d){return d.slice()})};pvc.stringify=function(t,keyArgs){var maxLevel=def.get(keyArgs,'maxLevel')||5;var out=[];pvc.stringifyRecursive(out,t,maxLevel,keyArgs);return out.join('')};pvc.stringifyRecursive=function(out,t,remLevels,keyArgs){if(remLevels>0){remLevels--;switch(typeof t){case'undefined':return out.push('undefined');case'object':if(!t){out.push('null');return true}if(def.fun.is(t.stringify)){return t.stringify(out,remLevels,keyArgs)}if(t instanceof Array){out.push('[');t.forEach(function(item,index){if(index){out.push(', ')}if(!pvc.stringifyRecursive(out,item,remLevels,keyArgs)){out.pop()}});out.push(']')}else{var ownOnly=def.get(keyArgs,'ownOnly',true);if(t===def.global){out.push('<window>');return true}if(def.fun.is(t.cloneNode)){out.push('<dom #'+(t.id||t.name||'?')+'>');return true}if(remLevels>1&&t.constructor!==Object){remLevels=1;ownOnly=true}out.push('{');var first=true;for(var p in t){if(!ownOnly||def.hasOwnProp.call(t,p)){if(!first){out.push(', ')}out.push(p+': ');if(!pvc.stringifyRecursive(out,t[p],remLevels,keyArgs)){out.pop();if(!first){out.pop()}}else if(first){first=false}}}if(first){var s=''+t;if(s!=='[object Object]'){out.push('{'+s+'}')}}out.push('}')}return true;case'number':out.push(''+(Math.round(100000*t)/100000)); return true;case'boolean':out.push(''+t);return true;case'string':out.push(JSON.stringify(t));return true;case'function':if(def.get(keyArgs,'funs',false)){out.push(JSON.stringify(t.toString().substr(0,13)+'...'));return true}return false}out.push("'new ???'");return true}};pvc.orientation={vertical:'vertical',horizontal:'horizontal'};pvc.extensionTag='extension';pvc.extendType=function(type,exts,names){if(exts){var exts2;var addExtension=function(ext,name){if(ext!==undefined){if(!exts2){exts2={}}exts2[name]=def.fun.to(ext)}};if(names){names.forEach(function(name){addExtension(exts[name],name)})}else{def.each(addExtension)}if(exts2){type.add(exts2)}}};pv.Mark.prototype.hasDelegateValue=function(name,tag){var p=this.$propertiesMap[name];if(p){return(!tag||p.tag===tag)}if(this.proto){return this.proto.hasDelegateValue(name,tag)}return false};pvc.defaultColorScheme=null;pvc.brighterColorTransform=function(color){return(color.rgb?color:pv.color(color)).brighter(0.6)};pvc.setDefaultColorScheme=function(colors){return pvc.defaultColorScheme=pvc.colorScheme(colors)};pvc.defaultColor=pv.Colors.category10()('?');pvc.colorScheme=function(colors){if(colors==null){return null}if(typeof colors==='function'){if(!colors.hasOwnProperty('range')){return colors}colors=colors.range()}else{colors=def.array.as(colors)}if(!colors.length){return null}return function(){var scale=pv.colors(colors);scale.domain.apply(scale,arguments);return scale}},pvc.createColorScheme=function(colors){return pvc.colorScheme(colors)||pvc.defaultColorScheme||pv.Colors.category10};pvc.toGrayScale=function(color,alpha,maxGrayLevel,minGrayLevel){color=pv.color(color);var avg=0.299*color.r+0.587*color.g+0.114*color.b;if(maxGrayLevel===undefined){maxGrayLevel=200}else if(maxGrayLevel==null){maxGrayLevel=255}if(minGrayLevel===undefined){minGrayLevel=30}else if(minGrayLevel==null){minGrayLevel=0}var delta=(maxGrayLevel-minGrayLevel);if(delta<=0){avg=maxGrayLevel}else{avg=minGrayLevel+(avg/255)*delta}if(alpha==null){alpha=color.opacity}else if(alpha<0){alpha=(-alpha)*color.opacity}avg=Math.round(avg);return pv.rgb(avg,avg,avg,alpha)};pvc.removeTipsyLegends=function(){try{$('.tipsy').remove()}catch(e){}};pvc.createDateComparer=function(parser,key){if(!key){key=pv.identity}return function(a,b){return parser.parse(key(a))-parser.parse(key(b))}};pvc.time={intervals:{'y':31536e6,'m':2592e6,'d30':2592e6,'w':6048e5,'d7':6048e5,'d':864e5,'h':36e5,'M':6e4,'s':1e3,'ms':1},withoutTime:function(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())},weekday:{previousOrSelf:function(t,toWd){var wd=t.getDay();var difDays=wd-toWd;if(difDays){var previousOffset=difDays<0?(7+difDays):difDays;t=new Date(t-previousOffset*pvc.time.intervals.d)}return t},nextOrSelf:function(t,toWd){var wd=t.getDay();var difDays=wd-toWd;if(difDays){var nextOffset=difDays>0?(7-difDays):-difDays;t=new Date(t+nextOffset*pvc.time.intervals.d)}return t},closestOrSelf:function(t,toWd){var wd=t.getDay();var difDays=wd-toWd;if(difDays){var D=pvc.time.intervals.d;var sign=difDays>0?1:-1;difDays=Math.abs(difDays);if(difDays>=4){t=new Date(t.getTime()+sign*(7-difDays)*D)}else{t=new Date(t.getTime()-sign*difDays*D)}}return t}}};pv.Format.createParser=function(pvFormat){function parse(value){return pvFormat.parse(value)}return parse};pv.Format.createFormatter=function(pvFormat){function format(value){return value!=null?pvFormat.format(value):""}return format};pvc.buildTitleFromName=function(name){return def.firstUpperCase(name).replace(/([a-z\d])([A-Z])/,"$1 $2")};pvc.buildIndexedId=function(prefix,index){if(index>0){return prefix+""+(index+1)}return prefix};pvc.splitIndexedId=function(indexedId){var match=/^(.*?)(\d*)$/.exec(indexedId);var index=null;if(match[2]){index=Number(match[2]);if(index<=1){index=1}else{index--}}return[match[1],index]};function unwrapExtensionOne(id,prefix){if(id){if(def.object.is(id)){return id.abs}return prefix?(prefix+def.firstUpperCase(id)):id}return prefix}var oneNullArray=[null];pvc.makeExtensionAbsId=function(id,prefix){if(!id){return prefix}return def.query(prefix||oneNullArray).selectMany(function(oneprefix){return def.query(id).select(function(oneid){return unwrapExtensionOne(oneid,oneprefix)})}).where(def.truthy).array()};pvc.parseDistinctIndexArray=function(value,max){value=def.array.as(value);if(value==null){return null}if(max==null){max=Infinity}var a=def.query(value).select(function(index){return+index}).where(function(index){return!isNaN(index)&&index>=0&&index<=max}).distinct().array();return a.length?a:null};pvc.parseLegendClickMode=function(clickMode){if(!clickMode){clickMode='none'}switch(clickMode){case'toggleSelected':case'toggleVisible':case'none':break;default:if(pvc.debug>=2){pvc.log("[Warning] Invalid 'legendClickMode' option value: '"+clickMode+"'. Assuming 'none'.")}clickMode='none';break}return clickMode};pvc.parseShape=function(shape){if(shape){switch(shape){case'square':case'circle':case'diamond':case'triangle':case'cross':case'bar':break;default:if(pvc.debug>=2){pvc.log("[Warning] Invalid 'shape' option value: '"+shape+"'.")}shape=null;break}}return shape};pvc.parseContinuousColorScaleType=function(scaleType){if(scaleType){switch(scaleType){case'linear':case'normal':case'discrete':break;default:if(pvc.debug>=2){pvc.log("[Warning] Invalid 'ScaleType' option value: '"+scaleType+"'.")}scaleType=null;break}}return scaleType};pvc.parseDomainScope=function(scope,orientation){if(scope){switch(scope){case'cell':case'global':break;case'section':if(!orientation){throw def.error.argumentRequired('orientation')}scope=orientation==='y'?'row':'column';break;case'column':case'row':if(orientation&&orientation!==(scope==='row'?'y':'x')){scope='section';if(pvc.debug>=2){pvc.log("[Warning] Invalid 'DomainScope' option value: '"+scope+"' for the orientation: '"+orientation+"'.")}}break;default:if(pvc.debug>=2){pvc.log("[Warning] Invalid 'DomainScope' option value: '"+scope+"'.")}scope=null;break}}return scope};pvc.parseDomainRoundingMode=function(mode){if(mode){switch(mode){case'none':case'nice':case'tick':break;default:if(pvc.debug>=2){pvc.log("[Warning] Invalid 'DomainRoundMode' value: '"+mode+"'.")}mode=null;break}}return mode};pvc.parseOverlappedLabelsMode=function(mode){if(mode){switch(mode){case'leave':case'hide':break;default:if(pvc.debug>=2){pvc.log("[Warning] Invalid 'OverlappedLabelsMode' option value: '"+mode+"'.")}mode=null;break}}return mode};pvc.castNumber=function(value){if(value!=null){value=+value;if(isNaN(value)){value=null}}return value};pvc.parseWaterDirection=function(value){if(value){switch(value){case'up':case'down':return value}if(pvc.debug>=2){pvc.log("[Warning] Invalid 'WaterDirection' value: '"+value+"'.")}}};pvc.parseTrendType=function(value){if(value){if(value==='none'){return value}if(pvc.trends.has(value)){return value}if(pvc.debug>=2){pvc.log("[Warning] Invalid 'TrendType' value: '"+value+"'.")}}};pvc.parseNullInterpolationMode=function(value){if(value){switch(value){case'none':case'linear':case'zero':return value}if(pvc.debug>=2){pvc.log("[Warning] Invalid 'NullInterpolationMode' value: '"+value+"'.")}}};pvc.parseAlign=function(side,align){var align2,isInvalid;if(side==='left'||side==='right'){align2=align&&pvc.BasePanel.verticalAlign[align];if(!align2){align2='middle';isInvalid=!!align}}else{align2=align&&pvc.BasePanel.horizontalAlign[align];if(!align2){align2='center';isInvalid=!!align}}if(isInvalid&&pvc.debug>=2){pvc.log(def.format("Invalid alignment value '{0}'. Assuming '{1}'.",[align,align2]))}return align2};pvc.parseAnchor=function(anchor){if(anchor){switch(anchor){case'top':case'left':case'center':case'bottom':case'right':return anchor}if(pvc.debug>=2){pvc.log(def.format("Invalid anchor value '{0}'.",[anchor]))}}};pvc.parseAnchorWedge=function(anchor){if(anchor){switch(anchor){case'outer':case'inner':case'center':case'start':case'end':return anchor}if(pvc.debug>=2){pvc.log(def.format("Invalid wedge anchor value '{0}'.",[anchor]))}}};pvc.unionExtents=function(result,range){if(!result){if(!range){return null}result={min:range.min,max:range.max}}else if(range){if(range.min<result.min){result.min=range.min}if(range.max>result.max){result.max=range.max}}return result};pvc.Sides=function(sides){if(sides!=null){this.setSides(sides)}};pvc.Sides.hnames='left right'.split(' ');pvc.Sides.vnames='top bottom'.split(' ');pvc.Sides.names='left right top bottom'.split(' ');pvc.Sides.namesSet=pv.dict(pvc.Sides.names,def.retTrue);pvc.parsePosition=function(side,defaultSide){if(side&&!def.hasOwn(pvc.Sides.namesSet,side)){if(!defaultSide){defaultSide='left'}if(pvc.debug>=2){pvc.log(def.format("Invalid position value '{0}. Assuming '{1}'.",[side,defaultSide]))}side=defaultSide}return side};pvc.Sides.as=function(v){if(v!=null&&!(v instanceof pvc.Sides)){v=new pvc.Sides().setSides(v)}return v};pvc.Sides.prototype.stringify=function(out,remLevels,keyArgs){return pvc.stringifyRecursive(out,def.copyOwn(this),remLevels,keyArgs)};pvc.Sides.prototype.setSides=function(sides){if(typeof sides==='string'){var comps=sides.split(/\s+/).map(function(comp){return pvc.PercentValue.parse(comp)});switch(comps.length){case 1:this.set('all',comps[0]);return this;case 2:this.set('top',comps[0]);this.set('left',comps[1]);this.set('right',comps[1]);this.set('bottom',comps[0]);return this;case 3:this.set('top',comps[0]);this.set('left',comps[1]);this.set('right',comps[1]);this.set('bottom',comps[2]);return this;case 4:this.set('top',comps[0]);this.set('right',comps[1]);this.set('bottom',comps[2]);this.set('left',comps[3]);return this;case 0:return this}}else if(typeof sides==='number'){this.set('all',sides);return this}else if(typeof sides==='object'){if(sides instanceof pvc.PercentValue){this.set('all',sides)}else{this.set('all',sides.all);for(var p in sides){if(p!=='all'&&pvc.Sides.namesSet.hasOwnProperty(p)){this.set(p,sides[p])}}}return this}if(pvc.debug){pvc.log("Invalid 'sides' value: "+pvc.stringify(sides))}return this};pvc.Sides.prototype.set=function(prop,value){value=pvc.PercentValue.parse(value);if(value!=null){if(prop==='all'){pvc.Sides.names.forEach(function(p){this[p]=value},this)}else if(def.hasOwn(pvc.Sides.namesSet,prop)){this[prop]=value}}};pvc.Sides.prototype.resolve=function(width,height){if(typeof width==='object'){height=width.height;width=width.width}var sides={};pvc.Sides.names.forEach(function(side){var value=0;var sideValue=this[side];if(sideValue!=null){if(typeof(sideValue)==='number'){value=sideValue}else{value=sideValue.resolve((side==='left'||side==='right')?width:height)}}sides[side]=value},this);return pvc.Sides.updateSize(sides)};pvc.Sides.updateSize=function(sides){sides.width=(sides.left||0)+(sides.right||0);sides.height=(sides.bottom||0)+(sides.top||0);return sides};pvc.Sides.resolvedMax=function(a,b){var sides={};pvc.Sides.names.forEach(function(side){sides[side]=Math.max(a[side]||0,b[side]||0)});return sides};pvc.Sides.inflate=function(sides,by){var sidesOut={};pvc.Sides.names.forEach(function(side){sidesOut[side]=(sides[side]||0)+by});return pvc.Sides.updateSize(sidesOut)};pvc.PercentValue=function(pct){this.percent=pct};pvc.PercentValue.prototype.resolve=function(total){return this.percent*total};pvc.PercentValue.parse=function(value){if(value!=null&&value!==''){switch(typeof value){case'number':return value;case'string':var match=value.match(/^(.+?)\s*(%)?$/);if(match){var n=+match[1];if(!isNaN(n)){if(match[2]){if(n>=0){return new pvc.PercentValue(n/100)}}else{return n}}}break;case'object':if(value instanceof pvc.PercentValue){return value}break}if(pvc.debug){pvc.log(def.format("Invalid margins component '{0}'",[''+value]))}}};pvc.PercentValue.resolve=function(value,total){return(value instanceof pvc.PercentValue)?value.resolve(total):value};var markRenderCore=pv.Mark.prototype.renderCore,markZOrder=pv.Mark.prototype.zOrder;pv.Mark.prototype.zOrder=function(zOrder){var borderPanel=this.borderPanel;if(borderPanel&&borderPanel!==this){return markZOrder.call(borderPanel,zOrder)}return markZOrder.call(this,zOrder)};pv.Mark.prototype.renderCore=function(){var root=this.root;root._renderId=(root._renderId||0)+1;if(pvc.debug>=25){pvc.log("BEGIN RENDER "+root._renderId)}markRenderCore.apply(this,arguments);if(pvc.debug>=25){pvc.log("END RENDER "+root._renderId)}};pv.Mark.prototype.renderId=function(){return this.root._renderId};pv.Mark.prototype.wrapper=function(wrapper){this._wrapper=wrapper;return this};pv.Mark.prototype.wrap=function(f,m){if(f&&def.fun.is(f)&&this._wrapper&&!f._cccWrapped){f=this._wrapper(f,m);f._cccWrapped=true}return f};pv.Mark.prototype.lock=function(prop,value){if(value!==undefined){this[prop](value)}(this._locked||(this._locked={}))[prop]=true;return this};pv.Mark.prototype.isIntercepted=function(prop){return this._intercepted&&this._intercepted[prop]};pv.Mark.prototype.isLocked=function(prop){return this._locked&&this._locked[prop]};pv.Mark.prototype.addMargin=function(name,margin){if(margin!==0){var staticValue=def.nullyTo(this.propertyValue(name),0),fMeasure=pv.functor(staticValue);this[name](function(){return margin+fMeasure.apply(this,arraySlice.call(arguments))})}return this};pv.Mark.prototype.addMargins=function(margins){var all=def.get(margins,'all',0);this.addMargin('left',def.get(margins,'left',all));this.addMargin('right',def.get(margins,'right',all));this.addMargin('top',def.get(margins,'top',all));this.addMargin('bottom',def.get(margins,'bottom',all));return this};pv.Mark.prototype.eachInstanceWithData=function(fun,ctx){this.eachInstance(function(scenes,index,t){if(scenes.mark.sign&&scenes[index].data){fun.call(ctx,scenes,index,t)}})};pv.Transform.prototype.transformHPosition=function(left){return this.x+(this.k*left)};pv.Transform.prototype.transformVPosition=function(top){return this.y+(this.k*top)};pv.Transform.prototype.transformLength=function(length){return this.k*length};var Size=def.type('pvc.Size').init(function(width,height){if(arguments.length===1){if(width!=null){this.setSize(width)}}else{if(width!=null){this.width=width}if(height!=null){this.height=height}}}).add({stringify:function(out,remLevels,keyArgs){return pvc.stringifyRecursive(out,def.copyOwn(this),remLevels,keyArgs)},setSize:function(size,keyArgs){if(typeof size==='string'){var comps=size.split(/\s+/).map(function(comp){return pvc.PercentValue.parse(comp)});switch(comps.length){case 1:this.set(def.get(keyArgs,'singleProp','all'),comps[0]);return this;case 2:this.set('width',comps[0]);this.set('height',comps[1]);return this;case 0:return this}}else if(typeof size==='number'){this.set(def.get(keyArgs,'singleProp','all'),size);return this}else if(typeof size==='object'){if(size instanceof pvc.PercentValue){this.set(def.get(keyArgs,'singleProp','all'),size)}else{this.set('all',size.all);for(var p in size){if(p!=='all'){this.set(p,size[p])}}}return this}if(pvc.debug){pvc.log("Invalid 'size' value: "+pvc.stringify(size))}return this},set:function(prop,value){if(value!=null&&(prop==='all'||def.hasOwn(pvc.Size.namesSet,prop))){value=pvc.PercentValue.parse(value);if(value!=null){if(prop==='all'){pvc.Size.names.forEach(function(p){this[p]=value},this)}else{this[prop]=value}}}return this},clone:function(){return new Size(this.width,this.height)},intersect:function(size){return new Size(Math.min(this.width,size.width),Math.min(this.height,size.height))},resolve:function(refSize){var size={};pvc.Size.names.forEach(function(length){var lengthValue=this[length];if(lengthValue!=null){if(typeof(lengthValue)==='number'){size[length]=lengthValue}else if(refSize){var refLength=refSize[length];if(refLength!=null){size[length]=lengthValue.resolve(refLength)}}}},this);return size}});pvc.Size.names=['width','height'];pvc.Size.namesSet=pv.dict(pvc.Size.names,def.retTrue);pvc.Size.toOrtho=function(value,anchor){if(value!=null){var a_ol;if(anchor){a_ol=pvc.BasePanel.orthogonalLength[anchor]}value=pvc.Size.to(value,{singleProp:a_ol});if(anchor){delete value[pvc.BasePanel.oppositeLength[a_ol]]}}return value};pvc.Size.to=function(v,keyArgs){if(v!=null&&!(v instanceof Size)){v=new Size().setSize(v,keyArgs)}return v};var Offset=def.type('pvc.Offset').init(function(x,y){if(arguments.length===1){if(x!=null){this.setOffset(x)}}else{if(x!=null){this.x=x}if(y!=null){this.y=y}}}).add({stringify:function(out,remLevels,keyArgs){return pvc.stringifyRecursive(out,def.copyOwn(this),remLevels,keyArgs)},setOffset:function(offset,keyArgs){if(typeof offset==='string'){var comps=offset.split(/\s+/).map(function(comp){return pvc.PercentValue.parse(comp)});switch(comps.length){case 1:this.set(def.get(keyArgs,'singleProp','all'),comps[0]);return this;case 2:this.set('x',comps[0]);this.set('y',comps[1]);return this;case 0:return this}}else if(typeof offset==='number'){this.set(def.get(keyArgs,'singleProp','all'),offset);return this}else if(typeof offset==='object'){this.set('all',offset.all);for(var p in offset){if(p!=='all'){this.set(p,offset[p])}}return this}if(pvc.debug){pvc.log("Invalid 'offset' value: "+pvc.stringify(offset))}return this},set:function(prop,value){if(value!=null&&def.hasOwn(pvc.Offset.namesSet,prop)){value=pvc.PercentValue.parse(value);if(value!=null){if(prop==='all'){pvc.Offset.names.forEach(function(p){this[p]=value},this)}else{this[prop]=value}}}},resolve:function(refSize){var offset={};pvc.Size.names.forEach(function(length){var offsetProp=pvc.Offset.namesSizeToOffset[length];var offsetValue=this[offsetProp];if(offsetValue!=null){if(typeof(offsetValue)==='number'){offset[offsetProp]=offsetValue}else if(refSize){var refLength=refSize[length];if(refLength!=null){offset[offsetProp]=offsetValue.resolve(refLength)}}}},this);return offset}});pvc.Offset.names=['x','y'];pvc.Offset.namesSet=pv.dict(pvc.Offset.names,def.retTrue);pvc.Offset.namesSizeToOffset={width:'x',height:'y'};pvc.Offset.namesSidesToOffset={left:'x',right:'x',top:'y',bottom:'y'};pvc.Offset.as=function(v){if(v!=null&&!(v instanceof Offset)){v=new Offset().setOffset(v)}return v}}());(function($){$.support.svg=$.support.svg||document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}(jQuery));
pvc.text={getFitInfo:function(w,h,text,font,diagMargin){if(text===''){return{h:true,v:true,d:true}}var len=pv.Text.measure(text,font).width;return{h:len<=w,v:len<=h,d:len<=Math.sqrt(w*w+h*h)-diagMargin}},trimToWidthB:function(len,text,font,trimTerminator,before){len-=pv.Text.measure(trimTerminator,font).width;return pvc.text.trimToWidth(len,text,font,trimTerminator,before)},trimToWidth:function(len,text,font,trimTerminator,before){if(text===''){return text}var textLen=pv.Text.measure(text,font).width;if(textLen<=len){return text}if(textLen>len*1.5){return pvc.text.trimToWidthBin(len,text,font,trimTerminator,before)}while(textLen>len){text=before?text.slice(1):text.slice(0,text.length-1);textLen=pv.Text.measure(text,font).width}return before?(trimTerminator+text):(text+trimTerminator)},trimToWidthBin:function(len,text,font,trimTerminator,before){var ilen=text.length,high=ilen-2,low=0,mid,textLen;while(low<=high&&high>0){mid=Math.ceil((low+high)/2);var textMid=before?text.slice(ilen-mid):text.slice(0,mid);textLen=pv.Text.measure(textMid,font).width;if(textLen>len){high=mid-1}else if(pv.Text.measure(before?text.slice(ilen-mid-1):text.slice(0,mid+1),font).width<len){low=mid+1}else{return before?(trimTerminator+textMid):(textMid+trimTerminator)}}return before?(trimTerminator+text.slice(ilen-high)):(text.slice(0,high)+trimTerminator)},justify:function(text,lineWidth,font){var lines=[];if(lineWidth<pv.Text.measure('a',font).width){return lines}var words=(text||'').split(/\s+/);var line="";while(words.length){var word=words.shift();if(word){var nextLine=line?(line+" "+word):word;if(pv.Text.measure(nextLine,font).width>lineWidth){if(line){lines.push(line)}line=word}else{line=nextLine}}}if(line){lines.push(line)}return lines},getLabelBBox:function(textWidth,textHeight,align,baseline,angle,margin){var polygon=pv.Label.getPolygon(textWidth,textHeight,align,baseline,angle,margin);var bbox=polygon.bbox();bbox.source=polygon;bbox.sourceAngle=angle;bbox.sourceAlign=align;bbox.sourceTextWidth=textWidth;return bbox}};
def.scope(function(){pvc.color={scale:colorScale,scales:colorScales};function colorScales(keyArgs){keyArgs||def.fail.argumentRequired('keyArgs');var type=keyArgs.type||def.fail.argumentRequired('keyArgs.type');switch(type){case'linear':return new pvc.color.LinearScalesBuild(keyArgs).buildMap();case'discrete':return new pvc.color.DiscreteScalesBuild(keyArgs).buildMap();case'normal':return new pvc.color.NormalScalesBuild(keyArgs).buildMap()}throw def.error.argumentInvalid('scaleType',"Unexistent scale type '{0}'.",[type])}function colorScale(keyArgs){keyArgs||def.fail.argumentRequired('keyArgs');var type=keyArgs.type||def.fail.argumentRequired('keyArgs.type');switch(type){case'linear':return new pvc.color.LinearScalesBuild(keyArgs).build();case'discrete':return new pvc.color.DiscreteScalesBuild(keyArgs).build();case'normal':return new pvc.color.NormalScalesBuild(keyArgs).build()}throw def.error.argumentInvalid('scaleType',"Unexistent scale type '{0}'.",[type])}def.type('pvc.color.ScalesBuild').init(function(keyArgs){this.keyArgs=keyArgs;this.data=keyArgs.data||def.fail.argumentRequired('keyArgs.data');this.domainDimName=keyArgs.colorDimension||def.fail.argumentRequired('keyArgs.colorDimension');this.domainDim=this.data.dimensions(this.domainDimName);var dimType=this.domainDim.type;if(!dimType.isComparable){this.domainComparer=null;pvc.log("Color value dimension should be comparable. Generated color scale may be invalid.")}else{this.domainComparer=function(a,b){return dimType.compare(a,b)}}this.nullRangeValue=keyArgs.colorNull?pv.color(keyArgs.colorNull):pv.Color.transparent;this.domainRangeCountDif=0}).add({build:function(){this.range=this._getRange();this.desiredDomainCount=this.range.length+this.domainRangeCountDif;var domain=this._getDomain();return this._createScale(domain)},buildMap:function(){this.range=this._getRange();this.desiredDomainCount=this.range.length+this.domainRangeCountDif;var createCategoryScale;if(this.keyArgs.normPerBaseCategory){createCategoryScale=function(leafData){var domain=this._ensureDomain(null,false,leafData);return this._createScale(domain)}}else{var domain=this._getDomain(),scale=this._createScale(domain);createCategoryScale=def.fun.constant(scale)}return this._createCategoryScalesMap(createCategoryScale)},_createScale:def.method({isAbstract:true}),_createCategoryScalesMap:function(createCategoryScale){return this.data.children().object({name:function(leafData){return leafData.absKey},value:createCategoryScale,context:this})},_getRange:function(){var keyArgs=this.keyArgs,range=keyArgs.colors||['red','yellow','green'];if(keyArgs.colorMin!=null&&keyArgs.colorMax!=null){range=[keyArgs.colorMin,keyArgs.colorMax]}else if(keyArgs.colorMin!=null){range.unshift(keyArgs.colorMin)}else if(keyArgs.colorMax!=null){range.push(keyArgs.colorMax)}return range.map(function(c){return pv.color(c)})},_getDataExtent:function(data){var extent=data.dimensions(this.domainDimName).extent({visible:true});if(!extent){return null}var min=extent.min.value,max=extent.max.value;if(max==min){if(max>=1){min=max-1}else{max=min+1}}return{min:min,max:max}},_getDomain:function(){var domain=this.keyArgs.colorDomain;if(domain!=null){if(this.domainComparer){domain.sort(this.domainComparer)}if(domain.length>this.desiredDomainCount){domain=domain.slice(0,this.desiredDomainCount)}}else{domain=[]}return this._ensureDomain(domain,true,this.data)},_ensureDomain:function(domain,doDomainPadding,data){var extent;if(domain&&doDomainPadding){var domainPointsMissing=this.desiredDomainCount-domain.length;if(domainPointsMissing>0){extent=this._getDataExtent(data);if(extent){switch(domainPointsMissing){case 1:if(this.domainComparer){def.array.insert(domain,extent.max,this.domainComparer)}else{domain.push(extent.max)}break;case 2:if(this.domainComparer){def.array.insert(domain,extent.min,this.domainComparer);def.array.insert(domain,extent.max,this.domainComparer)}else{domain.unshift(extent.min);domain.push(extent.max)}break;default:if(pvc.debug>=2){pvc.log("Ignoring option 'colorDomain' due to unsupported length."+def.format(" Should have '{0}', but instead has '{1}'.",[this.desiredDomainCount,domain.length]))}domain=null}}}}if(!domain){extent||(extent=this._getDataExtent(data));if(extent){var min=extent.min,max=extent.max;var step=(max-min)/(this.desiredDomainCount-1);domain=pv.range(min,max+step,step)}}return domain}});def.type('pvc.color.LinearScalesBuild',pvc.color.ScalesBuild).add({_createScale:function(domain){var scale=pv.Scale.linear();if(domain){scale.domain.apply(scale,domain)}scale.range.apply(scale,this.range);return scale}});def.type('pvc.color.DiscreteScalesBuild',pvc.color.ScalesBuild).init(function(keyArgs){this.base(keyArgs);this.domainRangeCountDif=1}).add({_createScale:function(domain){var Dl=domain.length-1,range=this.range,nullRangeValue=this.nullRangeValue,Rl=range.length-1;function scale(val){if(val==null){return nullRangeValue}for(var i=0;i<Dl;i++){if(val<=domain[i+1]){return range[i]}}return range[Rl]}def.copy(scale,pv.Scale.common);return scale}})});
def.space('pvc.trends',function(trends){var _trends={};def.set(trends,'define',function(type,trendSpec){type||def.fail.argumentRequired('type');trendSpec||def.fail.argumentRequired('trendSpec');def.object.is(trendSpec)||def.fail.argumentInvalid('trendSpec',"Must be a trend specification object.");if(pvc.debug>=2&&def.hasOwn(_trends,type)){pvc.log(def.format("[WARNING] A trend type with the name '{0}' is already defined.",[type]))}var label=trendSpec.label||def.fail.argumentRequired('trendSpec.label');var model=trendSpec.model||def.fail.argumentRequired('trendSpec.model');def.fun.is(model)||def.fail.argumentInvalid('trendSpec.mode',"Must be a function.");var trendInfo={dataPartAtom:{v:'trend',f:label},type:type,label:label,model:model};_trends[type]=trendInfo},'get',function(type){type||def.fail.argumentRequired('type');return def.getOwn(_trends,type)||def.fail.operationInvalid("Undefined trend type '{0}'.",[type])},'has',function(type){return def.hasOwn(_trends,type)},'types',function(){return def.ownKeys(_trends)});trends.define('linear',{label:'Linear trend',model:function(options){var rows=def.get(options,'rows');var funX=def.get(options,'x');var funY=def.get(options,'y');var i=0;var N=0;var sumX=0;var sumY=0;var sumXY=0;var sumXX=0;var parseNum=function(value){return value!=null?(+value):NaN};while(rows.next()){var row=rows.item;var x=funX?parseNum(funX(row)):i;if(!isNaN(x)){var y=parseNum(funY(row));if(!isNaN(y)){N++;sumX+=x;sumY+=y;sumXY+=x*y;sumXX+=x*x}}i++}var alpha,beta;if(N>=2){var avgX=sumX/N;var avgY=sumY/N;var avgXY=sumXY/N;var avgXX=sumXX/N;var den=(avgXX-avgX*avgX);if(den===0){beta=0}else{beta=(avgXY-(avgX*avgY))/den}alpha=avgY-beta*avgX;return{alpha:alpha,beta:beta,reset:def.noop,sample:function(x){return alpha+beta*(+x)}}}}});trends.define('moving-average',{label:'Moving average',model:function(options){var W=Math.max(+(def.get(options,'periods')||3),2);var sum=0;var avgValues=[];return{reset:function(){sum=0;avgValues.length=0},sample:function(x,y,i){var L=W;if(y!=null){avgValues.unshift(y);sum+=y;L=avgValues.length;if(L>W){sum-=avgValues.pop();L=W}}return sum/L}}}});trends.define('weighted-moving-average',{label:'Weighted Moving average',model:function(options){var W=Math.max(+(def.get(options,'periods')||3),2);var sum=0;var numer=0;var avgValues=[];var L=0;var denom=0;return{reset:function(){sum=numer=denom=L=0;avgValues.length=0},sample:function(x,y){if(y!=null){if(L<W){avgValues.push(y);L++;denom+=L;numer+=L*y;sum+=y}else{numer+=(L*y)-sum;sum+=y-avgValues[0];for(var j=1;j<W;j++){avgValues[j-1]=avgValues[j]}avgValues[W-1]=y}}return numer/denom}}}})});
def.scope(function(){function options(specs,context){specs||def.fail.argumentRequired('specs');var _infos={};def.each(specs,function(spec,name){var info=new OptionInfo(name,option,context,spec);_infos[info.name]=info});function resolve(name){var info=def.getOwn(_infos,name)||def.fail.operationInvalid("Undefined option '{0}'",[name]);return info.resolve()}function option(name,noDefault){var info=resolve(name);return noDefault&&!info.isSpecified?undefined:info.value}function isSpecified(name){return resolve(name).isSpecified}function specified(name){return option(name,true)}function isDefined(name){return def.hasOwn(_infos,name)}function specify(opts){return set(opts,false)}function defaults(opts){return set(opts,true)}function getDefaultValue(name){return resolve(name)._defaultValue}function set(opts,isDefault){for(var name in opts){var info=def.getOwn(_infos,name);if(info){var value=opts[name];if(value!==undefined){info.set(value,isDefault)}}}return option}option.option=option;option.specified=specified;option.isSpecified=isSpecified;option.isDefined=isDefined;option.defaultValue=getDefaultValue;option.specify=specify;option.defaults=defaults;return option}function resolvers(list){return function(optionInfo){for(var i=0,L=list.length;i<L;i++){var m=list[i];if(def.string.is(m)){m=this[m]}if(m.call(this,optionInfo)===true){return true}}}}function constantResolver(value,op){return function(optionInfo){optionInfo.specify(value);return true}}function specifyResolver(fun,op){return function(optionInfo){var value=fun.call(this,optionInfo);if(value!==undefined){optionInfo.specify(value);return true}}}function defaultResolver(fun){return function(optionInfo){var value=fun.call(this,optionInfo);if(value!==undefined){optionInfo.defaultValue(value);return true}}}options.resolvers=resolvers;options.constant=constantResolver;options.specify=specifyResolver;options.defaultValue=defaultResolver;pvc.options=options;var OptionInfo=def.type().init(function(name,option,context,spec){this.name=name;this._context=context;this.option=option;this._cast=def.get(spec,'cast');var value=def.get(spec,'value');if(value!==undefined){this._defaultValue=this.value=value}this.resolveCore=def.get(spec,'resolve');if(!this.resolveCore){this.isResolved=true}var getDefault=def.get(spec,'getDefault');if(getDefault){this._getDefault=getDefault}var data=def.get(spec,'data');if(data!=null){this.data=data}this.alias=def.array.to(def.get(spec,'alias'))}).add({isSpecified:false,isResolved:false,value:undefined,_defaultValue:undefined,resolve:function(){if(!this.isResolved){this.isResolved=true;var resolve=this._getFunProp('resolveCore');resolve.call(this._context,this);if(this.value==null){var getDefault=this._getFunProp('_getDefault');if(getDefault){var value=this.cast(getDefault.call(this._context,this));if(value!=null){delete this.isSpecified;this.value=this._defaultValue=value}}}}return this},specify:function(value){return this.set(value,false)},defaultValue:function(defaultValue){if(defaultValue!==undefined){this.set(defaultValue,true)}return this._defaultValue},cast:function(value){if(value!=null){var cast=this._getFunProp('_cast');if(cast){value=cast.call(this._context,value,this)}}return value},dynDefault:function(){var dynDefault=this._getFunProp('_dynDefault');if(dynDefault){return this.cast(dynDefault.call(this._context,this))}},set:function(value,isDefault){if(value!=null){value=this.cast(value)}if(value==null){value=this.dynDefault();if(value!=null){isDefault=true}}if(!isDefault){this.isSpecified=true;this.isResolved=true;this.value=value}else{this._defaultValue=value;if(!this.isSpecified){this.value=value}}return this},_getFunProp:function(name){var fun=this[name];if(fun){var context=this._context;if(context&&def.string.is(fun)){fun=context[fun]}}return fun}})});
def.global.NoDataException=function(){};pvc.data={visibleKeyArgs:{visible:true}};function data_disposeChildList(list,parentProp){if(list){list.forEach(function(child){if(parentProp){child[parentProp]=null}child.dispose()});list.length=0}}function data_addColChild(parent,childrenProp,child,parentProp,index){(child&&!child[parentProp])||def.assert("Must not have a '"+parentProp+"'.");child[parentProp]=parent;var col=(parent[childrenProp]||(parent[childrenProp]=[]));if(index==null||index>=col.length){col.push(child)}else{col.splice(index,0,child)}}function data_removeColChild(parent,childrenProp,child,parentProp){(child&&(!child[parentProp]||child[parentProp]===parent))||def.assert("Not a child");var children=parent[childrenProp];if(children){var index=children.indexOf(child);if(index>=0){def.array.removeAt(children,index)}}child[parentProp]=null}
def.type('pvc.data.DimensionType').init(function(complexType,name,keyArgs){this.complexType=complexType;this.name=name;this.label=def.get(keyArgs,'label')||pvc.buildTitleFromName(name);var groupAndLevel=pvc.splitIndexedId(name);this.group=groupAndLevel[0];this.groupLevel=def.nullyTo(groupAndLevel[1],0);if(this.label.indexOf('{')>=0){this.label=def.format(this.label,[this.groupLevel+1])}this.playedVisualRoles=new def.Map();this.isHidden=!!def.get(keyArgs,'isHidden');var valueType=def.get(keyArgs,'valueType')||null;var valueTypeName=pvc.data.DimensionType.valueTypeName(valueType);var cast=def.getOwn(pvc.data.DimensionType.cast,valueTypeName,null);this.valueType=valueType;this.valueTypeName=valueTypeName;this.cast=cast;this.isDiscreteValueType=(this.valueType!==Number&&this.valueType!==Date);this.isDiscrete=def.get(keyArgs,'isDiscrete');if(this.isDiscrete==null){this.isDiscrete=this.isDiscreteValueType}else{this.isDiscrete=!!this.isDiscrete;if(!this.isDiscrete&&this.isDiscreteValueType){throw def.error.argumentInvalid('isDiscrete',"The only supported continuous value types are Number and Date.")}}this._converter=def.get(keyArgs,'converter')||null;if(!this._converter){var rawFormat=def.get(keyArgs,'rawFormat');if(rawFormat){switch(this.valueType){case Date:this._converter=pv.Format.createParser(pv.Format.date(rawFormat));break}}}this._key=def.get(keyArgs,'key')||null;this._comparer=def.get(keyArgs,'comparer');if(this._comparer===undefined){switch(this.valueType){case Number:case Date:this._comparer=def.compare;break;default:this._comparer=null}}this.isComparable=this._comparer!=null;this._formatter=def.get(keyArgs,'formatter')||null;if(!this._formatter){switch(this.valueType){case Number:this._formatter=pv.Format.createFormatter(pv.Format.number().fractionDigits(0,2));break;case Date:var format=def.get(keyArgs,'format');if(!format){format=def.get(keyArgs,'rawFormat');if(format){format=format.replace(/-/g,"/")}}if(!format){format="%Y/%m/%d"}this._formatter=pv.Format.createFormatter(pv.Format.date(format));break}}}).add({isCalculated:false,compare:function(a,b){if(a==null){if(b==null){return 0}return-1}else if(b==null){return 1}return this._comparer.call(null,a,b)},comparer:function(reverse){if(!this.isComparable){return null}var me=this;if(reverse){return this._reverseComparer||(this._reverseComparer=function(a,b){return me.compare(b,a)})}return this._directComparer||(this._directComparer=function(a,b){return me.compare(a,b)})},atomComparer:function(reverse){if(reverse){return this._reverseAtomComparer||(this._reverseAtomComparer=this._createReverseAtomComparer())}return this._directAtomComparer||(this._directAtomComparer=this._createDirectAtomComparer())},_toDiscrete:function(){this.isDiscrete=true},_toCalculated:function(){this.isCalculated=true},_createReverseAtomComparer:function(){if(!this.isComparable){return atom_idComparerReverse}var me=this;function reverseAtomComparer(a,b){if(a===b){return 0}return me.compare(b.value,a.value)}return reverseAtomComparer},_createDirectAtomComparer:function(){if(!this.isComparable){return atom_idComparer}var me=this;function directAtomComparer(a,b){if(a===b){return 0}return me.compare(a.value,b.value)}return directAtomComparer},formatter:function(){return this._formatter},converter:function(){return this._converter},playingPercentVisualRole:function(){return def.query(this.playedVisualRoles.values()).any(function(visualRole){return visualRole.isPercent})}});pvc.data.DimensionType.cast={'Date':function(value){return value instanceof Date?value:new Date(value)},'Number':function(value){value=Number(value);return isNaN(value)?null:value},'String':String,'Boolean':Boolean,'Object':Object,'Any':null};pvc.data.DimensionType.dimensionGroupName=function(dimName){return dimName.replace(/^(.*?)(\d*)$/,"$1")};pvc.data.DimensionType.valueTypeName=function(valueType){if(valueType==null){return"Any"}switch(valueType){case Boolean:return'Boolean';case Number:return'Number';case String:return'String';case Object:return'Object';case Date:return'Date';default:throw def.error.argumentInvalid('valueType',"Invalid valueType function: '{0}'.",[valueType])}};pvc.data.DimensionType.extendSpec=function(dimName,dimSpec,keyArgs){var dimGroup=pvc.data.DimensionType.dimensionGroupName(dimName),userDimGroupsSpec=def.get(keyArgs,'dimensionGroups');if(userDimGroupsSpec){var groupDimSpec=userDimGroupsSpec[dimGroup];if(groupDimSpec){dimSpec=def.create(groupDimSpec,dimSpec)}}if(!dimSpec){dimSpec={}}switch(dimGroup){case'category':var isCategoryTimeSeries=def.get(keyArgs,'isCategoryTimeSeries',false);if(isCategoryTimeSeries){if(dimSpec.valueType===undefined){dimSpec.valueType=Date}}break;case'value':if(dimSpec.valueType===undefined){dimSpec.valueType=Number}if(dimSpec.valueType===Number){if(dimSpec.formatter===undefined&&!dimSpec.format){dimSpec.formatter=def.get(keyArgs,'valueNumberFormatter')}}break}if(dimSpec.converter===undefined&&dimSpec.valueType===Date&&!dimSpec.rawFormat){dimSpec.rawFormat=def.get(keyArgs,'timeSeriesFormat')}return dimSpec};function dimType_addVisualRole(visualRole){this.playedVisualRoles.set(visualRole.name,visualRole);compType_dimensionRolesChanged.call(this.type,this)}function dimType_removeVisualRole(visualRole){this.playedVisualRoles.rem(visualRole.name);compType_dimensionRolesChanged.call(this.type,this)}
def.type('pvc.data.ComplexType').init(function(dimTypeSpecs){this._dims={};this._dimsList=[];this._dimsNames=[];this._calculations=[];this._calculatedDimNames={};this._dimsIndexByName=null;this._dimsByGroup={};this._dimsNamesByGroup={};if(dimTypeSpecs){for(var name in dimTypeSpecs){this.addDimension(name,dimTypeSpecs[name])}}}).add({describe:function(){var out=["COMPLEX TYPE INFORMATION",pvc.logSeparator];this._dimsList.forEach(function(type){var features=[];features.push(type.valueTypeName);if(type.isComparable){features.push("comparable")}if(!type.isDiscrete){features.push("continuous")}if(type.isHidden){features.push("hidden")}out.push("  "+type.name+" ("+features.join(', ')+")")});return out.join("\n")},dimensions:function(name,keyArgs){if(name==null){return this._dims}var dimType=def.getOwn(this._dims,name,null);if(!dimType&&def.get(keyArgs,'assertExists',true)){throw def.error.argumentInvalid('name',"Undefined dimension '{0}'",[name])}return dimType},dimensionsList:function(){return this._dimsList},calculatedDimensionsList:function(){return this._calcDimsList},dimensionsNames:function(){return this._dimsNames},groupDimensions:function(group,keyArgs){var dims=def.getOwn(this._dimsByGroup,group);if(!dims&&def.get(keyArgs,'assertExists',true)){throw def.error.operationInvalid("There is no dimension type group with name '{0}'.",[group])}return dims},groupDimensionsNames:function(group,keyArgs){var dimNames=def.getOwn(this._dimsNamesByGroup,group);if(!dimNames&&def.get(keyArgs,'assertExists',true)){throw def.error.operationInvalid("There is no dimension type group with name '{0}'.",[group])}return dimNames},addDimension:function(name,dimTypeSpec){name||def.fail.argumentRequired('name');!def.hasOwn(this._dims,name)||def.fail.operationInvalid("A dimension type with name '{0}' is already defined.",[name]);var dimension=new pvc.data.DimensionType(this,name,dimTypeSpec);this._dims[name]=dimension;this._dimsIndexByName=null;var group=dimension.group;var groupLevel;if(group){var groupDims=def.getOwn(this._dimsByGroup,group),groupDimsNames;if(!groupDims){groupDims=this._dimsByGroup[group]=[];groupDimsNames=this._dimsNamesByGroup[group]=[]}else{groupDimsNames=this._dimsNamesByGroup[group]}groupLevel=def.array.insert(groupDimsNames,name,def.compare);groupLevel=~groupLevel;def.array.insertAt(groupDims,groupLevel,dimension)}var index;var L=this._dimsList.length;if(!group){index=L}else{groupLevel=dimension.groupLevel;for(var i=0;i<L;i++){var dim=this._dimsList[i];if(dim.group===group){if(dim.groupLevel>groupLevel){index=i;break}index=i+1}}if(index==null){index=L}}def.array.insertAt(this._dimsList,index,dimension);def.array.insertAt(this._dimsNames,index,name);if(dimension._calculate){index=def.array.binarySearch(this._calcDimsList,dimension._calculationOrder,def.compare,function(dimType){return dimType._calculationOrder});if(index>=0){index++}else{index=~index}def.array.insertAt(this._calcDimsList,index,dimension)}this._isPctRoleDimTypeMap=null;return dimension},addCalculation:function(calcSpec,dimsOptions){calcSpec||def.fail.argumentRequired('calcSpec');var calculation=calcSpec.calculation||def.fail.argumentRequired('calculations[i].calculation');var dimNames=calcSpec.names;if(typeof dimNames==='string'){dimNames=dimNames.split(/\s*\,\s*/)}else{dimNames=def.array.as(dimNames)}if(dimNames&&dimNames.length){var calcDimNames=this._calculatedDimNames;dimNames.forEach(function(name){if(name){name=name.replace(/^\s*(.+?)\s*$/,"$1");!def.hasOwn(calcDimNames,name)||def.fail.argumentInvalid('calculations[i].names',"Dimension name '{0}' is already being calculated.",[name]);var dimType=this._dims[name];if(!dimType){var dimSpec=pvc.data.DimensionType.extendSpec(name,null,dimsOptions);this.addDimension(name,dimSpec)}calcDimNames[name]=true;dimType._toCalculated()}},this)}this._calculations.push(calculation)},isCalculated:function(dimName){return def.hasOwn(this._calculatedDimNames,dimName)},_calculate:function(complex){var calcs=this._calculations;if(calcs.length){var valuesByName={};calcs.forEach(function(calc){calc(complex,valuesByName)});return valuesByName}},getPlayingPercentVisualRoleDimensionMap:function(){var map=this._isPctRoleDimTypeMap;if(!map){map=this._isPctRoleDimTypeMap=new def.Map(def.query(def.own(this._dims)).where(function(dimType){return dimType.playingPercentVisualRole()}).object({name:function(dimType){return dimType.name}}))}return map},sortDimensionNames:function(dims,nameKey){var dimsIndexByName=this._dimsIndexByName;if(!dimsIndexByName){dimsIndexByName=def.query(this._dimsList).object({name:function(dim){return dim.name},value:function(dim,index){return index}});this._dimsIndexByName=dimsIndexByName}dims.sort(function(da,db){return def.compare(dimsIndexByName[nameKey?nameKey(da):da],dimsIndexByName[nameKey?nameKey(db):db])});return dims}});function compType_dimensionRolesChanged(dimType){this._isPctRoleDimTypeMap=null}
def.type('pvc.data.ComplexTypeProject').init(function(dimGroupSpecs){this._dims={};this._dimList=[];this._dimGroupsDims={};this._dimGroupSpecs=dimGroupSpecs||{};this._calcList=[]}).add({_ensureDim:function(name){name||def.fail.argumentInvalid('name',"Invalid dimension name '{0}'.",[name]);var info=def.getOwn(this._dims,name);if(!info){info=this._dims[name]=this._createDim(name);this._dimList.push(info);var groupDimsNames=def.array.lazy(this._dimGroupsDims,info.groupName);def.array.insert(groupDimsNames,name,def.compare)}return info},hasDim:function(name){return def.hasOwn(this._dims,name)},setDim:function(name,spec){var _=this._ensureDim(name).spec;if(spec){def.copy(_,spec)}return this},setDimDefaults:function(name,spec){def.setUDefaults(this._ensureDim(name).spec,spec);return this},_createDim:function(name,spec){var dimGroupName=pvc.data.DimensionType.dimensionGroupName(name);var dimGroupSpec=this._dimGroupSpecs[dimGroupName];if(dimGroupSpec){spec=def.create(dimGroupSpec,spec)}return{name:name,groupName:dimGroupName,spec:spec||{}}},readDim:function(name){var info=this._ensureDim(name);if(info.isRead){throw def.error.operationInvalid("Dimension '{0}' already is the target of a reader.",[name])}if(info.isCalc){throw def.error.operationInvalid("Dimension '{0}' is being calculated, so it cannot be the target of a reader.",[name])}info.isRead=true},calcDim:function(name){var info=this._ensureDim(name);if(info.isCalc){throw def.error.operationInvalid("Dimension '{0}' already is being calculated.",[name])}if(info.isRead){throw def.error.operationInvalid("Dimension '{0}' is the target of a reader, so it cannot be calculated.",[name])}info.isCalc=true},isReadOrCalc:function(name){if(name){var info=def.getOwn(this._dims,name);if(info){return info.isRead||info.isCalc}}return false},groupDimensionsNames:function(groupDimName){return this._dimGroupsDims[groupDimName]},setCalc:function(calcSpec){calcSpec||def.fail.argumentRequired('calculations[i]');calcSpec.calculation||def.fail.argumentRequired('calculations[i].calculation');var dimNames=calcSpec.names;if(typeof dimNames==='string'){dimNames=dimNames.split(/\s*\,\s*/)}else{dimNames=def.array.as(dimNames)}if(dimNames&&dimNames.length){dimNames.forEach(this.calcDim,this)}this._calcList.push(calcSpec)},configureComplexType:function(complexType,translOptions){this._dimList.forEach(function(dimInfo){var dimName=dimInfo.name;var spec=dimInfo.spec;spec=pvc.data.DimensionType.extendSpec(dimName,spec,translOptions);complexType.addDimension(dimName,spec)});this._calcList.forEach(function(calcSpec){complexType.addCalculation(calcSpec)})}});
def.type('pvc.data.TranslationOper').init(function(chart,complexTypeProj,source,metadata,options){this.chart=chart;this.complexTypeProj=complexTypeProj;this.source=source;this.metadata=metadata||{};this.options=options||{};this._initType();if(pvc.debug>=4){this._logItems=true;this._logItemCount=0}}).add({_logItems:false,logSource:def.method({isAbstract:true}),virtualItemSize:function(){return this.metadata.length},freeVirtualItemSize:function(){return this.virtualItemSize()-this._userUsedIndexesCount},defReader:function(dimReaderSpec){dimReaderSpec||def.fail.argumentRequired('readerSpec');var dimNames;if(typeof dimReaderSpec==='string'){dimNames=dimReaderSpec}else{dimNames=dimReaderSpec.names}if(typeof dimNames==='string'){dimNames=dimNames.split(/\s*\,\s*/)}else{dimNames=def.array.as(dimNames)}var indexes=def.array.as(dimReaderSpec.indexes);if(indexes){indexes.forEach(this._userUseIndex,this)}var hasDims=!!(dimNames&&dimNames.length);var reader=dimReaderSpec.reader;if(!reader){if(hasDims){return this._userCreateReaders(dimNames,indexes)}}else{hasDims||def.fail.argumentRequired('reader.names',"Required argument when a reader function is specified.");this._userRead(reader,dimNames)}return indexes},configureType:function(){this._configureTypeCore()},_configureTypeCore:def.method({isAbstract:true}),_initType:function(){this._userDimsReaders=[];this._userDimsReadersByDim={};this._userItem=[];this._userUsedIndexes={};this._userUsedIndexesCount=0;var userDimReaders=this.options.readers;if(userDimReaders){userDimReaders.forEach(this.defReader,this)}var multiChartIndexes=pvc.parseDistinctIndexArray(this.options.multiChartIndexes);if(multiChartIndexes){this._multiChartIndexes=this.defReader({names:'multiChart',indexes:multiChartIndexes})}},_userUseIndex:function(index){index=+index;(index>=0)||def.fail.argumentInvalid('index',"Invalid reader index: '{0}'.",[index]);!def.hasOwn(this._userUsedIndexes,index)||def.fail.argumentInvalid('index',"Virtual item index '{0}' is already assigned.",[index]);this._userUsedIndexes[index]=true;this._userUsedIndexesCount++;this._userItem[index]=true;return index},_userCreateReaders:function(dimNames,indexes){if(!indexes){indexes=[]}else{indexes.forEach(function(index,j){indexes[j]=+index})}var I=indexes.length,N=dimNames.length,dimName;if(N>I){var nextIndex=I>0?(indexes[I-1]+1):0;do{nextIndex=this._nextAvailableItemIndex(nextIndex);indexes[I]=nextIndex;this._userUseIndex(nextIndex);I++}while(N>I)}var L=(I===N)?N:(N-1);for(var n=0;n<L;n++){dimName=dimNames[n];this._userRead(this._propGet(dimName,indexes[n]),dimName)}if(L<N){var splitGroupName=pvc.splitIndexedId(dimNames[N-1]),groupName=splitGroupName[0],level=def.nullyTo(splitGroupName[1],0);for(var i=L;i<I;i++,level++){dimName=pvc.buildIndexedId(groupName,level);this._userRead(this._propGet(dimName,indexes[i]),dimName)}}return indexes},_userRead:function(reader,dimNames){def.fun.is(reader)||def.fail.argumentInvalid('reader',"Reader must be a function.");if(def.array.is(dimNames)){dimNames.forEach(function(name){this._readDim(name,reader)},this)}else{this._readDim(dimNames,reader)}this._userDimsReaders.push(reader)},_readDim:function(name,reader){this.complexTypeProj.readDim(name);this._userDimsReadersByDim[name]=reader},execute:function(data){this.data=data;return this._executeCore()},_executeCore:function(){var dimsReaders=this._getDimensionsReaders();return def.query(this._getItems()).select(function(item){return this._readItem(item,dimsReaders)},this)},_getItems:function(){return this.source},_getDimensionsReaders:function(){return this._userDimsReaders},_readItem:function(item,dimsReaders){var logItem=this._logItems;if(logItem){var logItemCount=this._logItemCount;if(logItemCount<10){pvc.log('virtual item ['+this._logItemCount+']: '+pvc.stringify(item));this._logItemCount++}else{pvc.log('...');logItem=this._logItems=false}}var r=0,R=dimsReaders.length,a=0,data=this.data,valuesByDimName={};while(r<R){dimsReaders[r++].call(data,item,valuesByDimName)}if(logItem){var atoms={};for(var dimName in valuesByDimName){var atom=valuesByDimName[dimName];if(def.object.is(atom)){atom=('v'in atom)?atom.v:('value'in atom)?atom.value:'...'}atoms[dimName]=atom}pvc.log('-> read: '+pvc.stringify(atoms))}return valuesByDimName},_propGet:function(dimName,prop){function propGet(item,atoms){atoms[dimName]=item[prop]}return propGet},_constGet:function(dimName,constRawValue,keyArgs){var me=this,constAtom;function constGet(item,atoms){atoms[dimName]=constAtom||(constAtom=me.data.dimensions(dimName).intern(constRawValue))}return constGet},_nextAvailableItemIndex:function(index,L){if(index==null){index=0}if(L==null){L=Infinity}while(index<L&&def.hasOwn(this._userItem,index)){index++}return index<L?index:-1},_getUnboundRoleDefaultDimNames:function(roleName,count,dims,level){var role=this.chart.visualRoles(roleName,{assertExists:false});if(role&&!role.isPreBound()){var dimGroupName=role.defaultDimensionName;if(dimGroupName){dimGroupName=dimGroupName.match(/^(.*?)(\*)?$/)[1];if(!dims){dims=[]}if(level==null){level=0}if(count==null){count=1}while(count--){var dimName=pvc.buildIndexedId(dimGroupName,level++);if(!this.complexTypeProj.isReadOrCalc(dimName)){dims.push(dimName)}}return dims.length?dims:null}}}});
def.type('pvc.data.MatrixTranslationOper',pvc.data.TranslationOper).add({_initType:function(){this.J=this.metadata.length;this.I=this.source.length;this._processMetadata();this.base()},_knownContinuousColTypes:{'numeric':1,'number':1,'integer':1},_processMetadata:function(){var knownContinColTypes=this._knownContinuousColTypes;var columns=def.query(this.metadata).select(function(colDef,colIndex){colDef.colIndex=colIndex;return colDef}).where(function(colDef){var colType=colDef.colType;return!colType||knownContinColTypes[colType.toLowerCase()]!==1}).select(function(colDef){return colDef.colIndex}).array();var columnTypes=def.array.create(this.J,1);var I=this.I;var source=this.source;var J=columns.length;for(var i=0;i<I&&J>0;i++){var row=source[i];var m=0;while(m<J){var j=columns[m];var value=row[j];if(value!=null){columnTypes[j]=this._getSourceValueType(value);columns.splice(m,1);J--}else{m++}}}this._columnTypes=columnTypes},_getSourceValueType:function(value){switch(typeof value){case'number':return 1;case'object':if(value instanceof Date){return 1}}return 0},logSource:function(){var out=["DATA SOURCE SUMMARY",pvc.logSeparator,"ROWS ("+Math.min(10,this.I)+"/"+this.I+")"];def.query(this.source).take(10).each(function(row,index){out.push("  ["+index+"] "+pvc.stringify(row))});if(this.I>10){out.push('  ...')}out.push("COLS ("+this.J+")");var colTypes=this._columnTypes;this.metadata.forEach(function(col,j){out.push("  ["+j+"] "+"'"+col.colName+"' ("+"type: "+col.colType+", "+"inspected: "+(colTypes[j]?'continuous':'discrete')+(col.colLabel?(", label: '"+col.colLabel+"'"):"")+")")});pvc.log(out.join('\n'))},_createPlot2SeriesKeySet:function(plot2SeriesIndexes,seriesKeys){var plot2SeriesKeySet=null,seriesCount=seriesKeys.length;def.query(plot2SeriesIndexes).each(function(indexText){var seriesIndex=+indexText;if(isNaN(seriesIndex)){throw def.error.argumentInvalid('plot2SeriesIndexes',"Element is not a number '{0}'.",[indexText])}if(seriesIndex<0){if(seriesIndex<=-seriesCount){throw def.error.argumentInvalid('plot2SeriesIndexes',"Index is out of range '{0}'.",[seriesIndex])}seriesIndex=seriesCount+seriesIndex}else if(seriesIndex>=seriesCount){throw def.error.argumentInvalid('plot2SeriesIndexes',"Index is out of range '{0}'.",[seriesIndex])}if(!plot2SeriesKeySet){plot2SeriesKeySet={}}plot2SeriesKeySet[seriesKeys[seriesIndex]]=true});return plot2SeriesKeySet},_dataPartGet:function(calcAxis2SeriesKeySet,seriesReader){var me=this;var dataPartDimName=this.options.dataPartDimName;var dataPartDimension,plot2SeriesKeySet,part1Atom,part2Atom,outAtomsSeries={};function dataPartGet(item,outAtoms){if(!dataPartDimension){plot2SeriesKeySet=calcAxis2SeriesKeySet();dataPartDimension=me.data.dimensions(dataPartDimName);if(pvc.debug>=3&&plot2SeriesKeySet){pvc.log("Second axis series values: "+pvc.stringify(def.keys(plot2SeriesKeySet)))}}var partAtom;seriesReader(item,outAtomsSeries);var series=outAtomsSeries.series;if(series!=null&&series.v!=null){series=series.v}if(def.hasOwn(plot2SeriesKeySet,series)){partAtom=part2Atom||(part2Atom=dataPartDimension.intern("1"))}else{partAtom=part1Atom||(part1Atom=dataPartDimension.intern("0"))}outAtoms[dataPartDimName]=partAtom}return dataPartGet}});
def.type('pvc.data.CrosstabTranslationOper',pvc.data.MatrixTranslationOper).add({virtualItemSize:function(){return this.R+this.C+this.M},_executeCore:function(){if(!this.metadata.length){return def.query()}var dimsReaders=this._getDimensionsReaders();var item=new Array(this.virtualItemSize()),itemCrossGroupIndex=this._itemCrossGroupIndex,me=this;function updateVItemCrossGroup(crossGroupId,source){var itemIndex=itemCrossGroupIndex[crossGroupId],sourceIndex=0,depth=me[crossGroupId];while((depth--)>0){item[itemIndex++]=source[sourceIndex++]}}function updateVItemMeasure(line,cg){var itemIndex=itemCrossGroupIndex.M;var cgIndexes=me._colGroupsIndexes[cg];var depth=me.M;for(var i=0;i<depth;i++){var lineIndex=cgIndexes[i];item[itemIndex++]=lineIndex!=null?line[lineIndex]:null}}function expandLine(line){updateVItemCrossGroup('R',line);return def.query(this._colGroups).select(function(colGroup,cg){updateVItemCrossGroup('C',colGroup);updateVItemMeasure(line,cg);return this._readItem(item,dimsReaders)},this)}return def.query(this._lines).selectMany(expandLine,this)},_processMetadata:function(){this.base();this._separator=this.options.separator||'~';var lines=pvc.cloneMatrix(this.source);this._lines=lines;this.R=1;this.C=1;this.M=1;this.measuresDirection=null;var colNames;if(this.options.seriesInRows){colNames=this.metadata.map(function(d){return d.colName})}else if(this.options.compatVersion<=1){colNames=this.metadata.map(function(d){return{v:d.colName}})}else{colNames=this.metadata.map(function(d){return{v:d.colName,f:d.colLabel}})}var itemCrossGroupTypes=this._itemCrossGroupTypes={};if(!this.options.isMultiValued){this.R=this._getCategoriesCount();this._colGroups=colNames.slice(this.R);this._colGroupsIndexes=new Array(this._colGroups.length);this._colGroups.forEach(function(colGroup,cg){this._colGroups[cg]=[colGroup];this._colGroupsIndexes[cg]=[this.R+cg]},this);itemCrossGroupTypes.C=[0];itemCrossGroupTypes.M=[this._columnTypes[this.R]]}else{var measuresInColumns=def.get(this.options,'measuresInColumns',true);if(measuresInColumns||this.options.measuresIndex==null){this.R=this._getCategoriesCount();var encodedColGroups=colNames.slice(this.R);var L=encodedColGroups.length;if(L>0){if(!measuresInColumns){this._colGroups=encodedColGroups;this._colGroupsIndexes=[];this._colGroups.forEach(function(colGroup,cg){this._colGroups[cg]=this._splitEncodedColGroupCell(colGroup);this._colGroupsIndexes[cg]=[this.R+cg]},this);itemCrossGroupTypes.M=[this._columnTypes[this.R]]}else{this.measuresDirection='columns';this._processEncodedColGroups(encodedColGroups)}this.C=this._colGroups[0].length;itemCrossGroupTypes.C=def.array.create(this.C,0)}else{this.C=this.M=0;itemCrossGroupTypes.M=itemCrossGroupTypes.C=[]}}else{this.measuresDirection='rows';this.R=+this.options.measuresIndex;var measuresCount=this.options.measuresCount;if(measuresCount==null){measuresCount=1}this.M=measuresCount;this._colGroups=colNames.slice(this.R+1);this._colGroups.forEach(function(colGroup,cg){this._colGroups[cg]=[colGroup]},this)}}itemCrossGroupTypes.R=this._columnTypes.slice(0,this.R);var seriesInRows=this.options.seriesInRows;var itemGroupIndex=this._itemCrossGroupIndex={'C':!seriesInRows?0:this.R,'R':!seriesInRows?this.C:0,'M':this.C+this.R};var itemTypes=this._itemTypes=new Array(this.virtualItemSize());def.eachOwn(itemGroupIndex,function(groupStartIndex,crossGroup){itemCrossGroupTypes[crossGroup].forEach(function(type,groupIndex){itemTypes[groupStartIndex+groupIndex]=type})});this._itemLogicalGroup={'series':seriesInRows?this.R:this.C,'category':seriesInRows?this.C:this.R,'value':this.M};this._itemLogicalGroupIndex={'series':0,'category':this._itemLogicalGroup.series,'value':this.C+this.R};if(pvc.debug>=3){pvc.log("Crosstab translator "+pvc.stringify({R:this.R,C:this.C,M:this.M}))}},_getCategoriesCount:function(){var R=this.options.categoriesCount;if(R!=null&&(!isFinite(R)||R<0)){R=null}if(R==null){R=def.query(this._columnTypes).whayl(function(type){return type===0}).count();if(!R){R=1}}return R},_splitEncodedColGroupCell:function(colGroup){var values=colGroup.v;var labels;if(values==null){values=[]}else{values=values.split(this._separator);labels=colGroup.f;if(labels){labels=labels.split(this._separator)}}return values.map(function(value,index){return{v:value,f:labels&&labels[index]}})},_processEncodedColGroups:function(encodedColGroups){var L=encodedColGroups.length||def.assert("Must have columns"),R=this.R,colGroups=[],currColGroup,measuresInfo={},measuresInfoList=[];for(var i=0;i<L;i++){var colGroupCell=encodedColGroups[i];var encColGroupValues=colGroupCell.v;var encColGroupLabels=colGroupCell.f;var sepIndex=encColGroupValues.lastIndexOf(this._separator);var meaName,colGroupValues,colGroupLabels;if(sepIndex<0){meaName=encColGroupValues;encColGroupValues='';colGroupValues=[]}else{meaName=encColGroupValues.substring(sepIndex+1);encColGroupValues=encColGroupValues.substring(0,sepIndex);colGroupValues=encColGroupValues.split(this._separator);if(encColGroupLabels!=null){colGroupLabels=encColGroupLabels.split(this._separator);colGroupLabels.pop()}colGroupValues.forEach(function(value,index){var label=colGroupLabels&&colGroupLabels[index];colGroupValues[index]={v:value,f:label}})}if(!currColGroup||currColGroup.encValues!==encColGroupValues){currColGroup={startIndex:i,encValues:encColGroupValues,values:colGroupValues,measureNames:[meaName]};colGroups.push(currColGroup)}else{currColGroup.measureNames.push(meaName)}var currMeaIndex=(i-currColGroup.startIndex),meaInfo=def.getOwn(measuresInfo,meaName);if(!meaInfo){measuresInfo[meaName]=meaInfo={name:meaName,groupIndex:currMeaIndex,index:i,type:this._columnTypes[R+i]};measuresInfoList.push(meaInfo)}else if(currMeaIndex>meaInfo.groupIndex){meaInfo.groupIndex=currMeaIndex}}measuresInfoList.sort(function(meaInfoA,meaInfoB){return def.compare(meaInfoA.groupIndex,meaInfoB.groupIndex)||def.compare(meaInfoA.index,meaInfoB.index)});var M=measuresInfoList.length;var meaTypes=new Array(M);this._itemCrossGroupTypes.M=meaTypes;measuresInfoList.forEach(function(meaInfoA,index){meaInfoA.groupIndex=index;meaTypes[index]=meaInfoA.type});var CG=colGroups.length,colGroupsValues=new Array(CG),colGroupsIndexes=new Array(CG);colGroups.map(function(colGroup,cg){colGroupsValues[cg]=colGroup.values;var colGroupStartIndex=colGroup.startIndex;var meaIndexes=colGroupsIndexes[cg]=new Array(M);colGroup.measureNames.forEach(function(meaName2,localMeaIndex){var meaIndex=measuresInfo[meaName2].groupIndex;meaIndexes[meaIndex]=R+colGroupStartIndex+localMeaIndex})});this._colGroups=colGroupsValues;this._colGroupsIndexes=colGroupsIndexes;this.M=M},configureType:function(){if(this.measuresDirection==='rows'){throw def.error.notImplemented()}this.base()},_configureTypeCore:function(){var me=this;var itemLogicalGroup=me._itemLogicalGroup;var itemLogicalGroupIndex=me._itemLogicalGroupIndex;var index=0;var dimsReaders=[];function add(dimGroupName,level,count){var crossEndIndex=itemLogicalGroupIndex[dimGroupName]+count;while(count>0){var dimName=pvc.buildIndexedId(dimGroupName,level);if(!me.complexTypeProj.isReadOrCalc(dimName)){index=me._nextAvailableItemIndex(index);if(index>=crossEndIndex){return}dimsReaders.push({names:dimName,indexes:index});index++;count--}level++}}var dataPartDimName=this.options.dataPartDimName;if(dataPartDimName&&this.C===1&&!this.complexTypeProj.isReadOrCalc(dataPartDimName)){var plot2SeriesIndexes=this.options.plot2SeriesIndexes;if(plot2SeriesIndexes!=null){var seriesKeys=this._colGroups.map(function(colGroup){return''+colGroup[0].v});this._plot2SeriesKeySet=this._createPlot2SeriesKeySet(plot2SeriesIndexes,seriesKeys)}}['series','category','value'].forEach(function(dimGroupName){var L=itemLogicalGroup[dimGroupName];if(L>0){add(dimGroupName,0,L)}});if(dimsReaders){dimsReaders.forEach(this.defReader,this)}if(this._plot2SeriesKeySet){var seriesReader=this._userDimsReadersByDim.series;if(seriesReader){var calcAxis2SeriesKeySet=def.fun.constant(this._plot2SeriesKeySet);this._userRead(this._dataPartGet(calcAxis2SeriesKeySet,seriesReader),dataPartDimName)}}}});
def.type('pvc.data.RelationalTranslationOper',pvc.data.MatrixTranslationOper).add({M:0,C:0,S:0,_processMetadata:function(){this.base();var metadata=this.metadata;var J=this.J;var C=this.options.categoriesCount;if(C!=null&&(!isFinite(C)||C<0)){C=0}var S;var valuesColIndexes,M;if(this.options.isMultiValued){valuesColIndexes=pvc.parseDistinctIndexArray(this.options.measuresIndexes,J-1);M=valuesColIndexes?valuesColIndexes.length:0}var D;if(M==null){if(J>0&&J<=3&&(C==null||C===1)&&S==null){M=1;valuesColIndexes=[J-1];C=J>=2?1:0;S=J>=3?1:0;D=C+S}else if(C!=null&&C>=J){D=J;C=J;S=0;M=0}else{var Mmax=C!=null?(J-C):Infinity;valuesColIndexes=def.query(metadata).where(function(colDef,index){return this._columnTypes[index]!==0},this).select(function(colDef){return colDef.colIndex}).take(Mmax).array();M=valuesColIndexes.length}}if(D==null){D=J-M;if(D===0){S=C=0}else if(C!=null){if(C>D){C=D;S=0}else{S=D-C}}else{S=D>1?1:0;C=D-S}}var seriesInRows=this.options.seriesInRows;var colGroupSpecs=[];if(D){if(S&&!seriesInRows){colGroupSpecs.push({name:'S',count:S})}if(C){colGroupSpecs.push({name:'C',count:C})}if(S&&seriesInRows){colGroupSpecs.push({name:'S',count:S})}}if(M){colGroupSpecs.push({name:'M',count:M})}var availableInputIndexes=def.range(0,J).array();if(valuesColIndexes){valuesColIndexes.forEach(function(inputIndex){availableInputIndexes.splice(inputIndex,1)})}var specsByName={};colGroupSpecs.forEach(function(groupSpec){var count=groupSpec.count;var name=groupSpec.name;specsByName[name]=groupSpec;if(valuesColIndexes&&name==='M'){groupSpec.indexes=valuesColIndexes}else{groupSpec.indexes=availableInputIndexes.splice(0,count)}},this);this.M=M;this.S=S;this.C=C;var itemPerm=[];['S','C','M'].forEach(function(name){var groupSpec=specsByName[name];if(groupSpec){def.array.append(itemPerm,groupSpec.indexes)}});var colTypes=this._columnTypes;this._itemTypes=itemPerm.map(function(index){return colTypes[index]});this._itemCrossGroupIndex={S:0,C:this.S,M:this.S+this.C};this._itemPerm=itemPerm;if(pvc.debug>=3){var out=["RELATIONAL TRANSLATOR MAPPING",pvc.logSeparator,"["+colGroupSpecs.map(function(groupSpec){return def.array.create(groupSpec.count,groupSpec.name).join('')}).join(' ')+"]"];pvc.log(out.join("\n"))}},_configureTypeCore:function(){var me=this;var index=0;var dimsReaders=[];function add(dimGroupName,colGroupName,level,count){var groupEndIndex=me._itemCrossGroupIndex[colGroupName]+count;while(count>0){var dimName=pvc.buildIndexedId(dimGroupName,level);if(!me.complexTypeProj.isReadOrCalc(dimName)){index=me._nextAvailableItemIndex(index);if(index>=groupEndIndex){return}dimsReaders.push({names:dimName,indexes:index});index++;count--}level++}}if(this.S>0){add('series','S',0,this.S)}if(this.C>0){add('category','C',0,this.C)}if(this.M>0){add('value','M',0,this.M)}if(dimsReaders){dimsReaders.forEach(this.defReader,this)}var plot2SeriesIndexes=this.options.plot2SeriesIndexes;if(plot2SeriesIndexes!=null){var seriesReader=this._userDimsReadersByDim.series;if(seriesReader){var dataPartDimName=this.options.dataPartDimName;this._userRead(relTransl_dataPartGet.call(this,plot2SeriesIndexes,seriesReader),dataPartDimName)}}},_executeCore:function(){var dimsReaders=this._getDimensionsReaders();var permIndexes=this._itemPerm;return def.query(this._getItems()).select(function(item){item=pv.permute(item,permIndexes);return this._readItem(item,dimsReaders)},this)}});function relTransl_dataPartGet(plot2SeriesIndexes,seriesReader){var me=this;function calcAxis2SeriesKeySet(){var atoms={};var seriesKeys=def.query(me.source).select(function(item){seriesReader(item,atoms);var value=atoms.series;if(value!=null&&value.v!=null){value=value.v}return value||null}).distinct().array();return me._createPlot2SeriesKeySet(plot2SeriesIndexes,seriesKeys)}return this._dataPartGet(calcAxis2SeriesKeySet,seriesReader)}
def.type('pvc.data.Atom').init(function(dimension,value,label,rawValue,key){this.dimension=dimension;this.id=(value==null?-def.nextId():def.nextId());this.value=value;this.label=label;if(rawValue!==undefined){this.rawValue=rawValue}this.key=key}).add({isVirtual:false,rawValue:undefined,toString:function(){var label=this.label;if(label!=null){return label}label=this.value;return label!=null?(""+label):""}});function atom_idComparer(a,b){return a.id-b.id}function atom_idComparerReverse(a,b){return b.id-a.id}
var complex_nextId=1;def.type('pvc.data.Complex').init(function(source,atomsByName,dimNames,atomsBase,wantLabel,calculate){this.id=complex_nextId++;var owner;if(source){owner=source.owner;if(!atomsBase){atomsBase=source.atoms}}this.owner=owner||this;this.atoms=atomsBase?Object.create(atomsBase):{};var hadDimNames=!!dimNames;if(!dimNames){dimNames=owner.type._dimsNames}var atomsMap=this.atoms;var D=dimNames.length;var i,dimName;if(atomsByName){var ownerDims=owner._dimensions;var addAtom=function(dimName,value){if(value!=null){var dimension=def.getOwn(ownerDims,dimName);var atom=dimension.intern(value);if(!atomsBase||atom!==atomsBase[dimName]){atomsMap[dimName]=atom}}};if(!hadDimNames){for(dimName in atomsByName){addAtom(dimName,atomsByName[dimName])}}else{for(i=0;i<D;i++){dimName=dimNames[i];addAtom(dimName,atomsByName[dimName])}}if(calculate){var newAtomsByName=owner.type._calculate(this);for(dimName in newAtomsByName){if(!def.hasOwnProp.call(atomsMap,dimName)){addAtom(dimName,newAtomsByName[dimName])}}}}if(!D){this.value=null;this.key='';if(wantLabel){this.label=""}}else if(D===1){var singleAtom=atomsMap[dimNames[0]];this.value=singleAtom.value;this.rawValue=singleAtom.rawValue;this.key=singleAtom.key;if(wantLabel){this.label=singleAtom.label}}else{var key,label;var labelSep=owner.labelSep;var keySep=owner.keySep;for(i=0;i<D;i++){dimName=dimNames[i];var atom=atomsMap[dimName];if(!i){key=atom.key}else{key+=keySep+atom.key}if(wantLabel){var atomLabel=atom.label;if(atomLabel){if(!label){label=atomLabel}else{label+=labelSep+atomLabel}}}}this.value=this.rawValue=this.key=key;if(wantLabel){this.label=label}}}).add({labelSep:" ~ ",keySep:',',label:null,rawValue:undefined,ensureLabel:function(){var label=this.label;if(label!=null){label="";var labelSep=this.owner.labelSep;def.eachOwn(this.atoms,function(atom){var alabel=atom.label;if(alabel){if(label){label+=labelSep+alabel}else{label=alabel}}});this.label=label}return label},view:function(dimNames){return new pvc.data.ComplexView(this,dimNames)},toString:function(){var s=[''+this.constructor.typeName];if(this.index!=null){s.push("#"+this.index)}this.owner.type.dimensionsNames().forEach(function(name){s.push(name+": "+pvc.stringify(this.atoms[name].value))},this);return s.join(" ")}});pvc.data.Complex.values=function(complex,dimNames){var atoms=complex.atoms;return dimNames.map(function(dimName){return atoms[dimName].value})};pvc.data.Complex.labels=function(complex,dimNames){var atoms=complex.atoms;return dimNames.map(function(dimName){return atoms[dimName].label})};
def.type('pvc.data.ComplexView',pvc.data.Complex).init(function(source,viewDimNames){this.source=source;this.viewDimNames=viewDimNames;var sourceAtoms=source.atoms,ownSourceAtoms=[];viewDimNames.forEach(function(dimName){if(def.hasOwnProp.call(sourceAtoms,dimName)){ownSourceAtoms[dimName]=sourceAtoms[dimName]}});this.base(source,ownSourceAtoms,viewDimNames,source.owner.atoms,true)}).add({values:function(){return pvc.data.Complex.values(this,this.viewDimNames)},labels:function(){return pvc.data.Complex.labels(this,this.viewDimNames)}});
def.type('pvc.data.Datum',pvc.data.Complex).init(function(data,atomsByName,isNull){this.base(data,atomsByName,null,null,false,!isNull);if(isNull){this.isNull=true}}).add({isSelected:false,isVisible:true,isNull:false,isVirtual:false,isTrend:false,trendType:null,isInterpolated:false,interpolation:null,setSelected:function(select){if(this.isNull){return false}select=(select==null)||!!select;var changed=this.isSelected!==select;if(changed){if(!select){delete this.isSelected}else{this.isSelected=true}data_onDatumSelectedChanged.call(this.owner,this,select)}return changed},toggleSelected:function(){return this.setSelected(!this.isSelected)},setVisible:function(visible){if(this.isNull){return false}visible=(visible==null)||!!visible;var changed=this.isVisible!==visible;if(changed){this.isVisible=visible;data_onDatumVisibleChanged.call(this.owner,this,visible)}return changed},toggleVisible:function(){return this.setVisible(!this.isVisible)}});function datum_deselect(){delete this.isSelected}
def.type('pvc.data.Dimension').init(function(data,type){this.data=data;this.type=type;this.root=this;this.owner=this;var name=type.name;this.name=name;this._atomComparer=type.atomComparer();this._atomsByKey={};if(data.isOwner()){this._atoms=[];dim_createVirtualNullAtom.call(this)}else{var parentData=data.parent;var source;if(parentData){source=parentData._dimensions[name];dim_addChild.call(source,this);this.root=data.parent.root}else{parentData=data.linkParent;parentData||def.assert("Data must have a linkParent");source=parentData._dimensions[name];dim_addLinkChild.call(source,this)}this._nullAtom=this.owner._nullAtom;this._lazyInit=function(){this._lazyInit=null;var datums=this.data._datums;var L=datums.length;var atomsByKey=this._atomsByKey;for(var i=0;i<L;i++){var atom=datums[i].atoms[name];atomsByKey[atom.key]=atom}this._atoms=source.atoms().filter(function(atom){return def.hasOwnProp.call(atomsByKey,atom.key)})}}}).add({parent:null,linkParent:null,_children:null,_linkChildren:null,_atomsByKey:null,_atomVisibleDatumsCount:null,_disposed:false,_nullAtom:null,_virtualNullAtom:null,_visibleAtoms:null,_visibleIndexes:null,_atomComparer:null,_atoms:null,_sumCache:null,count:function(){if(this._lazyInit){this._lazyInit()}return this._atoms.length},isVisible:function(atom){if(this._lazyInit){this._lazyInit()}def.hasOwn(this._atomsByKey,atom.key)||def.assert("Atom must exist in this dimension.");return dim_getVisibleDatumsCountMap.call(this)[atom.key]>0},atoms:function(keyArgs){if(this._lazyInit){this._lazyInit()}var visible=def.get(keyArgs,'visible');if(visible==null){return this._atoms}visible=!!visible;this._visibleAtoms||(this._visibleAtoms={});return this._visibleAtoms[visible]||(this._visibleAtoms[visible]=dim_calcVisibleAtoms.call(this,visible))},indexes:function(keyArgs){if(this._lazyInit){this._lazyInit()}var visible=def.get(keyArgs,'visible');if(visible==null){return pv.range(0,this._atoms.length)}visible=!!visible;this._visibleIndexes||(this._visibleIndexes={});return this._visibleIndexes[visible]||(this._visibleIndexes[visible]=dim_calcVisibleIndexes.call(this,visible))},atom:function(value){if(value==null||value===''){return this._nullAtom}if(value instanceof pvc.data.Atom){return value}if(this._lazyInit){this._lazyInit()}var key=this.type._key?this.type._key.call(null,value):value;return this._atomsByKey[key]||null},extent:function(keyArgs){var atoms=this.atoms(keyArgs);var L=atoms.length;if(!L){return undefined}var offset=this._nullAtom&&atoms[0].value==null?1:0;var countWithoutNull=L-offset;if(countWithoutNull>0){var min=atoms[offset];var max=atoms[L-1];var tmp;if(min!==max&&def.get(keyArgs,'abs',false)){var minSign=min.value<0?-1:1;var maxSign=max.value<0?-1:1;if(minSign===maxSign){if(maxSign<0){tmp=max;max=min;min=tmp}}else if(countWithoutNull>2){if(max.value<-min.value){max=min}var zeroIndex=def.array.binarySearch(atoms,0,this.type.comparer(),function(a){return a.value});if(zeroIndex<0){zeroIndex=~zeroIndex;var negAtom=atoms[zeroIndex-1];var posAtom=atoms[zeroIndex];if(-negAtom.value<posAtom.value){min=negAtom}else{min=posAtom}}else{min=atoms[zeroIndex]}}else if(max.value<-min.value){tmp=max;max=min;min=tmp}}return{min:min,max:max}}return undefined},min:function(keyArgs){var atoms=this.atoms(keyArgs);var L=atoms.length;if(!L){return undefined}var offset=this._nullAtom&&atoms[0].value==null?1:0;return(L>offset)?atoms[offset]:undefined},max:function(keyArgs){var atoms=this.atoms(keyArgs);var L=atoms.length;return L&&atoms[L-1].value!=null?atoms[L-1]:undefined},sum:function(keyArgs){var isAbs=!!def.get(keyArgs,'abs',false),zeroIfNone=def.get(keyArgs,'zeroIfNone',true),key=dim_buildDatumsFilterKey(keyArgs)+':'+isAbs;var sum=def.getOwn(this._sumCache,key);if(sum===undefined){var dimName=this.name;sum=this.data.datums(null,keyArgs).reduce(function(sum2,datum){var value=datum.atoms[dimName].value;if(isAbs&&value<0){value=-value}return sum2!=null?(sum2+value):value},null);(this._sumCache||(this._sumCache={}))[key]=sum}return zeroIfNone?(sum||0):sum},percent:function(atomOrValue,keyArgs){var value=(atomOrValue instanceof pvc.data.Atom)?atomOrValue.value:atomOrValue;if(!value){return 0}var sum=this.sum(def.create(keyArgs,{abs:true}));return sum?(Math.abs(value)/sum):0},percentOverParent:function(keyArgs){var value=this.sum(keyArgs);if(!value){return 0}var parentData=this.data.parent;if(!parentData){return 0}var sum=parentData.dimensionsSumAbs(this.name,keyArgs);return sum?(Math.abs(value)/sum):0},format:function(value,sourceValue){return""+(this.type._formatter?this.type._formatter.call(null,value,sourceValue):"")},intern:function(sourceValue,isVirtual){if(sourceValue==null||sourceValue===''){return this._nullAtom||dim_createNullAtom.call(this,sourceValue)}if(sourceValue instanceof pvc.data.Atom){if(sourceValue.dimension!==this){throw def.error.operationInvalid("Atom is of a different dimension.")}return sourceValue}var value,label;var type=this.type;if(typeof sourceValue==='object'&&('v'in sourceValue)){label=sourceValue.f;sourceValue=sourceValue.v}if(!isVirtual){var converter=type._converter;value=converter?converter(sourceValue):sourceValue;if(value==null||value===''){return this._nullAtom||dim_createNullAtom.call(this,sourceValue)}}else{value=sourceValue}var cast=type.cast;if(cast){value=cast(value);if(value==null||value===''){return this._nullAtom||dim_createNullAtom.call(this)}}var keyFun=type._key;var key=''+(keyFun?keyFun(value):value);key||def.fail.operationInvalid("Only a null value can have an empty key.");var atom=this._atomsByKey[key];if(atom){if(!isVirtual&&atom.isVirtual){delete atom.isVirtual}return atom}return dim_createAtom.call(this,type,sourceValue,key,value,label,isVirtual)},dispose:function(){if(!this._disposed){data_disposeChildList(this._children,'parent');data_disposeChildList(this._linkChildren,'linkParent');if(this.parent){dim_removeChild.call(this.parent,this)}if(this.linkParent){dim_removeLinkChild.call(this.linkParent,this)}dim_clearVisiblesCache.call(this);this._lazyInit=null;this._atoms=this._nullAtom=this._virtualNullAtom=null;this._disposed=true}}});function dim_createAtom(type,sourceValue,key,value,label,isVirtual){var atom;if(this.owner===this){if(label==null){var formatter=type._formatter;if(formatter){label=formatter(value,sourceValue)}else{label=value}}label=""+label;if(!label&&pvc.debug>=2){pvc.log("Only the null value should have an empty label.")}atom=new pvc.data.Atom(this,value,label,sourceValue,key);if(isVirtual){atom.isVirtual=true}}else{var source=this.parent||this.linkParent;atom=source._atomsByKey[key]||dim_createAtom.call(source,type,sourceValue,key,value,label,isVirtual)}def.array.insert(this._atoms,atom,this._atomComparer);dim_clearVisiblesCache.call(this);this._atomsByKey[key]=atom;return atom}function dim_internAtom(atom){var key=atom.key;if(atom.dimension===this){(this.owner===this)||def.assert("Should be an owner dimension");if(!key&&atom===this._virtualNullAtom){atom=this.intern(null)}return atom}if(!this._lazyInit){var localAtom=this._atomsByKey[key];if(localAtom){if(localAtom!==atom){throw def.error.operationInvalid("Atom is from a different root data.")}return atom}if(this.owner===this){throw def.error.operationInvalid("Atom is from a different root data.")}}dim_internAtom.call(this.parent||this.linkParent,atom);if(!this._lazyInit){this._atomsByKey[key]=atom;if(!key){this._nullAtom=atom;this._atoms.unshift(atom)}else{def.array.insert(this._atoms,atom,this._atomComparer)}dim_clearVisiblesCache.call(this)}return atom}function dim_buildDatumsFilterKey(keyArgs){var visible=def.get(keyArgs,'visible'),selected=def.get(keyArgs,'selected');return(visible==null?null:!!visible)+':'+(selected==null?null:!!selected)}function dim_createNullAtom(sourceValue){var nullAtom=this._nullAtom;if(!nullAtom){if(this.owner===this){var typeFormatter=this.type._formatter;var label=""+(typeFormatter?typeFormatter.call(null,null,sourceValue):"");nullAtom=new pvc.data.Atom(this,null,label,null,'');this.data._atomsBase[this.name]=nullAtom}else{nullAtom=dim_createNullAtom.call(this.parent||this.linkParent,sourceValue)}this._atomsByKey['']=this._nullAtom=nullAtom;this._atoms.unshift(nullAtom)}return nullAtom}function dim_createVirtualNullAtom(){(this.owner===this)||def.assert("Can only create atoms on an owner dimension.");if(!this._virtualNullAtom){this._virtualNullAtom=new pvc.data.Atom(this,null,"",null,'');this.data._atomsBase[this.name]=this._virtualNullAtom}return this._virtualNullAtom}function dim_unintern(atom){(this.owner===this)||def.assert("Can only unintern atoms on an owner dimension.");(atom&&atom.dimension===this)||def.assert("Not an interned atom");if(atom===this._virtualNullAtom){return}var key=atom.key;if(this._atomsByKey[key]===atom){def.array.remove(this._atoms,atom,this._atomComparer);delete this._atomsByKey[key];if(!key){delete this._nullAtom;this.data._atomsBase[this.name]=this._virtualNullAtom}}dim_clearVisiblesCache.call(this)}function dim_uninternUnvisitedAtoms(){(this.owner===this)||def.assert("Can only unintern atoms of an owner dimension.");var atoms=this._atoms;if(atoms){var atomsByKey=this._atomsByKey;var i=0;var L=atoms.length;while(i<L){var atom=atoms[i];if(atom.visited){delete atom.visited;i++}else if(atom!==this._virtualNullAtom){atoms.splice(i,1);L--;var key=atom.key;delete atomsByKey[key];if(!key){delete this._nullAtom;this.data._atomsBase[this.name]=this._virtualNullAtom}}}dim_clearVisiblesCache.call(this)}}function dim_uninternVirtualAtoms(){var atoms=this._atoms;if(atoms){var atomsByKey=this._atomsByKey;var i=0;var L=atoms.length;var removed;while(i<L){var atom=atoms[i];if(!atom.isVirtual){i++}else{atoms.splice(i,1);L--;removed=true;var key=atom.key||def.assert("Cannot be the null or virtual null atom.");delete atomsByKey[key]}}if(removed){dim_clearVisiblesCache.call(this)}}}function dim_clearVisiblesCache(){this._atomVisibleDatumsCount=this._sumCache=this._visibleAtoms=this._visibleIndexes=null}function dim_onDatumsChanged(){dim_clearVisiblesCache.call(this)}function dim_addChild(child){data_addColChild(this,'_children',child,'parent');child.owner=this.owner}function dim_removeChild(child){data_removeColChild(this,'_children',child,'parent')}function dim_addLinkChild(linkChild){data_addColChild(this,'_linkChildren',linkChild,'linkParent');linkChild.owner=this.owner}function dim_removeLinkChild(linkChild){data_removeColChild(this,'_linkChildren',linkChild,'linkParent')}function dim_onDatumVisibleChanged(datum,visible){var map;if(!this._disposed&&(map=this._atomVisibleDatumsCount)){var atom=datum.atoms[this.name],key=atom.key;def.hasOwn(this._atomsByKey,key)||def.assert("Atom must exist in this dimension.");var count=map[key];(visible||(count>0))||def.assert("Must have had accounted for at least one visible datum.");map[key]=(count||0)+(visible?1:-1);this._visibleAtoms=this._sumCache=this._visibleIndexes=null}}function dim_getVisibleDatumsCountMap(){var map=this._atomVisibleDatumsCount;if(!map){map={};this.data.datums(null,{visible:true}).each(function(datum){var atom=datum.atoms[this.name],key=atom.key;map[key]=(map[key]||0)+1},this);this._atomVisibleDatumsCount=map}return map}function dim_calcVisibleIndexes(visible){var indexes=[];this._atoms.forEach(function(atom,index){if(this.isVisible(atom)===visible){indexes.push(index)}},this);return indexes}function dim_calcVisibleAtoms(visible){return def.query(this._atoms).where(function(atom){return this.isVisible(atom)===visible},this).array()}
def.type('pvc.data.Data',pvc.data.Complex).init(function(keyArgs){keyArgs||def.fail.argumentRequired('keyArgs');this._visibleDatums=new def.Map();var owner,atoms,atomsBase,dimNames,datums,index,parent=this.parent=keyArgs.parent||null;if(parent){this.root=parent.root;this.depth=parent.depth+1;this.type=parent.type;datums=keyArgs.datums||def.fail.argumentRequired('datums');owner=parent.owner;atoms=keyArgs.atoms||def.fail.argumentRequired('atoms');dimNames=keyArgs.dimNames||def.fail.argumentRequired('dimNames');atomsBase=parent.atoms}else{this.root=this;dimNames=[];var linkParent=keyArgs.linkParent||null;if(linkParent){owner=linkParent.owner;this.type=owner.type;datums=keyArgs.datums||def.fail.argumentRequired('datums');this._leafs=[];atomsBase=linkParent.atoms;index=def.get(keyArgs,'index',null);data_addLinkChild.call(linkParent,this,index)}else{owner=this;atomsBase={};if(keyArgs.labelSep){this.labelSep=keyArgs.labelSep}this.type=keyArgs.type||def.fail.argumentRequired('type');this._selectedDatums=new def.Map()}}if(datums){data_setDatums.call(this,datums)}this.owner=owner;this._atomsBase=atomsBase;this._dimensions={};this.type.dimensionsList().forEach(this._initDimension,this);this.base(owner,atoms,dimNames,atomsBase,true);pv.Dom.Node.call(this,null);delete this.nodeValue;this._children=this.childNodes;if(parent){index=def.get(keyArgs,'index',null);data_addChild.call(parent,this,index);if(parent.absLabel){this.absLabel=def.string.join(owner.labelSep,parent.absLabel,this.label)}else{this.absLabel=this.label}if(parent.absKey){this.absKey=def.string.join(",",parent.absKey,this.key)}else{this.absKey=this.key}}else{this.absLabel=this.label;this.absKey=this.key}}).add(pv.Dom.Node).add({parent:null,linkParent:null,_dimensions:null,_freeDimensionNames:null,_children:null,_linkChildren:null,_leafs:null,_childrenByKey:null,_visibleDatums:null,_selectedDatums:null,_groupByCache:null,_sumAbsCache:null,treeHeight:null,_groupOper:null,_groupSpec:null,_groupLevel:null,_datums:null,_datumsById:null,depth:0,label:"",absLabel:"",_disposed:false,_isFlattenGroup:false,_isDegenerateFlattenGroup:false,_initDimension:function(dimType){this._dimensions[dimType.name]=new pvc.data.Dimension(this,dimType)},dimensions:function(name,keyArgs){if(name==null){return this._dimensions}var dim=def.getOwn(this._dimensions,name);if(!dim&&def.get(keyArgs,'assertExists',true)){throw def.error.argumentInvalid('name',"Undefined dimension '{0}'.",[name])}return dim},freeDimensionNames:function(){if(!this._freeDimensionNames){var free=this._freeDimensionNames=[];def.eachOwn(this._dimensions,function(dim,dimName){var atom=this.atoms[dimName];if(!(atom instanceof pvc.data.Atom)||atom.value==null){free.push(dimName)}},this)}return this._freeDimensionNames},isOwner:function(){return this.owner===this},children:function(){if(!this._children){return def.query()}return def.query(this._children)},childCount:function(){return this._children?this._children.length:0},leafs:function(){return def.query(this._leafs)},count:function(){return this._datums.length},singleDatum:function(){var datums=this._datums;return datums.length===1?datums[0]:null},dispose:function(){if(!this._disposed){data_disposeChildLists.call(this);if(this._selectedDatums){this._selectedDatums.clear()}this._visibleDatums.clear();def.eachOwn(this._dimensions,function(dimension){dimension.dispose()});if(this.parent){this.parent.removeChild(this);this.parent=null}if(this.linkParent){data_removeLinkChild.call(this.linkParent,this)}this._disposed=true}},disposeChildren:function(){data_disposeChildLists.call(this)}});function data_addChild(child,index){this.insertAt(child,index);(this._childrenByKey||(this._childrenByKey={}))[child.key]=child}function data_addLinkChild(linkChild,index){data_addColChild(this,'_linkChildren',linkChild,'linkParent',index)}function data_removeLinkChild(linkChild){data_removeColChild(this,'_linkChildren',linkChild,'linkParent')}function data_disposeChildLists(){data_disposeChildList(this._children,'parent');this._childrenByKey=null;data_disposeChildList(this._linkChildren,'linkParent');this._groupByCache=null;this._sumAbsCache=null}function data_assertIsOwner(){this.isOwner()||def.fail("Can only be called on the owner data.")}
pvc.data.Data.add({selectedCount:function(){if(!this.isOwner()){return this.datums(null,{selected:true}).count()}return this._selectedDatums.count},selectedDatums:function(){if(!this.isOwner()){return this.datums(null,{selected:true}).array()}return this._selectedDatums.values()},selectedDatumMap:function(){if(!this.isOwner()){var datums=this.datums(null,{selected:true}).object({name:function(datum){return datum.id}});return new def.Set(datums)}return this._selectedDatums.clone()},visibleCount:function(){return this._visibleDatums.count},replaceSelected:function(datums){if(!def.array.is(datums)){datums=datums.array()}var alreadySelectedById=def.query(datums).where(function(datum){return datum.isSelected}).object({name:function(datum){return datum.id}});var changed=this.owner.clearSelected(function(datum){return!def.hasOwn(alreadySelectedById,datum.id)});changed|=pvc.data.Data.setSelected(datums,true);return changed},clearSelected:function(funFilter){if(this.owner!==this){return this.owner.clearSelected(funFilter)}if(!this._selectedDatums.count){return false}var changed;if(funFilter){changed=false;this._selectedDatums.values().filter(funFilter).forEach(function(datum){changed=true;datum_deselect.call(datum);this._selectedDatums.rem(datum.id)},this)}else{changed=true;this._selectedDatums.values().forEach(function(datum){datum_deselect.call(datum)});this._selectedDatums.clear()}return changed}});function data_onDatumSelectedChanged(datum,selected){!datum.isNull||def.assert("Null datums do not notify selected changes");if(selected){this._selectedDatums.set(datum.id,datum)}else{this._selectedDatums.rem(datum.id)}this._sumAbsCache=null}function data_onDatumVisibleChanged(datum,visible){if(def.hasOwn(this._datumsById,datum.id)){!datum.isNull||def.assert("Null datums do not notify visible changes");if(visible){this._visibleDatums.set(datum.id,datum)}else{this._visibleDatums.rem(datum.id)}this._sumAbsCache=null;def.eachOwn(this._dimensions,function(dimension){dim_onDatumVisibleChanged.call(dimension,datum,visible)});this._children.forEach(function(data){data_onDatumVisibleChanged.call(data,datum,visible)});if(this._linkChildren){this._linkChildren.forEach(function(data){data_onDatumVisibleChanged.call(data,datum,visible)})}}}pvc.data.Data.setSelected=function(datums,selected){var anyChanged=false;if(datums){def.query(datums).each(function(datum){if(datum.setSelected(selected)){anyChanged=true}})}return anyChanged};pvc.data.Data.toggleSelected=function(datums){if(!def.array.isLike(datums)){datums=def.query(datums).array()}var allSelected=def.query(datums).all(function(datum){return datum.isNull||datum.isSelected});return this.setSelected(datums,!allSelected)};pvc.data.Data.setVisible=function(datums,visible){var anyChanged=false;if(datums){def.query(datums).each(function(datum){if(datum.setVisible(visible)){anyChanged=true}})}return anyChanged};pvc.data.Data.toggleVisible=function(datums){if(!def.array.isLike(datums)){datums=def.query(datums).array()}var allVisible=def.query(datums).all(function(datum){return datum.isVisible});return pvc.data.Data.setVisible(datums,!allVisible)};
def.type('pvc.data.GroupingSpec').init(function(levelSpecs,type,keyArgs){this.type=type||null;var ids=[];this.hasCompositeLevels=false;var dimNames=[];this.levels=def.query(levelSpecs||undefined).where(function(levelSpec){return levelSpec.dimensions.length>0}).select(function(levelSpec){ids.push(levelSpec.id);def.array.append(dimNames,levelSpec.dimensionNames());if(!this.hasCompositeLevels&&levelSpec.dimensions.length>1){this.hasCompositeLevels=true}levelSpec._setAccDimNames(dimNames.slice(0));return levelSpec},this).array();this._dimNames=dimNames;this.depth=this.levels.length;this.isSingleLevel=this.depth===1;this.isSingleDimension=this.isSingleLevel&&!this.hasCompositeLevels;this.firstDimension=this.depth>0?this.levels[0].dimensions[0]:null;this.flatteningMode=def.get(keyArgs,'flatteningMode')||null;this.flattenRootLabel=def.get(keyArgs,'flattenRootLabel')||'';this.id=(this.flatteningMode||'')+"##"+this.flattenRootLabel+"##"+ids.join('||')}).add({bind:function(type){this.type=type||def.fail.argumentRequired('type');this.levels.forEach(function(levelSpec){levelSpec.bind(type)})},dimensions:function(){return def.query(this.levels).selectMany(function(level){return level.dimensions})},dimensionNames:function(){return this._dimNames},view:function(complex){return complex.view(this.dimensionNames())},isDiscrete:function(){var d;return!this.isSingleDimension||(!!(d=this.firstDimension)&&d.type.isDiscrete)},firstDimensionType:function(){var d=this.firstDimension;return d&&d.type},firstDimensionName:function(){var dt=this.firstDimensionType();return dt&&dt.name},firstDimensionValueType:function(){var dt=this.firstDimensionType();return dt&&dt.valueType},isNull:function(){return!this.levels.length},ensure:function(keyArgs){var grouping=this,flatteningMode=def.get(keyArgs,'flatteningMode');if(flatteningMode){if(flatteningMode==='singleLevel'){return grouping.singleLevelGrouping(keyArgs)}var flattenRootLabel=def.get(keyArgs,'flattenRootLabel')||'';if(this.flatteningMode!==flatteningMode||(this.flattenRootLabel!==flattenRootLabel)){grouping=new pvc.data.GroupingSpec(grouping.levels,grouping.type,{flatteningMode:flatteningMode,flattenRootLabel:flattenRootLabel})}}if(def.get(keyArgs,'reverse',false)){grouping=grouping.reversed()}return grouping},singleLevelGrouping:function(keyArgs){var reverse=!!def.get(keyArgs,'reverse',false);if(this.isSingleLevel&&!reverse){return this}this._singleLevelGrouping||(this._singleLevelGrouping={});var singleLevel=this._singleLevelGrouping[reverse];if(!singleLevel){var dimSpecs=this.dimensions().select(function(dimSpec){return reverse?new pvc.data.GroupingDimensionSpec(dimSpec.name,!dimSpec.reverse,dimSpec.type.complexType):dimSpec});var levelSpec=new pvc.data.GroupingLevelSpec(dimSpecs,this.type);singleLevel=new pvc.data.GroupingSpec([levelSpec],this.type,{flatteningMode:this.flatteningMode});this._singleLevelGrouping[reverse]=singleLevel}return singleLevel},reversed:function(){var reverseGrouping=this._reverseGrouping;if(!reverseGrouping){var levelSpecs=def.query(this.levels).select(function(levelSpec){var dimSpecs=def.query(levelSpec.dimensions).select(function(dimSpec){return new pvc.data.GroupingDimensionSpec(dimSpec.name,!dimSpec.reverse,dimSpec.type.complexType)});return new pvc.data.GroupingLevelSpec(dimSpecs,this.type)});reverseGrouping=new pvc.data.GroupingSpec(levelSpecs,this.type,{flatteningMode:this.flatteningMode});this._reverseGrouping=reverseGrouping}return reverseGrouping},toString:function(){return def.query(this.levels).select(function(level){return''+level}).array().join(', ')}});def.type('pvc.data.GroupingLevelSpec').init(function(dimSpecs,type){var ids=[];var dimNames=[];this.dimensions=def.query(dimSpecs).select(function(dimSpec){ids.push(dimSpec.id);dimNames.push(dimSpec.name);return dimSpec}).array();this._dimNames=dimNames;this.dimensionsInDefOrder=this.dimensions.slice(0);if(type){this._sortDimensions(type)}this.id=ids.join(',');this.depth=this.dimensions.length;var me=this;this.comparer=function(a,b){return me.compare(a,b)}}).add({_sortDimensions:function(type){type.sortDimensionNames(this.dimensionsInDefOrder,function(d){return d.name})},_setAccDimNames:function(accDimNames){this._accDimNames=accDimNames},accDimensionNames:function(){return this._accDimNames},dimensionNames:function(){return this._dimNames},bind:function(type){this._sortDimensions(type);this.dimensions.forEach(function(dimSpec){dimSpec.bind(type)})},compare:function(a,b){for(var i=0,D=this.depth;i<D;i++){var result=this.dimensions[i].compareDatums(a,b);if(result!==0){return result}}return 0},key:function(datum){var key='';var atoms={};var datoms=datum.atoms;var dimNames=this._dimNames;var keySep=datum.owner.keySep;for(var i=0,D=this.depth;i<D;i++){var dimName=dimNames[i];var atom=datoms[dimName];atoms[dimName]=atom;if(!i){key=atom.key}else{key+=keySep+atom.key}}return{key:key,atoms:atoms,dimNames:dimNames}},toString:function(){return def.query(this.dimensions).select(function(dimSpec){return''+dimSpec}).array().join('|')}});def.type('pvc.data.GroupingDimensionSpec').init(function(name,reverse,type){this.name=name;this.reverse=!!reverse;this.id=this.name+":"+(this.reverse?'0':'1');if(type){this.bind(type)}}).add({type:null,comparer:null,bind:function(type){type||def.fail.argumentRequired('type');this.type=type.dimensions(this.name);this.comparer=this.type.atomComparer(this.reverse)},compareDatums:function(a,b){var result=this.comparer(a.atoms[this.name],b.atoms[this.name]);if(result!==0){return result}return 0},toString:function(){return this.name+(this.reverse?' desc':'')}});pvc.data.GroupingSpec.parse=function(specText,type){if(!specText){return new pvc.data.GroupingSpec(null,type)}var levels;if(def.array.is(specText)){levels=specText}else if(def.string.is(specText)){levels=specText.split(/\s*,\s*/)}var levelSpecs=def.query(levels).select(function(levelText){var dimSpecs=groupSpec_parseGroupingLevel(levelText,type);return new pvc.data.GroupingLevelSpec(dimSpecs,type)});return new pvc.data.GroupingSpec(levelSpecs,type)};var groupSpec_matchDimSpec=/^\s*(.+?)(?:\s+(asc|desc))?\s*$/i;function groupSpec_parseGroupingLevel(groupLevelText,type){def.string.is(groupLevelText)||def.fail.argumentInvalid('groupLevelText',"Invalid grouping specification.");return def.query(groupLevelText.split(/\s*\|\s*/)).where(def.truthy).select(function(dimSpecText){var match=groupSpec_matchDimSpec.exec(dimSpecText)||def.fail.argumentInvalid('groupLevelText',"Invalid grouping level syntax '{0}'.",[dimSpecText]),name=match[1],order=(match[2]||'').toLowerCase(),reverse=order==='desc';return new pvc.data.GroupingDimensionSpec(name,reverse,type)})}
def.type('pvc.data.DataOper').init(function(linkParent,keyArgs){this._linkParent=linkParent}).add({key:null,execute:def.method({isAbstract:true})});
def.type('pvc.data.GroupingOper',pvc.data.DataOper).init(function(linkParent,groupingSpecs,keyArgs){groupingSpecs||def.fail.argumentRequired('groupingSpecs');this.base(linkParent,keyArgs);this._where=def.get(keyArgs,'where');this._visible=def.get(keyArgs,'visible',null);this._selected=def.get(keyArgs,'selected',null);this._isNull=def.get(keyArgs,'isNull',null);var hasKey=this._selected==null,whereKey='';if(this._where){whereKey=def.get(keyArgs,'whereKey');if(!whereKey){if(!keyArgs||whereKey===null){hasKey=false}else{whereKey=''+def.nextId('dataOperWhereKey');keyArgs.whereKey=whereKey}}}var ids=[];this._groupSpecs=def.array.as(groupingSpecs).map(function(groupSpec){if(groupSpec instanceof pvc.data.GroupingSpec){if(groupSpec.type!==linkParent.type){throw def.error.argumentInvalid('groupingSpecText',"Invalid associated complex type.")}}else{groupSpec=pvc.data.GroupingSpec.parse(groupSpec,linkParent.type)}ids.push(groupSpec.id);return groupSpec});if(hasKey){this.key=ids.join('!!')+"||visible:"+this._visible+"||isNull:"+this._isNull+"||where:"+whereKey}}).add({execute:function(){var datumsQuery=data_whereState(def.query(this._linkParent._datums),{visible:this._visible,selected:this._selected,isNull:this._isNull,where:this._where});var rootNode=this._group(datumsQuery);return this._generateData(rootNode,null,this._linkParent)},executeAdd:function(rootData,datums){var datumsQuery=data_whereState(def.query(datums),{visible:this._visible,selected:this._selected,isNull:this._isNull,where:this._where});var rootNode=this._group(datumsQuery);this._generateData(rootNode,null,this._linkParent,rootData);return rootNode.datums},_group:function(datumsQuery){var rootNode={isRoot:true,treeHeight:def.query(this._groupSpecs).select(function(spec){var levelCount=spec.levels.length;if(!levelCount){return 0}return!!spec.flatteningMode?1:levelCount}).reduce(def.add,0),datums:[]};if(rootNode.treeHeight>0){this._groupSpecRecursive(rootNode,datumsQuery,0)}return rootNode},_groupSpecRecursive:function(specParentNode,specDatumsQuery,specIndex){var groupSpec=this._groupSpecs[specIndex];var levelSpecs=groupSpec.levels;var L=levelSpecs.length;var doFlatten=!!groupSpec.flatteningMode;var nextSpecIndex=specIndex+1;var isLastSpec=(nextSpecIndex>=this._groupSpecs.length);var isPostOrder=doFlatten&&(groupSpec.flatteningMode==='tree-post');var specGroupParent;if(doFlatten){specParentNode.children=[];specParentNode.childrenByKey={};specGroupParent={key:'',absKey:'',atoms:{},datums:[],label:groupSpec.flattenRootLabel,dimNames:[]};if(!isPostOrder){specParentNode.children.push(specGroupParent);specParentNode.childrenByKey['']=specGroupParent}}else{specGroupParent=specParentNode}groupLevelRecursive.call(this,specGroupParent,specDatumsQuery,0);if(doFlatten){if(isPostOrder){specParentNode.children.push(specGroupParent)}specParentNode.datums=specGroupParent.datums}function groupLevelRecursive(levelParentNode,levelDatums,levelIndex){var levelSpec=levelSpecs[levelIndex];if(!doFlatten){levelParentNode.children=[];levelParentNode.groupSpec=groupSpec;levelParentNode.groupLevelSpec=levelSpec}var childNodes=this._groupDatums(levelSpec,levelParentNode,levelDatums,doFlatten);var isLastSpecLevel=levelIndex===L-1;var willRecurseParent=doFlatten&&!isLastSpec;var levelParentDatums=willRecurseParent?[]:levelParentNode.datums;childNodes.forEach(function(child){var childDatums=child.datums;if(!(isLastSpec&&isLastSpecLevel)){child.datums=[]}var specParentChildIndex;if(!doFlatten){levelParentNode.children.push(child)}else{def.array.lazy(levelParentNode,'_children').push(child);if(def.hasOwn(specParentNode.childrenByKey,child.key)){def.array.append(levelParentDatums,childDatums);return}specParentChildIndex=specParentNode.children.length;if(!isPostOrder){specParentNode.children.push(child);specParentNode.childrenByKey[child.key]=child;levelParentNode.isFlattenGroup=true}}if(!isLastSpecLevel){groupLevelRecursive.call(this,child,childDatums,levelIndex+1)}else if(!isLastSpec){this._groupSpecRecursive(child,childDatums,nextSpecIndex)}def.array.append(levelParentDatums,child.datums);if(doFlatten&&isPostOrder){if(def.hasOwn(specParentNode.childrenByKey,child.key)){child.isFlattenGroup||def.assert("Must be a parent for duplicate keys to exist.");if(child._children.length===1){specParentNode.children.splice(specParentChildIndex,specParentNode.children.length-specParentChildIndex);child.isDegenerateFlattenGroup=true}}specParentNode.children.push(child);specParentNode.childrenByKey[child.key]=child;levelParentNode.isFlattenGroup=true}},this);if(willRecurseParent){this._groupSpecRecursive(levelParentNode,levelParentDatums,nextSpecIndex)}}},_groupDatums:function(levelSpec,levelParentNode,levelDatums,doFlatten){var firstDatums=[];var childNodes=new def.OrderedMap();def.query(levelDatums).each(function(datum){var newChild=levelSpec.key(datum);var key=newChild.key;var child=childNodes.get(key);if(child){child.datums.push(datum)}else{child=newChild;child.datums=[datum];if(doFlatten){def.copy(child.atoms,levelParentNode.atoms);if(levelParentNode.dimNames.length){var keySep=datum.owner.keySep;child.absKey=levelParentNode.absKey+keySep+key;var K=keySep.length;var trimKey=child.absKey;while(trimKey.lastIndexOf(keySep)===trimKey.length-K){trimKey=trimKey.substr(0,trimKey.length-K)}child.key=trimKey}else{child.absKey=key}child.dimNames=levelSpec.accDimensionNames()}var datumIndex=def.array.insert(firstDatums,datum,levelSpec.comparer);childNodes.add(key,child,~datumIndex)}});return childNodes},_generateData:function(node,parentNode,parentData,rootData){var data,isNew;if(node.isRoot){if(rootData){data=rootData;data_addDatumsLocal.call(data,node.datums)}else{isNew=true;data=new pvc.data.Data({linkParent:parentData,datums:node.datums});data.treeHeight=node.treeHeight;data._groupOper=this}}else{if(rootData){data=def.get(parentData._childrenByKey,node.key);if(data){data_addDatumsSimple.call(data,node.datums)}}if(!data){isNew=true;var index,siblings;if(rootData&&(siblings=parentData._children)){index=~def.array.binarySearch(siblings,node.datums[0],parentNode.groupLevelSpec.comparer)}data=new pvc.data.Data({parent:parentData,atoms:node.atoms,dimNames:node.dimNames,datums:node.datums,index:index})}}if(isNew&&node.isFlattenGroup){data._isFlattenGroup=true;data._isDegenerateFlattenGroup=!!node.isDegenerateFlattenGroup;var label=node.label;if(label){data.label+=label;data.absLabel+=label}}var childNodes=node.children;if(childNodes&&childNodes.length){if(isNew){data._groupSpec=node.groupSpec;data._groupLevelSpec=node.groupLevelSpec}childNodes.forEach(function(childNode){this._generateData(childNode,node,data,rootData)},this)}else if(isNew&&!node.isRoot){var leafs=data.root._leafs;data.leafIndex=leafs.length;leafs.push(data)}return data}});
def.type('pvc.data.LinearInterpolationOper').init(function(allPartsData,data,catRole,serRole,valRole,stretchEnds){this._newDatums=[];this._data=data;var allCatDataRoot=allPartsData.flattenBy(catRole,{ignoreNulls:false});var allCatDatas=allCatDataRoot._children;var serDatas1=this._serDatas1=serRole.isBound()?data.flattenBy(serRole).children().array():[null];this._isCatDiscrete=catRole.grouping.isDiscrete();this._firstCatDim=!this._isCatDiscrete?data.owner.dimensions(catRole.firstDimensionName()):null;this._stretchEnds=stretchEnds;var valDim=this._valDim=data.owner.dimensions(valRole.firstDimensionName());var visibleKeyArgs={visible:true,zeroIfNone:false};this._catInfos=allCatDatas.map(function(allCatData,catIndex){var catData=data._childrenByKey[allCatData.key];var catInfo={data:catData||allCatData,value:allCatData.value,isInterpolated:false,serInfos:null,index:catIndex};catInfo.serInfos=serDatas1.map(function(serData1){var group=catData;if(group&&serData1){group=group._childrenByKey[serData1.key]}var value=group?group.dimensions(valDim.name).sum(visibleKeyArgs):null;return{data:serData1,group:group,value:value,isNull:value==null,catInfo:catInfo}},this);return catInfo});this._serCount=serDatas1.length;this._serStates=def.range(0,this._serCount).select(function(serIndex){return new pvc.data.LinearInterpolationOperSeriesState(this,serIndex)},this).array()}).add({interpolate:function(){var catInfo;while((catInfo=this._catInfos.shift())){catInfo.serInfos.forEach(this._visitSeries,this)}var newDatums=this._newDatums;if(newDatums.length){this._data.owner.add(newDatums)}},_visitSeries:function(catSerInfo,serIndex){this._serStates[serIndex].visit(catSerInfo)},nextUnprocessedNonNullCategOfSeries:function(serIndex){var catIndex=0,catCount=this._catInfos.length;while(catIndex<catCount){var catInfo=this._catInfos[catIndex++];var catSerInfo=catInfo.serInfos[serIndex];if(!catSerInfo.isNull){return catSerInfo}}}});
def.type('pvc.data.LinearInterpolationOperSeriesState').init(function(interpolation,serIndex){this.interpolation=interpolation;this.index=serIndex;this._lastNonNull(null)}).add({visit:function(catSeriesInfo){if(catSeriesInfo.isNull){this._interpolate(catSeriesInfo)}else{this._lastNonNull(catSeriesInfo)}},_lastNonNull:function(catSerInfo){if(arguments.length){this.__lastNonNull=catSerInfo;this.__nextNonNull=undefined}return this.__lastNonNull},_nextNonNull:function(){return this.__nextNonNull},_initInterpData:function(){if(this.__nextNonNull!==undefined){return}var last=this.__lastNonNull;var next=this.__nextNonNull=this.interpolation.nextUnprocessedNonNullCategOfSeries(this.index)||null;if(next&&last){var fromValue=last.value;var toValue=next.value;var deltaValue=toValue-fromValue;if(this.interpolation._isCatDiscrete){var stepCount=next.catInfo.index-last.catInfo.index;(stepCount>=2)||def.assert("Must have at least one interpolation point.");this._stepValue=deltaValue/stepCount;this._middleIndex=~~(stepCount/2); var dotCount=(stepCount-1);this._isOdd=(dotCount%2)>0}else{var fromCat=+last.catInfo.value;var toCat=+next.catInfo.value;var deltaCat=toCat-fromCat;this._steep=deltaValue/deltaCat; this._middleCat=(toCat+fromCat)/2}}},_interpolate:function(catSerInfo){this._initInterpData();var next=this.__nextNonNull;var last=this.__lastNonNull;var one=next||last;if(!one){return}var value,group;var interpolation=this.interpolation;var catInfo=catSerInfo.catInfo;if(next&&last){if(interpolation._isCatDiscrete){var groupIndex=(catInfo.index-last.catInfo.index);value=last.value+this._stepValue*groupIndex;if(this._isOdd){group=groupIndex<this._middleIndex?last.group:next.group}else{group=groupIndex<=this._middleIndex?last.group:next.group}}else{var cat=+catInfo.value;var lastCat=+last.catInfo.value;value=last.value+this._steep*(cat-lastCat);group=cat<this._middleCat?last.group:next.group}}else{if(!interpolation._stretchEnds){return}value=one.value;group=one.group}var atoms=Object.create(group._datums[0].atoms);def.copyOwn(atoms,catInfo.data.atoms);var valueAtom=interpolation._valDim.intern(value,true);atoms[valueAtom.dimension.name]=valueAtom;var newDatum=new pvc.data.Datum(group.owner,atoms);newDatum.isVirtual=true;newDatum.isInterpolated=true;newDatum.interpolation='linear';interpolation._newDatums.push(newDatum)}});
def.type('pvc.data.ZeroInterpolationOper').init(function(allPartsData,data,catRole,serRole,valRole,stretchEnds){this._newDatums=[];this._data=data;var allCatDataRoot=allPartsData.flattenBy(catRole,{ignoreNulls:false});var allCatDatas=allCatDataRoot._children;var serDatas1=this._serDatas1=serRole.isBound()?data.flattenBy(serRole).children().array():[null];this._isCatDiscrete=catRole.grouping.isDiscrete();this._firstCatDim=!this._isCatDiscrete?data.owner.dimensions(catRole.firstDimensionName()):null;this._stretchEnds=stretchEnds;var valDim=this._valDim=data.owner.dimensions(valRole.firstDimensionName());var visibleKeyArgs={visible:true,zeroIfNone:false};this._catInfos=allCatDatas.map(function(allCatData,catIndex){var catData=data._childrenByKey[allCatData.key];var catInfo={data:catData||allCatData,value:allCatData.value,isInterpolated:false,serInfos:null,index:catIndex};catInfo.serInfos=serDatas1.map(function(serData1){var group=catData;if(group&&serData1){group=group._childrenByKey[serData1.key]}var value=group?group.dimensions(valDim.name).sum(visibleKeyArgs):null;return{data:serData1,group:group,value:value,isNull:value==null,catInfo:catInfo}},this);return catInfo});this._serCount=serDatas1.length;this._serStates=def.range(0,this._serCount).select(function(serIndex){return new pvc.data.ZeroInterpolationOperSeriesState(this,serIndex)},this).array()}).add({interpolate:function(){var catInfo;while((catInfo=this._catInfos.shift())){catInfo.serInfos.forEach(this._visitSeries,this)}var newDatums=this._newDatums;if(newDatums.length){this._data.owner.add(newDatums)}},_visitSeries:function(catSerInfo,serIndex){this._serStates[serIndex].visit(catSerInfo)},nextUnprocessedNonNullCategOfSeries:function(serIndex){var catIndex=0,catCount=this._catInfos.length;while(catIndex<catCount){var catInfo=this._catInfos[catIndex++];var catSerInfo=catInfo.serInfos[serIndex];if(!catSerInfo.isNull){return catSerInfo}}}});
def.type('pvc.data.ZeroInterpolationOperSeriesState').init(function(interpolation,serIndex){this.interpolation=interpolation;this.index=serIndex;this._lastNonNull(null)}).add({visit:function(catSeriesInfo){if(catSeriesInfo.isNull){this._interpolate(catSeriesInfo)}else{this._lastNonNull(catSeriesInfo)}},_lastNonNull:function(catSerInfo){if(arguments.length){this.__lastNonNull=catSerInfo;this.__nextNonNull=undefined}return this.__lastNonNull},_nextNonNull:function(){return this.__nextNonNull},_initInterpData:function(){if(this.__nextNonNull!==undefined){return}var last=this.__lastNonNull;var next=this.__nextNonNull=this.interpolation.nextUnprocessedNonNullCategOfSeries(this.index)||null;if(next&&last){var fromValue=last.value;var toValue=next.value;var deltaValue=toValue-fromValue;if(this.interpolation._isCatDiscrete){var stepCount=next.catInfo.index-last.catInfo.index;(stepCount>=2)||def.assert("Must have at least one interpolation point.");this._middleIndex=~~(stepCount/2); var dotCount=(stepCount-1);this._isOdd=(dotCount%2)>0}else{var fromCat=+last.catInfo.value;var toCat=+next.catInfo.value;this._middleCat=(toCat+fromCat)/2}}},_interpolate:function(catSerInfo){this._initInterpData();var next=this.__nextNonNull;var last=this.__lastNonNull;var one=next||last;if(!one){return}var group;var interpolation=this.interpolation;var catInfo=catSerInfo.catInfo;if(next&&last){if(interpolation._isCatDiscrete){var groupIndex=(catInfo.index-last.catInfo.index);if(this._isOdd){group=groupIndex<this._middleIndex?last.group:next.group}else{group=groupIndex<=this._middleIndex?last.group:next.group}}else{var cat=+catInfo.value;group=cat<this._middleCat?last.group:next.group}}else{if(!interpolation._stretchEnds){return}group=one.group}var atoms=Object.create(group._datums[0].atoms);def.copyOwn(atoms,catInfo.data.atoms);var zeroAtom=interpolation._zeroAtom||(interpolation._zeroAtom=interpolation._valDim.intern(0,true));atoms[zeroAtom.dimension.name]=zeroAtom;var newDatum=new pvc.data.Datum(group.owner,atoms);newDatum.isVirtual=true;newDatum.isInterpolated=true;newDatum.interpolation='zero';interpolation._newDatums.push(newDatum)}});
pvc.data.Data.add({load:function(atomz,keyArgs){data_assertIsOwner.call(this);var whereFun=def.get(keyArgs,'where');var isNullFun=def.get(keyArgs,'isNull');var datums=def.query(atomz).select(function(atoms){var datum=new pvc.data.Datum(this,atoms);if(isNullFun&&isNullFun(datum)){datum.isNull=true}if(whereFun&&!whereFun(datum)){return null}return datum},this);data_setDatums.call(this,datums,{doAtomGC:true})},clearVirtuals:function(){var datums=this._datums;if(datums){this._sumAbsCache=null;var visibleDatums=this._visibleDatums;var selectedDatums=this._selectedDatums;var i=0;var L=datums.length;var removed;while(i<L){var datum=datums[i];if(datum.isVirtual){var id=datum.id;if(selectedDatums&&datum.isSelected){selectedDatums.rem(id)}if(datum.isVisible){visibleDatums.rem(id)}datums.splice(i,1);L--;removed=true}else{i++}}if(removed){if(!datums.length&&this.parent){this.dispose();return}var children=this._children;if(children){i=0;L=children.length;while(i<L){var childData=children[i];childData.clearVirtuals();if(!childData.parent){L--}else{i++}}}if(this._linkChildren){this._linkChildren.forEach(function(linkChildData){linkChildData.clearVirtuals()})}}}def.eachOwn(this._dimensions,function(dim){dim_uninternVirtualAtoms.call(dim)})},add:function(datums){data_assertIsOwner.call(this);data_setDatums.call(this,datums,{isAdditive:true,doAtomGC:true})},groupBy:function(groupingSpecText,keyArgs){var groupOper=new pvc.data.GroupingOper(this,groupingSpecText,keyArgs),cacheKey=groupOper.key,groupByCache,data;if(cacheKey){groupByCache=this._groupByCache;data=groupByCache&&groupByCache[cacheKey]}if(!data){if(pvc.debug>=7){pvc.log("[GroupBy] "+(cacheKey?("Cache key not found: '"+cacheKey+"'"):"No Cache key"))}data=groupOper.execute();if(cacheKey){(groupByCache||(this._groupByCache={}))[cacheKey]=data}}else if(pvc.debug>=7){pvc.log("[GroupBy] Cache key hit '"+cacheKey+"'")}return data},flattenBy:function(role,keyArgs){var grouping=role.flattenedGrouping(keyArgs)||def.fail.operationInvalid("Role is unbound.");return this.groupBy(grouping,keyArgs)},where:function(whereSpec,keyArgs){var datums=this.datums(whereSpec,keyArgs);return new pvc.data.Data({linkParent:this,datums:datums})},datums:function(whereSpec,keyArgs){if(!whereSpec){if(!keyArgs){return def.query(this._datums)}return data_whereState(def.query(this._datums),keyArgs)}whereSpec=data_processWhereSpec.call(this,whereSpec,keyArgs);return data_where.call(this,whereSpec,keyArgs)},datum:function(whereSpec,keyArgs){whereSpec||def.fail.argumentRequired('whereSpec');whereSpec=data_processWhereSpec.call(this,whereSpec,keyArgs);var datum=data_where.call(this,whereSpec,keyArgs).first()||null;if(!datum&&def.get(keyArgs,'createNull')&&whereSpec.length){var sourceDatumFilter=whereSpec[0],atoms={};for(var dimName in this._dimensions){var dimAtoms=sourceDatumFilter[dimName];if(dimAtoms){atoms[dimName]=dimAtoms[0]}}datum=new pvc.data.Datum(this,atoms,true)}return datum},firstDatum:function(){return this._datums.length?this._datums[0]:null},dimensionsSumAbs:function(dimName,keyArgs){var key=dimName+":"+dim_buildDatumsFilterKey(keyArgs),sum=def.getOwn(this._sumAbsCache,key);if(sum==null){sum=this.children().where(function(childData){return!childData._isFlattenGroup||childData._isDegenerateFlattenGroup}).select(function(childData){return Math.abs(childData.dimensions(dimName).sum(keyArgs))},this).reduce(def.add,0);(this._sumAbsCache||(this._sumAbsCache={}))[key]=sum}return sum}});function data_setDatums(newDatums,keyArgs){newDatums||def.fail.argumentRequired('newDatums');var doAtomGC=def.get(keyArgs,'doAtomGC',false);var isAdditive=def.get(keyArgs,'isAdditive',false);var visibleDatums=this._visibleDatums;var selectedDatums=this._selectedDatums;var newDatumsByKey={};var prevDatumsByKey;var prevDatums=this._datums;if(prevDatums){var processPrevAtoms=isAdditive&&doAtomGC;prevDatumsByKey=def.query(prevDatums).uniqueIndex(function(datum){if(processPrevAtoms){data_processDatumAtoms.call(this,datum,false,true)}return datum.key},this);if(isAdditive){this._sumAbsCache=null}else{data_disposeChildLists.call(this);if(selectedDatums){selectedDatums.clear()}visibleDatums.clear()}}else{isAdditive=false}var datumsById;if(isAdditive){datumsById=this._datumsById}else{datumsById=this._datumsById={}}if(def.array.is(newDatums)){var i=0;var L=newDatums.length;while(i<L){var inDatum=newDatums[i];var outDatum=setDatum.call(this,inDatum);if(!outDatum){newDatums.splice(i,1);L--}else{if(outDatum!==inDatum){newDatums[i]=outDatum}i++}}}else if(newDatums instanceof def.Query){newDatums=newDatums.select(setDatum,this).where(def.notNully).array()}else{throw def.error.argumentInvalid('newDatums',"Argument is of invalid type.")}if(doAtomGC){def.eachOwn(this._dimensions,function(dimension){dim_uninternUnvisitedAtoms.call(dimension)})}if(isAdditive){def.array.append(prevDatums,newDatums);if(this._linkChildren){this._linkChildren.forEach(function(linkChildData){data_addDatumsSimple.call(linkChildData,newDatums)})}}else{this._datums=newDatums}function setDatum(newDatum){if(!newDatum){return}var key=newDatum.key;if(def.hasOwnProp.call(newDatumsByKey,key)){return}if(prevDatumsByKey){var prevDatum=def.getOwn(prevDatumsByKey,key);if(prevDatum){if(isAdditive){return}newDatum=prevDatum}}newDatumsByKey[key]=newDatum;var id=newDatum.id;datumsById[id]=newDatum;data_processDatumAtoms.call(this,newDatum,!!this._dimensions,doAtomGC);if(!newDatum.isNull){if(selectedDatums&&newDatum.isSelected){selectedDatums.set(id,newDatum)}if(newDatum.isVisible){visibleDatums.set(id,newDatum)}}return newDatum}}function data_processDatumAtoms(datum,intern,markVisited){var dims=this._dimensions;if(!dims){intern=false}def.each(datum.atoms,function(atom){if(intern){var localDim=def.getOwn(dims,atom.dimension.name)||def.fail.argumentInvalid("Datum has atoms of foreign dimension.");dim_internAtom.call(localDim,atom)}if(markVisited){atom.visited=true}})}function data_addDatumsSimple(newDatums){newDatums||def.fail.argumentRequired('newDatums');var groupOper=this._groupOper;if(groupOper){newDatums=groupOper.executeAdd(this,newDatums)}else{data_addDatumsLocal.call(this,newDatums)}if(this._linkChildren){this._linkChildren.forEach(function(linkChildData){data_addDatumsSimple.call(linkChildData,newDatums)})}}function data_addDatumsLocal(newDatums){var visibleDatums=this._visibleDatums;var selectedDatums=this._selectedDatums;this._sumAbsCache=null;var datumsById=this._datumsById;var datums=this._datums;newDatums.forEach(addDatum,this);function addDatum(newDatum){var id=newDatum.id;datumsById[id]=newDatum;data_processDatumAtoms.call(this,newDatum,true,false);if(!newDatum.isNull){if(selectedDatums&&newDatum.isSelected){selectedDatums.set(id,newDatum)}if(newDatum.isVisible){visibleDatums.set(id,newDatum)}}datums.push(newDatum)}}function data_processWhereSpec(whereSpec){var whereProcSpec=[];whereSpec=def.array.as(whereSpec);if(whereSpec){whereSpec.forEach(processDatumFilter,this)}return whereProcSpec;function processDatumFilter(datumFilter){if(datumFilter!=null){(typeof datumFilter==='object')||def.fail.invalidArgument('datumFilter');var datumProcFilter={},any=false;for(var dimName in datumFilter){var atoms=processDimensionFilter.call(this,dimName,datumFilter[dimName]);if(atoms){any=true;datumProcFilter[dimName]=atoms}}if(any){whereProcSpec.push(datumProcFilter)}}}function processDimensionFilter(dimName,values){var dimension=this.dimensions(dimName),atoms=def.query(values).select(function(value){return dimension.atom(value)}).where(def.notNully).distinct(function(atom){return atom.key}).array();return atoms.length?atoms:null}}function data_whereState(q,keyArgs){var selected=def.get(keyArgs,'selected'),visible=def.get(keyArgs,'visible'),where=def.get(keyArgs,'where'),isNull=def.get(keyArgs,'isNull');if(visible!=null){q=q.where(function(datum){return datum.isVisible===visible})}if(isNull!=null){q=q.where(function(datum){return datum.isNull===isNull})}if(selected!=null){q=q.where(function(datum){return datum.isSelected===selected})}if(where){q=q.where(where)}return q}function data_where(whereSpec,keyArgs){var orderBys=def.array.as(def.get(keyArgs,'orderBy')),datumKeyArgs=def.create(keyArgs||{},{orderBy:null});var query=def.query(whereSpec).selectMany(function(datumFilter,index){if(orderBys){datumKeyArgs.orderBy=orderBys[index]}return data_whereDatumFilter.call(this,datumFilter,datumKeyArgs)},this);return query.distinct(function(datum){return datum.id})}function data_whereDatumFilter(datumFilter,keyArgs){var groupingSpecText=keyArgs.orderBy;if(!groupingSpecText){groupingSpecText=Object.keys(datumFilter).sort().join(',')}else{if(groupingSpecText.indexOf("|")>=0){throw def.error.argumentInvalid('keyArgs.orderBy',"Multi-dimension order by is not supported.")}}var rootData=this.groupBy(groupingSpecText,keyArgs),H=rootData.treeHeight;var stateStack=[];return def.query(function(){var state;if(!this._data){this._data=rootData;this._dimAtomsOrQuery=def.query(datumFilter[rootData._groupLevelSpec.dimensions[0].name])}else if(this._datumsQuery){this._data||def.assert("Must have a current data");stateStack.length||def.assert("Must have a parent data");!this._dimAtomsOrQuery||def.assert();if(this._datumsQuery.next()){this.item=this._datumsQuery.item;return 1}this._datumsQuery=null;state=stateStack.pop();this._data=state.data;this._dimAtomsOrQuery=state.dimAtomsOrQuery}this._dimAtomsOrQuery||def.assert("Invalid programmer");this._data||def.assert("Must have a current data");var depth=stateStack.length;do{while(this._dimAtomsOrQuery.next()){var dimAtomOr=this._dimAtomsOrQuery.item,childData=this._data._childrenByKey[dimAtomOr.key];if(childData&&(depth<H-1||childData._datums.length)){stateStack.push({data:this._data,dimAtomsOrQuery:this._dimAtomsOrQuery});this._data=childData;if(depth<H-1){this._dimAtomsOrQuery=def.query(datumFilter[childData._groupLevelSpec.dimensions[0].name]);depth++}else{this._dimAtomsOrQuery=null;this._datumsQuery=def.query(childData._datums);this._datumsQuery.next();this.item=this._datumsQuery.item;return 1}}}if(!depth){return 0}state=stateStack.pop();this._data=state.data;this._dimAtomsOrQuery=state.dimAtomsOrQuery;depth--}while(true);return 0})}
pvc.data.Data.add({getInfo:function(){var out=["DATA SUMMARY",pvc.logSeparator,"  Dimension",pvc.logSeparator];def.eachOwn(this.dimensions(),function(dimension,name){var count=dimension.count(),type=dimension.type,features=[];features.push('"'+type.label+'"');features.push(type.valueTypeName);if(type.isComparable){features.push("comparable")}if(!type.isDiscrete){features.push("continuous")}if(type.isHidden){features.push("hidden")}out.push("  "+name+" ("+features.join(', ')+")"+" ("+count+")\n\t"+dimension.atoms().slice(0,10).map(function(atom){return atom.label}).join(", ")+(count>10?"...":""))});return out.join("\n")},getValues:function(){return pv.range(0,this.getCategoriesSize()).map(function(categIndex){return this._getValuesForCategoryIndex(categIndex)},this)},_getDimensionValues:function(name){return this.dimensions(name).atoms().map(function(atom){return atom.value})},_getDimensionVisibleValues:function(name){return this.dimensions(name).atoms({visible:true}).map(function(atom){return atom.value})},getSeries:function(){return this._getDimensionValues('series')},getVisibleSeriesIndexes:function(){return this.dimensions('series').indexes({visible:true})},getVisibleCategoriesIndexes:function(){return this.dimensions('category').indexes({visible:true})},getVisibleSeries:function(){return this._getDimensionVisibleValues('series')},getCategories:function(){return this._getDimensionValues('category')},getVisibleCategories:function(){return this._getDimensionVisibleValues('category')},_getValuesForCategoryIndex:function(categIdx){var categAtom=this.dimensions('category').atoms()[categIdx];var datumsBySeriesKey=this.datums({category:categAtom}).uniqueIndex(function(datum){return datum.atoms.series.key});return this.dimensions('series').atoms().map(function(atom){var datum=def.getOwn(datumsBySeriesKey,atom.key);return datum?datum.atoms.value.value:null})},getSeriesSize:function(){var dim=this.dimensions('series',{assertExists:false});return dim?dim.count():0},getCategoriesSize:function(){var dim=this.dimensions('category',{assertExists:false});return dim?dim.count():0}});
def.type('pvc.visual.Role').init(function(name,keyArgs){this.name=name;this.label=def.get(keyArgs,'label')||pvc.buildTitleFromName(name);this.index=def.get(keyArgs,'index')||0;this.dimensionDefaults=def.get(keyArgs,'dimensionDefaults')||{};if(def.get(keyArgs,'isRequired',false)){this.isRequired=true}if(def.get(keyArgs,'autoCreateDimension',false)){this.autoCreateDimension=true}var defaultSourceRoleName=def.get(keyArgs,'defaultSourceRole');if(defaultSourceRoleName){this.defaultSourceRoleName=defaultSourceRoleName}var defaultDimensionName=def.get(keyArgs,'defaultDimension');if(defaultDimensionName){this.defaultDimensionName=defaultDimensionName}if(!defaultDimensionName&&this.autoCreateDimension){throw def.error.argumentRequired('defaultDimension')}var requireSingleDimension;var requireIsDiscrete=def.get(keyArgs,'requireIsDiscrete');if(requireIsDiscrete!=null){if(!requireIsDiscrete){requireSingleDimension=true}}if(requireSingleDimension!=null){requireSingleDimension=def.get(keyArgs,'requireSingleDimension',false);if(requireSingleDimension){if(def.get(keyArgs,'isMeasure',false)){this.isMeasure=true;if(def.get(keyArgs,'isPercent',false)){this.isPercent=true}}var valueType=def.get(keyArgs,'valueType',null);if(valueType!==this.valueType){this.valueType=valueType;this.dimensionDefaults.valueType=valueType}}}if(requireSingleDimension!==this.requireSingleDimension){this.requireSingleDimension=requireSingleDimension}if(requireIsDiscrete!=this.requireIsDiscrete){this.requireIsDiscrete=!!requireIsDiscrete;this.dimensionDefaults.isDiscrete=this.requireIsDiscrete}var flatteningMode=def.get(keyArgs,'flatteningMode');if(flatteningMode&&flatteningMode!=this.flatteningMode){this.flatteningMode=flatteningMode}}).add({isRequired:false,requireSingleDimension:false,valueType:null,requireIsDiscrete:null,isMeasure:false,isPercent:false,defaultSourceRoleName:null,defaultDimensionName:null,grouping:null,flatteningMode:'singleLevel',flattenRootLabel:'',autoCreateDimension:false,isReversed:false,label:null,sourceRole:null,firstDimensionType:function(){var g=this.grouping;return g&&g.firstDimensionType()},firstDimensionName:function(){var g=this.grouping;return g&&g.firstDimensionName()},firstDimensionValueType:function(){var g=this.grouping;return g&&g.firstDimensionValueType()},isDiscrete:function(){var g=this.grouping;return g&&g.isDiscrete()},setSourceRole:function(sourceRole){this.sourceRole=sourceRole},setIsReversed:function(isReversed){if(!isReversed){delete this.isReversed}else{this.isReversed=true}},setFlatteningMode:function(flatteningMode){if(!flatteningMode||flatteningMode==='singleLevel'){delete this.flatteningMode}else{this.flatteningMode=flatteningMode}},setFlattenRootLabel:function(flattenRootLabel){if(!flattenRootLabel){delete this.flattenRootLabel}else{this.flattenRootLabel=flattenRootLabel}},flatten:function(data,keyArgs){if(this.grouping){return data.flattenBy(this,keyArgs)}},flattenedGrouping:function(keyArgs){var grouping=this.grouping;if(grouping){keyArgs=def.setDefaults(keyArgs,'flatteningMode',this.flatteningMode,'flattenRootLabel',this.flattenRootLabel);return grouping.ensure(keyArgs)}},select:function(data,keyArgs){var grouping=this.grouping;if(grouping){return data.groupBy(grouping.ensure(keyArgs),keyArgs)}},view:function(complex){var grouping=this.grouping;if(grouping){return grouping.view(complex)}},preBind:function(groupingSpec){this.__grouping=groupingSpec;return this},isPreBound:function(){return!!this.__grouping},preBoundGrouping:function(){return this.__grouping},isBound:function(){return!!this.grouping},postBind:function(type){var grouping=this.__grouping;if(grouping){delete this.__grouping;grouping.bind(type);this.bind(grouping)}return this},bind:function(groupingSpec){if(groupingSpec){if(groupingSpec.isNull()){groupingSpec=null}else{if(this.requireSingleDimension&&!groupingSpec.isSingleDimension){throw def.error.operationInvalid("Role '{0}' only accepts a single dimension.",[this.name])}var valueType=this.valueType;var requireIsDiscrete=this.requireIsDiscrete;groupingSpec.dimensions().each(function(dimSpec){var dimType=dimSpec.type;if(valueType&&dimType.valueType!==valueType){throw def.error.operationInvalid("Role '{0}' cannot be bound to dimension '{1}'. \nIt only accepts dimensions of type '{2}' and not of type '{3}'.",[this.name,dimType.name,pvc.data.DimensionType.valueTypeName(valueType),dimType.valueTypeName])}if(requireIsDiscrete!=null&&dimType.isDiscrete!==requireIsDiscrete){if(requireIsDiscrete){dimType._toDiscrete()}else{throw def.error.operationInvalid("Role '{0}' cannot be bound to dimension '{1}'. \nIt only accepts {2} dimensions.",[this.name,dimType.name,requireIsDiscrete?'discrete':'continuous'])}}},this)}}if(this.grouping){this.grouping.dimensions().each(function(dimSpec){if(dimSpec.type){dimType_removeVisualRole.call(dimSpec.type,this)}},this)}this.grouping=groupingSpec;if(this.grouping){if(this.isReversed){this.grouping=this.grouping.reversed()}this.grouping.dimensions().each(function(dimSpec){dimType_addVisualRole.call(dimSpec.type,this)},this)}return this}});
def.type('pvc.visual.Scene').init(function(parent,keyArgs){if(pvc.debug>=4){this.id=def.nextId('scene')}this._renderId=0;this.renderState={};pv.Dom.Node.call(this,null);this.parent=parent||null;this.root=this;if(parent){var index=def.get(keyArgs,'index',null);parent.insertAt(this,index);this.root=parent.root}else{this._active=null;this._panel=def.get(keyArgs,'panel')||def.fail.argumentRequired('panel',"Argument is required on root scene.")}var group=def.get(keyArgs,'group',null),datum;if(group){datum=group._datums[0]}else{datum=def.get(keyArgs,'datum')}this.datum=datum||null;this.group=group;var parentAtoms;var source=(group||datum);this.atoms=source?source.atoms:(parentAtoms=(parent&&parent.atoms))?Object.create(parentAtoms):{};source=(datum||group);this.firstAtoms=source?source.atoms:(parentAtoms=(parent&&parent.firstAtoms))?Object.create(parentAtoms):this.atoms;if(!source){this.isNull=true}this.vars=parent?Object.create(parent.vars):{}}).add(pv.Dom.Node).add({isNull:false,datums:function(){return this.group?this.group.datums():(this.datum?def.query(this.datum):def.query())},format:function(mask){return def.format(mask,this._formatScope,this)},_formatScope:function(prop){if(prop.charAt(0)==='#'){prop=prop.substr(1).split('.');if(prop.length>2){throw def.error.operationInvalid("Scene format mask is invalid.")}var atom=this.atoms[prop[0]];if(atom){if(prop.length>1){switch(prop[1]){case'value':return atom.value;case'label':break;default:throw def.error.operationInvalid("Scene format mask is invalid.")}}return atom}return null}return def.getPath(this.vars,prop)},isRoot:function(){return this.root===this},panel:function(){return this.root._panel},chart:function(){return this.root._panel.chart},compatVersion:function(){return this.root._panel.compatVersion()},children:function(){if(!this.childNodes){return def.query()}return def.query(this.childNodes)},leafs:function(){function getFirstLeafFrom(leaf){while(leaf.childNodes.length){leaf=leaf.childNodes[0]}return leaf}var root=this;return def.query(function(nextIndex){if(!nextIndex){var item=getFirstLeafFrom(root);if(item===root){return 0}this.item=item;return 1}var next=this.item.nextSibling;if(next){this.item=next;return 1}var current=this.item;while((current!==root)&&(current=current.parentNode)){if((next=current.nextSibling)){this.item=getFirstLeafFrom(next);return 1}}return 0})},anyInteraction:function(){return(!!this.root._active||this.anySelected())},isActive:false,setActive:function(isActive){isActive=!!isActive;if(this.isActive!==isActive){rootScene_setActive.call(this.root,this.isActive?null:this)}},clearActive:function(){return rootScene_setActive.call(this.root,null)},anyActive:function(){return!!this.root._active},active:function(){return this.root._active},activeSeries:function(){var active=this.active();var seriesVar;return active&&(seriesVar=active.vars.series)&&seriesVar.value},isActiveSeries:function(){if(this.isActive){return true}var activeSeries;return(activeSeries=this.activeSeries())!=null&&(activeSeries===this.vars.series.value)},isSelected:function(){return this._selectedData().is},anySelected:function(){return this._selectedData().any},_selectedData:function(){return this.renderState._selectedData||(this.renderState._selectedData=this._createSelectedData())},_createSelectedData:function(){var any=this.panel().chart.data.owner.selectedCount()>0,isSelected=any&&this.datums().any(function(datum){return datum.isSelected});return{any:any,is:isSelected}}});function scene_renderId(renderId){if(this._renderId!==renderId){if(pvc.debug>=20){pvc.log({sceneId:this.id,oldRenderId:this._renderId,newRenderId:renderId})}this._renderId=renderId;this.renderState={}}}function rootScene_setActive(scene){var ownerScene;if(scene&&(ownerScene=scene.ownerScene)){scene=ownerScene}if(this._active!==scene){if(this._active){scene_setActive.call(this._active,false)}this._active=scene||null;if(this._active){scene_setActive.call(this._active,true)}return true}return false}function scene_setActive(isActive){isActive=!!isActive;if(this.isActive!==isActive){if(!isActive){delete this.isActive}else{this.isActive=true}}}
pvc.visual.ValueLabelVar=function(value,label,rawValue){this.value=value;this.label=label;if(rawValue!==undefined){this.rawValue=rawValue}};def.set(pvc.visual.ValueLabelVar.prototype,'rawValue',undefined,'clone',function(){return new pvc.visual.ValueLabelVar(this.value,this.label,this.rawValue)},'toString',function(){var label=this.label||this.value;return typeof label!=='string'?(''+label):label});pvc.visual.ValueLabelVar.fromComplex=function(complex){return complex?new pvc.visual.ValueLabelVar(complex.value,complex.label,complex.rawValue):new pvc.visual.ValueLabelVar(null,"",null)};def.type('pvc.visual.RoleVarHelper').init(function(rootScene,role,keyArgs){var g;var hasPercentSubVar=def.get(keyArgs,'hasPercentSubVar',false);if(!def.get(keyArgs,'forceUnbound',false)){this.role=role;this.sourceRoleName=role.sourceRole&&role.sourceRole.name;g=this.grouping=role.grouping;if(g&&!g.isDiscrete()){var panel=rootScene.panel();this.rootContDim=panel.data.owner.dimensions(g.firstDimensionName());if(hasPercentSubVar){this.percentFormatter=panel.chart.options.percentValueFormat}}}if(!g){var roleVar=rootScene.vars[role.name]=new pvc.visual.ValueLabelVar(null,"");if(hasPercentSubVar){roleVar.percent=new pvc.visual.ValueLabelVar(null,"")}}}).add({isBound:function(){return!!this.grouping},onNewScene:function(scene,isLeaf){if(!this.grouping){return}var roleName=this.role.name;if(scene.vars[roleName]){return}var sourceName=this.sourceRoleName;if(sourceName){var sourceVar=def.getOwn(scene.vars,sourceName);if(sourceVar){scene.vars[roleName]=sourceVar.clone();return}}if(isLeaf){var roleVar;var rootContDim=this.rootContDim;if(!rootContDim){var firstDatum=scene.datum;if(firstDatum&&!firstDatum.isNull){var view=this.grouping.view(firstDatum);roleVar=new pvc.visual.ValueLabelVar(view.value,view.label,view.rawValue)}}else{var group=scene.group;var singleDatum=group?group.singleDatum():scene.datum;if(singleDatum){if(!singleDatum.isNull){roleVar=Object.create(singleDatum.atoms[rootContDim.name])}}else if(group){var valueDim=group.dimensions(rootContDim.name);var value=valueDim.sum({visible:true,zeroIfNone:false});var label=rootContDim.format(value);roleVar=new pvc.visual.ValueLabelVar(value,label,value);if(this.percentFormatter){if(value==null){roleVar.percent=new pvc.visual.ValueLabelVar(value,label)}else{var valuePct=valueDim.percentOverParent({visible:true});roleVar.percent=new pvc.visual.ValueLabelVar(valuePct,this.percentFormatter.call(null,valuePct))}}}}scene.vars[roleName]=roleVar||new pvc.visual.ValueLabelVar(null,"")}}});
(function(){pv.Mark.prototype.getSign=function(){return this.sign||createBasic(this)};pv.Mark.prototype.getScene=function(){return this.getSign().scene};function createBasic(pvMark){var as=getAncestorSign(pvMark)||def.assert("There must exist an ancestor sign");var bs=new pvc.visual.BasicSign(as.panel,pvMark);var i;var s=pvMark.scene;if(s&&(i=pvMark.index)!=null&&i>=0){bs._buildInstance(pvMark,s[i],true)}return bs}function getAncestorSign(pvMark){var sign;do{pvMark=pvMark.parent}while(pvMark&&!(sign=pvMark.sign)&&(!pvMark.proto||!(sign=pvMark.proto.sign)));return sign}def.type('pvc.visual.BasicSign').init(function(panel,pvMark){this.chart=panel.chart;this.panel=panel;this.pvMark=pvMark;!pvMark.sign||def.assert("Mark already has an attached Sign.");pvMark.sign=this;pvMark.__buildInstance=pvMark.buildInstance;pvMark.buildInstance=this._dispatchBuildInstance}).add({localProperty:function(name,type){this.pvMark.localProperty(name,type);return this},lock:function(name,value){return this.lockMark(name,this._bindWhenFun(value))},optional:function(name,value,tag){return this.optionalMark(name,this._bindWhenFun(value),tag)},lockMark:function(name,value){this.pvMark.lock(name,value);return this},optionalMark:function(name,value,tag){this.pvMark[name](value,tag);return this},delegate:function(dv,tag){return this.pvMark.delegate(dv,tag)},delegateExtension:function(dv){return this.pvMark.delegate(dv,pvc.extensionTag)},hasDelegate:function(tag){return this.pvMark.hasDelegate(tag)},_bindWhenFun:function(value){if(typeof value==='function'){return function(){var sign=this.getSign();return value.apply(sign,arguments)}}return value},_lockDynamic:function(name,method){var me=this;return this.lockMark(name,function(){var sign=this.getSign();var m=sign[method]||me[method]||def.assert("No method with name '"+method+"' is defined");return m.apply(sign,arguments)})},_dispatchBuildInstance:function(instance){this.sign._buildInstance(this,instance)},_buildInstance:function(mark,instance,lateCall){var scene=instance.data;var index=scene?scene.childIndex():0;this.pvInstance=instance;this.scene=scene;this.index=index<0?0:index;scene_renderId.call(scene,mark.renderId());this.state={};if(!lateCall){mark.__buildInstance.call(mark,instance)}}})}());
def.type('pvc.visual.Sign',pvc.visual.BasicSign).init(function(panel,pvMark,keyArgs){this.base(panel,pvMark,keyArgs);this.bits=0;var extensionIds=def.get(keyArgs,'extensionId');if(extensionIds!=null){this.extensionAbsIds=def.array.to(panel._makeExtensionAbsId(extensionIds))}this.isActiveSeriesAware=def.get(keyArgs,'activeSeriesAware',true)&&!!this.chart.visualRoles('series',{assertExists:false});var wrapper=def.get(keyArgs,'wrapper');if(!wrapper){wrapper=function(f){return function(scene){return f.call(panel._getContext(pvMark),scene)}}}pvMark.wrapper(wrapper);if(!def.get(keyArgs,'freeColor',true)){this._bindProperty('fillStyle','fillColor','color')._bindProperty('strokeStyle','strokeColor','color')}}).postInit(function(panel,pvMark,keyArgs){panel._addSign(this);this._addInteractive(keyArgs)}).add({property:function(name){var upperName=def.firstUpperCase(name);var baseName='base'+upperName;var defName='default'+upperName;var normalName='normal'+upperName;var interName='interactive'+upperName;var methods={};methods[name]=function(arg){delete this._finished;var value;this._arg=arg;try{value=this[baseName](arg);if(value==null){return null}if(this.hasOwnProperty('_finished')){return value}if(this.showsInteraction()&&this.scene.anyInteraction()){value=this[interName](value,arg)}else{value=this[normalName](value,arg)}}finally{delete this._arg}return value};methods[baseName]=function(arg){return this.delegateExtension()};methods[defName]=function(arg){return};methods[normalName]=function(value,arg){return value};methods[interName]=function(value,arg){return value};this.constructor.add(methods);return this},finished:function(value){this._finished=true;return value},applyExtensions:function(){if(!this._extended){this._extended=true;var extensionAbsIds=this.extensionAbsIds;if(extensionAbsIds){extensionAbsIds.forEach(function(extensionAbsId){this.panel.extendAbs(this.pvMark,extensionAbsId)},this)}}return this},intercept:function(name,fun){return this._intercept(name,fun.bind(this))},lockDimensions:function(){this.pvMark.lock('left').lock('right').lock('top').lock('bottom').lock('width').lock('height');return this},_extensionKeyArgs:{tag:pvc.extensionTag},_bindProperty:function(pvName,prop,realProp){var me=this;if(!realProp){realProp=prop}var defaultPropName="default"+def.firstUpperCase(realProp);if(def.fun.is(this[defaultPropName])){if(!this.pvMark.hasDelegateValue(pvName,pvc.extensionTag)){var defaultMethodCaller=function(){return me[defaultPropName](me._arg)};this.pvMark.intercept(pvName,defaultMethodCaller,this._extensionKeyArgs)}}function mainMethodCaller(){return me[prop]()}return this._intercept(pvName,mainMethodCaller)},_intercept:function(name,fun){var mark=this.pvMark;var extensionAbsIds=this.extensionAbsIds;if(extensionAbsIds){def.query(extensionAbsIds).select(function(extensionAbsId){return this.panel._getExtensionAbs(extensionAbsId,name)},this).where(def.notUndef).each(function(extValue){extValue=mark.wrap(extValue,name);mark.intercept(name,extValue,this._extensionKeyArgs)},this)}(mark._intercepted||(mark._intercepted={}))[name]=true;mark.intercept(name,fun);return this}}).prototype.property('color').constructor.add({_bitShowsActivity:2,_bitShowsSelection:4,_bitShowsInteraction:4|2,_bitShowsTooltip:8,_bitSelectable:16,_bitHoverable:32,_bitClickable:64,_bitDoubleClickable:128,showsInteraction:function(){return(this.bits&this._bitShowsInteraction)!==0},showsActivity:function(){return(this.bits&this._bitShowsActivity)!==0},showsSelection:function(){return(this.bits&this._bitShowsSelection)!==0},showsTooltip:function(){return(this.bits&this._bitShowsTooltip)!==0},isSelectable:function(){return(this.bits&this._bitSelectable)!==0},isHoverable:function(){return(this.bits&this._bitHoverable)!==0},isClickable:function(){return(this.bits&this._bitClickable)!==0},isDoubleClickable:function(){return(this.bits&this._bitDoubleClickable)!==0},extensionAbsIds:null,_addInteractive:function(keyArgs){var panel=this.panel,pvMark=this.pvMark,chart=this.chart,options=chart.options;var bits=this.bits;bits|=this._bitShowsInteraction;if(chart._tooltipEnabled&&!def.get(keyArgs,'noTooltip')){bits|=this._bitShowsTooltip;this.panel._addPropTooltip(pvMark,def.get(keyArgs,'tooltipArgs'))}var clickSelectable=false;var clickable=false;if(options.selectable||options.hoverable){if(options.selectable&&!def.get(keyArgs,'noSelect')){bits|=this._bitSelectable;clickSelectable=!def.get(keyArgs,'noClickSelect')&&chart._canSelectWithClick()}if(options.hoverable&&!def.get(keyArgs,'noHover')){bits|=this._bitHoverable;panel._addPropHoverable(pvMark)}}var showsInteraction=def.get(keyArgs,'showsInteraction');if(showsInteraction!=null){if(showsInteraction){bits|=this._bitShowsInteraction}else{bits&=~this._bitShowsInteraction}}var showsActivity=def.get(keyArgs,'showsActivity');if(showsActivity!=null){if(showsActivity){bits|=this._bitShowsActivity}else{bits&=~this._bitShowsActivity}}var showsSelection=def.get(keyArgs,'showsSelection');if(showsSelection!=null){if(showsSelection){bits|=this._bitShowsSelection}else{bits&=~this._bitShowsSelection}}if(!def.get(keyArgs,'noClick')&&panel._isClickable()){bits|=this._bitClickable;clickable=true}if(clickSelectable||clickable){panel._addPropClick(pvMark)}if(!def.get(keyArgs,'noDoubleClick')&&panel._isDoubleClickable()){bits|=this._bitDoubleClickable;panel._addPropDoubleClick(pvMark)}this.bits=bits},fillColor:function(){return this.color('fill')},strokeColor:function(){return this.color('stroke')},defaultColor:function(){return this.defaultColorSceneScale()(this.scene)},dimColor:function(color){return pvc.toGrayScale(color,-0.3,null,null)},_initDefaultColorSceneScale:function(){var colorAxis=this.panel.axes.color;return colorAxis?colorAxis.sceneScale({nullToZero:false}):def.fun.constant(pvc.defaultColor)},defaultColorSceneScale:function(){return this._defaultColorSceneScale||(this._defaultColorSceneScale=this._initDefaultColorSceneScale())}});
def.type('pvc.visual.Panel',pvc.visual.Sign).init(function(panel,protoMark,keyArgs){var pvPanel=def.get(keyArgs,'panel');if(!pvPanel){var pvPanelType=def.get(keyArgs,'panelType')||pv.Panel;pvPanel=protoMark.add(pvPanelType)}this.base(panel,pvPanel,keyArgs)}).add({_addInteractive:function(keyArgs){var t=true;keyArgs=def.setDefaults(keyArgs,'noSelect',t,'noHover',t,'noTooltip',t,'noClick',t,'noDoubleClick',t);this.base(keyArgs)}});
def.type('pvc.visual.Label',pvc.visual.Sign).init(function(panel,protoMark,keyArgs){var pvMark=protoMark.add(pv.Label);this.base(panel,pvMark,keyArgs)}).add({_addInteractive:function(keyArgs){keyArgs=def.setDefaults(keyArgs,'noSelect',true,'noHover',true,'noTooltip',true,'noClick',true,'noDoubleClick',true);this.base(keyArgs)},defaultColor:function(type){return pv.Color.names.black}});
def.type('pvc.visual.Dot',pvc.visual.Sign).init(function(panel,parentMark,keyArgs){var pvMark=parentMark.add(pv.Dot);var protoMark=def.get(keyArgs,'proto');if(protoMark){pvMark.extend(protoMark)}keyArgs=def.setDefaults(keyArgs,'freeColor',false);this.base(panel,pvMark,keyArgs);if(!def.get(keyArgs,'freePosition',false)){var basePosProp=panel.isOrientationVertical()?"left":"bottom",orthoPosProp=panel.anchorOrtho(basePosProp);this._lockDynamic(orthoPosProp,'y')._lockDynamic(basePosProp,'x')}this._bindProperty('shape','shape')._bindProperty('shapeRadius','radius')._bindProperty('shapeSize','size').optional('strokeDasharray',undefined).optional('lineWidth',1.5)}).prototype.property('size').constructor.add({y:function(){return 0},x:function(){return 0},shape:function(){return this.delegateExtension()},radius:function(){this.state.radius=this.delegateExtension()},baseSize:function(){var radius=this.state.radius;if(radius!=null){return radius*radius}return this.base()},defaultSize:function(){return 12},interactiveSize:function(size){if(this.scene.isActive){return Math.max(size,5)*2.5}return size},interactiveColor:function(color,type){var scene=this.scene;if(scene.isActive){if(type==='stroke'){return color.brighter(1)}}else if(this.showsSelection()&&scene.anySelected()&&!scene.isSelected()){if(this.isActiveSeriesAware&&scene.isActiveSeries()){return color.alpha(0.8)}else{switch(type){case'fill':return this.dimColor(color,type);case'stroke':return color.alpha(0.45)}}}return this.base(color,type)}});
def.type('pvc.visual.Line',pvc.visual.Sign).init(function(panel,protoMark,keyArgs){var pvMark=protoMark.add(pv.Line);this.base(panel,pvMark,keyArgs);this.lock('segmented','smart').lock('antialias',true);if(!def.get(keyArgs,'freePosition',false)){var basePosProp=panel.isOrientationVertical()?"left":"bottom",orthoPosProp=panel.anchorOrtho(basePosProp);this._lockDynamic(orthoPosProp,'y')._lockDynamic(basePosProp,'x')}this._bindProperty('strokeStyle','strokeColor','color')._bindProperty('lineWidth','strokeWidth')}).prototype.property('strokeWidth').constructor.add({_addInteractive:function(keyArgs){keyArgs=def.setDefaults(keyArgs,'noTooltip',true);this.base(keyArgs)},y:function(){return 0},x:function(){return 0},defaultStrokeWidth:function(){return 1.5},interactiveStrokeWidth:function(strokeWidth){if(this.isActiveSeriesAware&&this.scene.isActiveSeries()){return Math.max(1,strokeWidth)*2.5}return strokeWidth},interactiveColor:function(color,type){var scene=this.scene;if(this.showsSelection()&&scene.anySelected()&&!scene.isSelected()){if(this.isActiveSeriesAware&&scene.isActiveSeries()){return pv.Color.names.darkgray.darker().darker()}if(type==='stroke'){return this.dimColor(color,type)}}return this.base(color,type)}});
def.type('pvc.visual.Area',pvc.visual.Sign).init(function(panel,protoMark,keyArgs){var pvMark=protoMark.add(pv.Area);if(!keyArgs){keyArgs={}}keyArgs.freeColor=true;this.base(panel,pvMark,keyArgs);var antialias=def.get(keyArgs,'antialias',true);this.lock('segmented','smart').lock('antialias',antialias);if(!def.get(keyArgs,'freePosition',false)){var basePosProp=panel.isOrientationVertical()?"left":"bottom",orthoPosProp=panel.anchorOrtho(basePosProp),orthoLenProp=panel.anchorOrthoLength(orthoPosProp);this._lockDynamic(basePosProp,'x')._lockDynamic(orthoPosProp,'y')._lockDynamic(orthoLenProp,'dy')}this._bindProperty('fillStyle','fillColor','color');this.lock('strokeStyle',null).lock('lineWidth',0)}).add({_addInteractive:function(keyArgs){keyArgs=def.setDefaults(keyArgs,'noTooltip',true);this.base(keyArgs)},x:function(){return 0},y:function(){return 0},dy:function(){return 0},interactiveColor:function(color,type){if(type==='fill'&&this.showsSelection()&&this.scene.anySelected()&&!this.scene.isSelected()){return this.dimColor(color,type)}return this.base(color,type)}});
def.type('pvc.visual.Bar',pvc.visual.Sign).init(function(panel,protoMark,keyArgs){var pvMark=protoMark.add(pv.Bar);keyArgs=def.setDefaults(keyArgs,'freeColor',false);this.base(panel,pvMark,keyArgs);this.normalStroke=def.get(keyArgs,'normalStroke',false);this._bindProperty('lineWidth','strokeWidth')}).prototype.property('strokeWidth').constructor.add({normalColor:function(color,type){if(type==='stroke'&&!this.normalStroke){return null}return color},interactiveColor:function(color,type){var scene=this.scene;if(type==='stroke'){if(scene.isActive){return color.brighter(1.3).alpha(0.7)}if(!this.normalStroke){return null}if(this.showsSelection()&&scene.anySelected()&&!scene.isSelected()){if(this.isActiveSeriesAware&&scene.isActiveSeries()){return pv.Color.names.darkgray.darker().darker()}return this.dimColor(color,type)}if(this.isActiveSeriesAware&&scene.isActiveSeries()){return color.brighter(1).alpha(0.7)}}else if(type==='fill'){if(scene.isActive){return color.brighter(0.2).alpha(0.8)}if(this.showsSelection()&&scene.anySelected()&&!scene.isSelected()){if(this.isActiveSeriesAware&&scene.isActiveSeries()){return pv.Color.names.darkgray.darker(2).alpha(0.8)}return this.dimColor(color,type)}if(this.isActiveSeriesAware&&scene.isActiveSeries()){return color.brighter(0.2).alpha(0.8)}}return this.base(color,type)},defaultStrokeWidth:function(){return 0.5},interactiveStrokeWidth:function(strokeWidth){if(this.scene.isActive){return Math.max(1,strokeWidth)*1.3}return strokeWidth}});
pv.PieSlice=function(){pv.Wedge.call(this)};pv.PieSlice.prototype=pv.extend(pv.Wedge);pv.PieSlice.prototype.midAngle=function(){var instance=this.instance();return instance.startAngle+(instance.angle/2)};def.type('pvc.visual.PieSlice',pvc.visual.Sign).init(function(panel,protoMark,keyArgs){var pvMark=protoMark.add(pv.PieSlice);keyArgs=def.setDefaults(keyArgs,'freeColor',false);this.base(panel,pvMark,keyArgs);this._activeOffsetRadius=def.get(keyArgs,'activeOffsetRadius',0);this._center=def.get(keyArgs,'center');this.optional('lineWidth',0.6)._bindProperty('angle','angle')._lockDynamic('bottom','y')._lockDynamic('left','x').lock('top',null).lock('right',null)}).prototype.property('offsetRadius').constructor.add({angle:function(){return 0},x:function(){return this._center.x+this._offsetSlice('cos')},y:function(){return this._center.y-this._offsetSlice('sin')},_offsetSlice:function(fun){var offset=this._getOffsetRadius();if(offset!==0){offset=offset*Math[fun](this.pvMark.midAngle())}return offset},_getOffsetRadius:function(){var offset=this.state.offsetRadius;if(offset==null){offset=(this.state.offsetRadius=this.offsetRadius()||0)}return offset},defaultColor:function(type){if(type==='stroke'){return null}return this.base(type)},interactiveColor:function(color,type){var scene=this.scene;if(scene.isActive){switch(type){case'fill':return color.brighter(0.2).alpha(0.8);case'stroke':return color.brighter(1.3).alpha(0.7)}}else if(this.showsSelection()&&scene.anySelected()&&!scene.isSelected()){if(type==='fill'){return this.dimColor(color,type)}}return this.base(color,type)},baseOffsetRadius:function(){return 0},interactiveOffsetRadius:function(offsetRadius){if(this.scene.isActive){return offsetRadius+this._activeOffsetRadius}return offsetRadius}});
def.type('pvc.visual.Rule',pvc.visual.Sign).init(function(panel,parentMark,keyArgs){var pvMark=parentMark.add(pv.Rule);var protoMark=def.get(keyArgs,'proto');if(protoMark){pvMark.extend(protoMark)}this.base(panel,pvMark,keyArgs);if(!def.get(keyArgs,'freeStyle')){this._bindProperty('strokeStyle','strokeColor','color')._bindProperty('lineWidth','strokeWidth')}}).prototype.property('strokeWidth').constructor.add({_addInteractive:function(keyArgs){keyArgs=def.setDefaults(keyArgs,'noHover',true,'noSelect',true,'noTooltip',true,'noClick',true,'noDoubleClick',true);this.base(keyArgs)},defaultStrokeWidth:function(){return 1},interactiveStrokeWidth:function(strokeWidth){if(this.scene.isActive){return Math.max(1,strokeWidth)*2.2}return strokeWidth},interactiveColor:function(color,type){var scene=this.scene;if(!scene.isActive&&this.showsSelection()&&scene.anySelected()&&scene.datum&&!scene.isSelected()){return this.dimColor(color,type)}return this.base(color,type)}});
def.type('pvc.visual.Context').init(function(panel,mark,event){this.chart=panel.chart;this.panel=panel;visualContext_update.call(this,mark,event)}).add({isPinned:false,pin:function(){this.isPinned=true;return this},finished:function(v){return this.sign.finished(v)},delegate:function(dv){return this.sign.delegate(dv)},getV1Series:function(){var s;var series=this.scene.firstAtoms&&(s=this.scene.firstAtoms[this.panel._getV1DimName('series')])&&s.rawValue;if(series==null){series='Series'}return series},getV1Category:function(){var c;return this.scene.firstAtoms&&(c=this.scene.firstAtoms[this.panel._getV1DimName('category')])&&c.rawValue},getV1Value:function(){var v;return this.scene.firstAtoms&&(v=this.scene.firstAtoms[this.panel._getV1DimName('value')])&&v.value},getV1Datum:function(){return this.panel._getV1Datum(this.scene)}});if(Object.defineProperty){try{Object.defineProperty(pvc.visual.Context.prototype,'parent',{get:function(){throw def.error.operationInvalid("The 'this.parent.index' idiom has no equivalent in this version. Please try 'this.pvMark.parent.index'.")}})}catch(ex){}}function visualContext_update(mark,event){this.event=event||null;this.pvMark=mark;var scene;if(mark){var sign=this.sign=mark.sign||null;if(sign){scene=mark.instance().data}if(!scene){this.index=null;scene=new pvc.visual.Scene(null,{panel:this.panel})}else{this.index=scene.childIndex()}}else{this.sign=null;this.index=null;scene=new pvc.visual.Scene(null,{panel:this.panel,group:this.chart.root.data})}this.scene=scene}
def.type('pvc.visual.OptionsBase').init(function(chart,type,index,keyArgs){this.chart=chart;this.type=type;this.index=index==null?0:index;this.name=def.get(keyArgs,'name');this.id=this._buildId();this.optionId=this._buildOptionId();var rs=this._resolvers=[];this._registerResolversFull(rs,keyArgs);this.option=pvc.options(this._getOptionsDefinition(),this)}).add({_buildId:function(){return pvc.buildIndexedId(this.type,this.index)},_buildOptionId:function(){return this.id},_getOptionsDefinition:def.method({isAbstract:true}),_chartOption:function(name){return this.chart.options[name]},_registerResolversFull:function(rs,keyArgs){var fixed=def.get(keyArgs,'fixed');if(fixed){this._fixed=fixed;rs.push(pvc.options.specify(function(optionInfo){return fixed[optionInfo.name]}))}this._registerResolversNormal(rs,keyArgs);var defaults=def.get(keyArgs,'defaults');if(defaults){this._defaults=defaults}rs.push(this._resolveDefault)},_registerResolversNormal:function(rs,keyArgs){if(this.chart.compatVersion()<=1){rs.push(this._resolveByV1OnlyLogic)}if(this.name){rs.push(pvc.options.specify(function(optionInfo){return this._chartOption(this.name+def.firstUpperCase(optionInfo.name))}))}rs.push(this._resolveByOptionId);if(def.get(keyArgs,'byNaked',!this.index)){rs.push(this._resolveByNaked)}},_resolveFull:function(optionInfo){var rs=this._resolvers;for(var i=0,L=rs.length;i<L;i++){if(rs[i].call(this,optionInfo)){return true}}return false},_resolveFixed:pvc.options.specify(function(optionInfo){if(this._fixed){return this._fixed[optionInfo.name]}}),_resolveByV1OnlyLogic:function(optionInfo){var data=optionInfo.data;var resolverV1;if(data&&(resolverV1=data.resolveV1)){return resolverV1.call(this,optionInfo)}},_resolveByName:pvc.options.specify(function(optionInfo){if(this.name){return this._chartOption(this.name+def.firstUpperCase(optionInfo.name))}}),_resolveByOptionId:pvc.options.specify(function(optionInfo){return this._chartOption(this.optionId+def.firstUpperCase(optionInfo.name))}),_resolveByNaked:pvc.options.specify(function(optionInfo){if(!this.index){return this._chartOption(def.firstLowerCase(optionInfo.name))}}),_resolveDefault:function(optionInfo){var data=optionInfo.data;var resolverDefault;if(data&&(resolverDefault=data.resolveDefault)){if(resolverDefault.call(this,optionInfo)){return true}}if(this._defaults){var value=this._defaults[optionInfo.name];if(value!==undefined){optionInfo.defaultValue(value);return true}}},_specifyChartOption:function(optionInfo,asName){var value=this._chartOption(asName);if(value!=null){optionInfo.specify(value);return true}}});
var axis_optionsDef;def.scope(function(){def.type('pvc.visual.Axis',pvc.visual.OptionsBase).init(function(chart,type,index,keyArgs){this.base(chart,type,index,keyArgs);chart._addAxis(this)}).add({isVisible:true,scaleTreatsNullAs:function(){return'null'},scaleNullRangeValue:function(){return null},scaleUsesAbs:function(){return false},bind:function(dataCells){dataCells||def.fail.argumentRequired('dataCells');!this.dataCells||def.fail.operationInvalid('Axis is already bound.');this.dataCells=def.array.to(dataCells);this.dataCell=this.dataCells[0];this.role=this.dataCell&&this.dataCell.role;this.scaleType=groupingScaleType(this.role.grouping);this._checkRoleCompatibility();return this},isDiscrete:function(){return this.role&&this.role.isDiscrete()},isBound:function(){return!!this.role},setScale:function(scale,noWrap){this.role||def.fail.operationInvalid('Axis is unbound.');this.scale=scale?(noWrap?scale:this._wrapScale(scale)):null;return this},_wrapScale:function(scale){scale.type=this.scaleType;var by;if(scale.type!=='discrete'){var useAbs=this.scaleUsesAbs();var nullAs=this.scaleTreatsNullAs();if(nullAs&&nullAs!=='null'){var nullValue=nullAs==='min'?scale.domain()[0]:0;if(useAbs){by=function(v){return scale(v==null?nullValue:(v<0?-v:v))}}else{by=function(v){return scale(v==null?nullValue:v)}}}else{var nullRangeValue=this.scaleNullRangeValue();if(useAbs){by=function(v){return v==null?nullRangeValue:scale(v<0?-v:v)}}else{by=function(v){return v==null?nullRangeValue:scale(v)}}}}else{by=function(v){return scale(v==null?'':v)}}return def.copy(by,scale)},sceneScale:function(keyArgs){var varName=def.get(keyArgs,'sceneVarName')||this.role.name,grouping=this.role.grouping;if(grouping.isSingleDimension&&grouping.firstDimensionValueType()===Number){var scale=this.scale,nullToZero=def.get(keyArgs,'nullToZero',true);var by=function(scene){var value=scene.vars[varName].value;if(value==null){if(!nullToZero){return value}value=0}return scale(value)};def.copy(by,scale);return by}return this.scale.by1(function(scene){return scene.vars[varName].value})},_checkRoleCompatibility:function(){var L=this.dataCells.length;if(L>1){var grouping=this.role.grouping,i;if(this.scaleType==='discrete'){for(i=1;i<L;i++){if(grouping.id!==this.dataCells[i].role.grouping.id){throw def.error.operationInvalid("Discrete roles on the same axis must have equal groupings.")}}}else{if(!grouping.firstDimensionType().isComparable){throw def.error.operationInvalid("Continuous roles on the same axis must have 'comparable' groupings.")}for(i=1;i<L;i++){if(this.scaleType!==groupingScaleType(this.dataCells[i].role.grouping)){throw def.error.operationInvalid("Continuous roles on the same axis must have scales of the same type.")}}}}},_getOptionsDefinition:function(){return axis_optionsDef}});function groupingScaleType(grouping){return grouping.isDiscrete()?'discrete':(grouping.firstDimensionValueType()===Date?'timeSeries':'numeric')}axis_optionsDef={}});
def.scope(function(){var $VA=pvc.visual.Axis;def.type('pvc.visual.CartesianAxis',$VA).init(function(chart,type,index,keyArgs){var options=chart.options;this.orientation=$VCA.getOrientation(type,options.orientation);this.orientedId=$VCA.getOrientedId(this.orientation,index);if(chart._allowV1SecondAxis&&index===1){this.v1SecondOrientedId='second'+this.orientation.toUpperCase()}this.base(chart,type,index,keyArgs);var extensions=this.extensionPrefixes=[this.id+'Axis',this.orientedId+'Axis'];if(this.v1SecondOrientedId){extensions.push(this.v1SecondOrientedId+'Axis')}this._extPrefAxisPosition=extensions.length;extensions.push('axis')}).add({bind:function(dataCells){this.base(dataCells);this._syncExtensionPrefixes();return this},_syncExtensionPrefixes:function(){var extensions=this.extensionPrefixes;extensions.length=this._extPrefAxisPosition;var st=this.scaleType;if(st){extensions.push(st+'Axis');if(st!=='discrete'){extensions.push('continuousAxis')}}extensions.push('axis')},setScale:function(scale){var oldScale=this.scale;this.base(scale);if(oldScale){delete this.domain;delete this.ticks;delete this._roundingPaddings}if(scale){if(!scale.isNull&&this.scaleType!=='discrete'){this.domain=scale.domain();this.domain.minLocked=!!scale.minLocked;this.domain.maxLocked=!!scale.maxLocked;if(this.scaleType==='numeric'){var roundMode=this.option('DomainRoundMode');if(roundMode==='nice'){scale.nice()}var tickFormatter=this.option('TickFormatter');if(tickFormatter){scale.tickFormatter(tickFormatter)}}}}return this},setTicks:function(ticks){var scale=this.scale;(scale&&!scale.isNull)||def.fail.operationInvalid("Scale must be set and non-null.");this.ticks=ticks;if(scale.type==='numeric'&&this.option('DomainRoundMode')==='tick'){delete this._roundingPaddings;var tickCount=ticks&&ticks.length;if(tickCount){this.scale.domain(ticks[0],ticks[tickCount-1])}else{this.scale.domain(this.domain[0],this.domain[1])}}},setScaleRange:function(size){var scale=this.scale;scale.min=0;scale.max=size;scale.size=size;if(scale.type==='discrete'){if(scale.domain().length>0){var bandRatio=this.chart.options.panelSizeRatio||0.8;scale.splitBandedCenter(scale.min,scale.max,bandRatio)}}else{scale.range(scale.min,scale.max)}if(pvc.debug>4){this.chart._log("Axis "+this.id+" setRange: "+pvc.stringify(scale.range()))}return scale},getScaleRoundingPaddings:function(){var roundingPaddings=this._roundingPaddings;if(!roundingPaddings){roundingPaddings={begin:0,end:0,beginLocked:false,endLocked:false};var scale=this.scale;if(scale&&!scale.isNull&&scale.type!=='discrete'){var originalDomain=this.domain;roundingPaddings.beginLocked=originalDomain.minLocked;roundingPaddings.endLocked=originalDomain.maxLocked;if(scale.type==='numeric'&&this.option('DomainRoundMode')!=='none'){var currDomain=scale.domain();var origDomain=this.domain||def.assert("Original domain must be set");var currLength=currDomain[1]-currDomain[0];if(currLength){var diff=origDomain[0]-currDomain[0];if(diff>0){roundingPaddings.begin=diff/currLength}diff=currDomain[1]-origDomain[1];if(diff>0){roundingPaddings.end=diff/currLength}}}}this._roundingPaddings=roundingPaddings}return roundingPaddings},_getOptionsDefinition:function(){return cartAxis_optionsDef},_buildOptionId:function(){return this.id+"Axis"},_registerResolversNormal:function(rs,keyArgs){if(this.chart.compatVersion()<=1){rs.push(this._resolveByV1OnlyLogic)}rs.push(this._resolveByOptionId,this._resolveByOrientedId);if(this.index===1){rs.push(this._resolveByV1OptionId)}rs.push(this._resolveByScaleType,this._resolveByCommonId)},_resolveByOrientedId:pvc.options.specify(function(optionInfo){return this._chartOption(this.orientedId+"Axis"+optionInfo.name)}),_resolveByV1OptionId:pvc.options.specify(function(optionInfo){return this._chartOption('secondAxis'+optionInfo.name)}),_resolveByScaleType:pvc.options.specify(function(optionInfo){var st=this.scaleType;if(st){var name=optionInfo.name;var value=this._chartOption(st+'Axis'+name);if(value===undefined&&st!=='discrete'){value=this._chartOption('continuousAxis'+name)}return value}}),_resolveByCommonId:pvc.options.specify(function(optionInfo){return this._chartOption('axis'+optionInfo.name)})});var $VCA=pvc.visual.CartesianAxis;$VCA.getOrientation=function(type,chartOrientation){return((type==='base')===(chartOrientation==='vertical'))?'x':'y'};$VCA.getOrientedId=function(orientation,index){if(index===0){return orientation}return orientation+(index+1)};var fixedMinMaxSpec={resolve:'_resolveFull',data:{resolveV1:function(optionInfo){if(!this.index&&this.type==='ortho'){this._specifyChartOption(optionInfo,this.id+optionInfo.name)}return true}},cast:pvc.castNumber};function castDomainScope(scope,axis){return pvc.parseDomainScope(scope,axis.orientation)}function castAxisPosition(side){if(side){if(def.hasOwn(pvc.Sides.namesSet,side)){var mapAlign=pvc.BasePanel[this.orientation==='y'?'horizontalAlign':'verticalAlign2'];return mapAlign[side]}if(pvc.debug>=2){pvc.log(def.format("Invalid axis position value '{0}'.",[side]))}}return this.orientation==='x'?'bottom':'left'}var normalV1Data={resolveV1:function(optionInfo){if(!this.index){if(this._resolveByOrientedId(optionInfo)){return true}}else if(this._resolveByV1OptionId(optionInfo)){return true}this._resolveDefault(optionInfo);return true}};var defaultPosition=pvc.options.defaultValue(function(optionInfo){if(!this.typeIndex){return this.orientation==='x'?'bottom':'left'}var firstAxis=this.chart.axesByType[this.type].first;var position=firstAxis.option('Position');return pvc.BasePanel.oppositeAnchor[position]});function castSize(value){var position=this.option('Position');return pvc.Size.toOrtho(value,position)}function castTitleSize(value){var position=this.option('Position');return pvc.Size.to(value,{singleProp:pvc.BasePanel.orthogonalLength[position]})}var cartAxis_optionsDef=def.create(axis_optionsDef,{Visible:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){if(this.index<=1){var v1OptionId=this.index===0?def.firstUpperCase(this.orientation):'Second';this._specifyChartOption(optionInfo,'show'+v1OptionId+'Scale')}return true}},cast:Boolean,value:true},Composite:{resolve:function(optionInfo){if(this.index>0){optionInfo.specify(false);return true}return this._resolveFull(optionInfo)},data:{resolveV1:function(optionInfo){this._specifyChartOption(optionInfo,'useCompositeAxis');return true}},cast:Boolean,value:false},Size:{resolve:'_resolveFull',data:normalV1Data,cast:castSize},SizeMax:{resolve:'_resolveFull',cast:castSize},Position:{resolve:'_resolveFull',data:{resolveV1:normalV1Data.resolveV1,resolveDefault:defaultPosition},cast:castAxisPosition},FixedMin:fixedMinMaxSpec,FixedMax:fixedMinMaxSpec,OriginIsZero:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){switch(this.index){case 0:this._specifyChartOption(optionInfo,'originIsZero');break;case 1:if(this.chart._allowV1SecondAxis){this._specifyChartOption(optionInfo,'secondAxisOriginIsZero')}break}return true}},cast:Boolean,value:true},DomainScope:{resolve:'_resolveFull',cast:castDomainScope,value:'global'},Offset:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){switch(this.index){case 0:this._specifyChartOption(optionInfo,'axisOffset');break;case 1:if(this.chart._allowV1SecondAxis){this._specifyChartOption(optionInfo,'secondAxisOffset');break}break}return true}},cast:pvc.castNumber},LabelSpacingMin:{resolve:'_resolveFull',cast:pvc.castNumber},OverlappedLabelsMode:{resolve:'_resolveFull',cast:pvc.parseOverlappedLabelsMode,value:'hide'},Grid:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){if(!this.index){this._specifyChartOption(optionInfo,this.orientation+'AxisFullGrid')}return true}},cast:Boolean,value:false},GridCrossesMargin:{resolve:'_resolveFull',cast:Boolean,value:true},EndLine:{resolve:'_resolveFull',cast:Boolean},ZeroLine:{resolve:'_resolveFull',cast:Boolean,value:true},RuleCrossesMargin:{resolve:'_resolveFull',cast:Boolean,value:true},Ticks:{resolve:'_resolveFull',cast:Boolean},DesiredTickCount:{resolve:'_resolveFull',data:{resolveV1:normalV1Data.resolveV1,resolveDefault:function(optionInfo){if(this.chart.compatVersion()<=1){optionInfo.defaultValue(5);return true}}},cast:pvc.castNumber},MinorTicks:{resolve:'_resolveFull',data:normalV1Data,cast:Boolean,value:true},TickFormatter:{resolve:'_resolveFull',cast:def.fun.as},DomainRoundMode:{resolve:'_resolveFull',data:{resolveV1:normalV1Data.resolveV1,resolveDefault:function(optionInfo){if(this.chart.compatVersion()<=1){optionInfo.defaultValue('none');return true}}},cast:pvc.parseDomainRoundingMode,value:'tick'},TickExponentMin:{resolve:'_resolveFull',cast:pvc.castNumber},TickExponentMax:{resolve:'_resolveFull',cast:pvc.castNumber},Title:{resolve:'_resolveFull',cast:String},TitleSize:{resolve:'_resolveFull',cast:castTitleSize},TitleSizeMax:{resolve:'_resolveFull',cast:castTitleSize},TitleFont:{resolve:'_resolveFull',cast:String},TitleMargins:{resolve:'_resolveFull',cast:pvc.Sides.as},TitlePaddings:{resolve:'_resolveFull',cast:pvc.Sides.as},TitleAlign:{resolve:'_resolveFull',cast:function castAlign(align){var position=this.option('Position');return pvc.parseAlign(position,align)}},Font:{resolve:'_resolveFull',cast:String},ClickAction:{resolve:'_resolveFull',data:normalV1Data},DoubleClickAction:{resolve:'_resolveFull',data:normalV1Data}})});
def.type('pvc.visual.CartesianAxisRootScene',pvc.visual.Scene);
def.type('pvc.visual.CartesianAxisTickScene',pvc.visual.Scene).init(function(parent,keyArgs){this.base(parent,keyArgs);this.vars.tick=new pvc.visual.ValueLabelVar(def.get(keyArgs,'tick'),def.get(keyArgs,'tickLabel'),def.get(keyArgs,'tickRaw'))});
def.scope(function(){def.type('pvc.visual.CartesianFocusWindow',pvc.visual.OptionsBase).init(function(chart){this.base(chart,'focusWindow',0,{byNaked:false});var baseAxis=chart.axes.base;this.base=new pvc.visual.CartesianFocusWindowAxis(this,baseAxis)}).add({_getOptionsDefinition:function(){return focusWindow_optionsDef},_exportData:function(){return{base:def.copyProps(this.base,pvc.visual.CartesianFocusWindow.props)}},_importData:function(data){var baseData=data.base;this.base.option.specify({Begin:baseData.begin,End:baseData.end,Length:baseData.length})},_initFromOptions:function(){this.base._initFromOptions()},_onAxisChanged:function(axis){var changed=this.option('Changed');if(changed){changed.call(this.chart.basePanel._getContext())}}});var focusWindow_optionsDef=def.create(axis_optionsDef,{Changed:{resolve:'_resolveFull',cast:def.fun.as}});def.type('pvc.visual.CartesianFocusWindowAxis',pvc.visual.OptionsBase).init(function(fw,axis){this.window=fw;this.axis=axis;this.isDiscrete=axis.isDiscrete();this.base(axis.chart,'focusWindow'+def.firstUpperCase(axis.type),0,{byNaked:false})}).addStatic({props:['begin','end','length']}).add({_getOptionsDefinition:function(){return focusWindowAxis_optionsDef},_initFromOptions:function(){var o=this.option;this.set({begin:o('Begin'),end:o('End'),length:o('Length')})},set:function(keyArgs){var me=this;var render=def.get(keyArgs,'render');var select=def.get(keyArgs,'select',true);var b,e,l;keyArgs=me._readArgs(keyArgs);if(!keyArgs){if(this.begin!=null&&this.end!=null&&this.length!=null){return}}else{b=keyArgs.begin;e=keyArgs.end;l=keyArgs.length}var axis=me.axis;var scale=axis.scale;var isDiscrete=me.isDiscrete;var contCast=!isDiscrete?axis.role.firstDimensionType().cast:null;var domain=scale.domain();var a,L;if(isDiscrete){L=domain.length;var ib,ie,ia;if(b!=null){var nb=+b;if(!isNaN(nb)){if(nb===Infinity){ib=L-1;b=domain[ib]}else if(nb===-Infinity){ib=0;b=domain[ib]}}if(ib==null){ib=domain.indexOf(''+b);if(ib<0){ib=0;b=domain[ib]}}}if(e!=null){var ne=+e;if(!isNaN(ne)){if(ne===Infinity){ie=L-1;e=domain[ie]}else if(ne===-Infinity){ie=0;e=domain[ie]}}if(ie==null){ie=domain.indexOf(''+e);if(ie<0){ie=L-1;e=domain[ie]}}}if(l!=null){l=+l;if(isNaN(l)){l=null}else if(l<0&&(b!=null||e!=null)){a=b;ia=ib;b=e,ib=ie,e=a,ie=ia;l=-l}}if(b!=null){if(e!=null){if(ib>ie){a=b;ia=ib;b=e,ib=ie,e=a,ie=ia}l=ie-ib+1}else{if(l==null){l=L-ib}ie=ib+l-1;if(ie>L-1){ie=L-1;l=ie-ib+1}e=domain[ie]}}else{if(e!=null){if(l==null){l=ie}ib=ie-l+1;if(ib<0){ib=0;l=ie-ib+1}b=domain[ib]}else{if(l==null){l=Math.max(~~(L/3),1); }if(l>L){l=L;ib=0;ie=L-1}else{ia=~~(L/2); ib=ia-~~(l/2);ie=ib+l-1}b=domain[ib];e=domain[ie]}}}else{if(l!=null){l=+l;if(isNaN(l)){l=null}else if(l<0&&(b!=null||e!=null)){a=b;b=e,e=a;l=-l}}var min=domain[0];var max=domain[1];L=max-min;if(b!=null){if(b<min){b=min}if(b>max){b=max}}if(e!=null){if(e<min){e=min}if(e>max){e=max}}if(b!=null){if(e!=null){if(b>e){a=b;b=e,e=a}l=e-b}else{if(l==null){l=max-b}e=b+l;if(e>max){e=max;l=e-b}}}else{if(e!=null){if(l==null){l=e-min}b=e-l;if(b<min){b=min;l=e-b}}else{if(l==null){l=Math.max(~~(L/3),1); }if(l>L){l=L;b=min;e=max}else{a=~~(L/2); b=a-~~(l/2);e=(+b)+(+l)}}}b=contCast(b);e=contCast(e);l=contCast(l);var constraint=me.option('Constraint');if(constraint){var oper2={type:'new',target:'begin',value:b,length:l,length0:l,min:min,max:max,minView:min,maxView:max};constraint(oper2);b=contCast(oper2.value);l=contCast(oper2.length);e=contCast((+b)+(+l))}}me._set(b,e,l,select,render)},_updatePosition:function(pbeg,pend,select,render){var me=this;var axis=me.axis;var scale=axis.scale;var b,e,l;if(me.isDiscrete){var ib=scale.invertIndex(pbeg);var ie=scale.invertIndex(pend)-1;var domain=scale.domain();b=domain[ib];e=domain[ie];l=ie-ib+1}else{b=scale.invert(pbeg);e=scale.invert(pend);l=e-b}this._set(b,e,l,select,render)},_constraintPosition:function(oper){var me=this;var axis=me.axis;var scale=axis.scale;var constraint;if(me.isDiscrete){var index=Math.floor(scale.invertIndex(oper.point,true));if(index>=0){var r=scale.range();var L=scale.domain().length;var S=(r.max-r.min)/L;if(index>=L&&(oper.type==='new'||oper.type==='resize-begin')){index=L-1}oper.point=index*S}}else if((constraint=me.option('Constraint'))){var contCast=axis.role.firstDimensionType().cast;var v=contCast(scale.invert(oper.point));var sign=oper.target==='begin'?1:-1;var pother=oper.point+sign*oper.length;var vother=contCast(scale.invert(pother));var vlength=contCast(sign*(vother-v));var vlength0,pother0,vother0;if(oper.length===oper.length0){vlength0=vlength}else{pother0=oper.point+sign*oper.length0;vother0=contCast(scale.invert(pother0));vlength0=sign*(vother0-v)}var vmin=contCast(scale.invert(oper.min));var vmax=contCast(scale.invert(oper.max));var oper2={type:oper.type,target:oper.target,value:v,length:vlength,length0:vlength0,min:vmin,max:vmax,minView:contCast(scale.invert(oper.minView)),maxView:contCast(scale.invert(oper.maxView))};constraint(oper2);if(+oper2.value!==+v){v=oper2.value;oper.point=scale(v)}var vlength2=oper2.length;if(+vlength2!==+vlength){if(+vlength2===+vlength0){oper.length=oper.length0}else{var vother2=(+v)+sign*(+vlength2);var pother2=scale(vother2);oper.length=pother2-sign*oper.point}}if(+oper2.min!==+vmin){oper.min=scale(oper2.min)}if(+oper2.max!==+vmax){oper.max=scale(oper2.max)}}},_compare:function(a,b){return this.isDiscrete?((''+a)===(''+b)):((+a)===(+b))},_set:function(b,e,l,select,render){var me=this;var changed=false;if(!me._compare(b,me.begin)){me.begin=b;changed=true}if(!me._compare(e,me.end)){me.end=e;changed=true}if(!me._compare(l,me.length)){me.length=l;changed=true}if(changed){me.window._onAxisChanged(this)}if(select){me._updateSelection({render:render})}return changed},_readArgs:function(keyArgs){if(keyArgs){var out={};var any=0;var read=function(p){var v=keyArgs[p];if(v!=null){any=true}else{v=this[p]}out[p]=v};pvc.visual.CartesianFocusWindowAxis.props.forEach(read,this);if(any){return out}}},_updateSelection:function(keyArgs){var me=this;var selectDatums;var axis=me.axis;var isDiscrete=axis.isDiscrete();var chart=axis.chart;var dataCell=axis.dataCell;var role=dataCell.role;var partData=chart.partData(dataCell.dataPartValue,{visible:true});var domainData;if(isDiscrete){domainData=partData.flattenBy(role);var dataBegin=domainData._childrenByKey[me.begin];var dataEnd=domainData._childrenByKey[me.end];if(dataBegin&&dataEnd){var indexBegin=dataBegin.childIndex();var indexEnd=dataEnd.childIndex();selectDatums=def.range(indexBegin,indexEnd-indexBegin+1).select(function(index){return domainData._children[index]}).selectMany(function(data){return data._datums}).distinct(function(datum){return datum.key})}}else{domainData=partData;var dimName=role.firstDimensionName();selectDatums=def.query(partData._datums).where(function(datum){var v=datum.atoms[dimName].value;return v!=null&&v>=me.begin&&v<=me.end})}if(selectDatums){chart.data.replaceSelected(selectDatums);chart.root.updateSelections(keyArgs)}}});var focusWindowAxis_optionsDef=def.create(axis_optionsDef,{Resizable:{resolve:'_resolveFull',cast:Boolean,value:true},Movable:{resolve:'_resolveFull',cast:Boolean,value:true},Begin:{resolve:'_resolveFull'},End:{resolve:'_resolveFull'},Length:{resolve:'_resolveFull'},Constraint:{resolve:'_resolveFull',cast:def.fun.as}})});
def.scope(function(){def.type('pvc.visual.ColorAxis',pvc.visual.Axis).add({scaleNullRangeValue:function(){return this.option('Missing')||null},scaleUsesAbs:function(){return this.option('UseAbs')},bind:function(dataCells){this.base(dataCells);this._plotList=def.query(dataCells).select(function(dataCell){return dataCell.plot}).distinct(function(plot){return plot&&plot.id}).array();return this},calculateScale:function(){var scale,noWrap;var dataCells=this.dataCells;if(dataCells){var chart=this.chart;if(this.scaleType==='discrete'){var domainValues=def.query(dataCells).selectMany(function(dataCell){var role=dataCell.role;if(role&&role.isBound()){var partData=chart.partData(dataCell.dataPartValue);var domainData=partData&&partData.flattenBy(role);dataCell.data=domainData;return domainData&&domainData.children()}}).distinct(function(child){return child.key}).select(function(child){return def.nullyTo(child.value,'')}).array();this.domainValues=domainValues;scale=this.scheme()(domainValues);noWrap=true}else{if(dataCells.length===1){var visibleDomainData=chart.root.visibleData(this.dataCell.dataPartValue);var normByCateg=this.option('NormByCategory');var scaleOptions={type:this.option('ScaleType'),colors:this.option('Colors')().range(),colorDomain:this.option('Domain'),colorMin:this.option('Min'),colorMax:this.option('Max'),colorNull:this.option('Missing'),data:visibleDomainData,colorDimension:this.role.firstDimensionName(),normPerBaseCategory:normByCateg};if(normByCateg){this.scalesByCateg=pvc.color.scales(scaleOptions)}else{scale=pvc.color.scale(scaleOptions)}}}}this.setScale(scale,noWrap);return this},_wrapScale:function(scale){var applyTransf;if(this.scaleType==='discrete'){applyTransf=this.option.isSpecified('Transform')||(!this.option.isSpecified('Colors')&&!this.option.isSpecified('Map'))}else{applyTransf=true}if(applyTransf){var colorTransf=this.option('Transform');if(colorTransf){scale=scale.transform(colorTransf)}}return this.base(scale)},scheme:function(){return def.lazy(this,'_scheme',this._createScheme,this)},_createColorMapFilter:function(colorMap){var fixedColors=def.uniqueIndex(colorMap,function(c){return c.key});return{domain:function(k){return!def.hasOwn(colorMap,k)},color:function(c){return!def.hasOwn(fixedColors,c.key)}}},_createScheme:function(){var me=this;var baseScheme=me.option('Colors');if(me.scaleType!=='discrete'){return function(d){var scale=baseScheme.apply(null,arguments);return me._wrapScale(scale)}}var colorMap=me.option('Map');if(!colorMap){return function(d){var scale=baseScheme.apply(null,arguments);return me._wrapScale(scale)}}var filter=this._createColorMapFilter(colorMap);return function(d){var scale;if(!(d instanceof Array)){d=def.array.copy(arguments)}d=d.filter(filter.domain);var baseScale=baseScheme(d);var r=baseScale.range().filter(filter.color);baseScale.range(r);scale=function(k){var c=def.getOwn(colorMap,k);return c||baseScale(k)};def.copy(scale,baseScale);var dx,rx;scale.domain=function(){if(arguments.length){throw def.operationInvalid("The scale cannot be modified.")}if(!dx){dx=def.array.append(def.ownKeys(colorMap),d)}return dx};scale.range=function(){if(arguments.length){throw def.operationInvalid("The scale cannot be modified.")}if(!rx){rx=def.array.append(def.own(colorMap),d)}return rx};return me._wrapScale(scale)}},sceneScale:function(keyArgs){var varName=def.get(keyArgs,'sceneVarName')||this.role.name;return this.scale.by1(function(scene){return scene.vars[varName].value})},_buildOptionId:function(){return this.id+"Axis"},_getOptionsDefinition:function(){return colorAxis_optionsDef},_resolveByNaked:pvc.options.specify(function(optionInfo){if(!this.index){return this._chartOption(this.id+def.firstUpperCase(optionInfo.name))}}),_specifyV1ChartOption:function(optionInfo,asName){if(!this.index&&this.chart.compatVersion()<=1&&this._specifyChartOption(optionInfo,asName)){return true}}});function castSize(size){if(!def.object.is(size)){var position=this.option('Position');size=new pvc.Size().setSize(size,{singleProp:pvc.BasePanel.orthogonalLength[position]})}return size}function castAlign(align){var position=this.option('Position');return pvc.parseAlign(position,align)}function castColorMap(colorMap){var resultMap;if(colorMap){var any;def.eachOwn(colorMap,function(v,k){any=true;colorMap[k]=pv.color(v)});if(any){resultMap=colorMap}}return resultMap}var legendData={resolveDefault:function(optionInfo){if(!this.index&&this._specifyChartOption(optionInfo,def.firstLowerCase(optionInfo.name))){return true}}};function getDefaultColor(optionInfo){var colors;if(this.scaleType==='discrete'){if(this.index===0){colors=pvc.createColorScheme()}else{var me=this;colors=function(){return me.chart._getRoleColorScale(me.role.name)}}}else{colors=['red','yellow','green'].map(function(name){return pv.Color.names[name]})}return colors}var colorAxis_optionsDef=def.create(axis_optionsDef,{Colors:{resolve:'_resolveFull',getDefault:getDefaultColor,data:{resolveV1:function(optionInfo){if(this.scaleType==='discrete'){if(this.index===0){this._specifyChartOption(optionInfo,'colors')}else if(this.index===1&&this.chart._allowV1SecondAxis){this._specifyChartOption(optionInfo,'secondAxisColor')}}else{this._specifyChartOption(optionInfo,'colorRange')}return true},resolveDefault:function(optionInfo){if(this.index===0){this._specifyChartOption(optionInfo,'colors')}}},cast:pvc.colorScheme},Map:{resolve:'_resolveFull',cast:castColorMap},Transform:{resolve:'_resolveFull',data:{resolveDefault:function(optionInfo){var plotList=this._plotList;if(plotList.length<=2){var onlyTrendAndPlot2=def.query(plotList).all(function(plot){var name=plot.name;return(name==='plot2'||name==='trend')});if(onlyTrendAndPlot2){optionInfo.defaultValue(pvc.brighterColorTransform);return true}}}},cast:def.fun.to},NormByCategory:{resolve:function(optionInfo){if(!this.chart._allowColorPerCategory){optionInfo.specify(false);return true}return this._resolveFull(optionInfo)},data:{resolveV1:function(optionInfo){this._specifyV1ChartOption(optionInfo,'normPerBaseCategory');return true}},cast:Boolean,value:false},ScaleType:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyV1ChartOption(optionInfo,'scalingType');return true}},cast:pvc.parseContinuousColorScaleType,value:'linear'},UseAbs:{resolve:'_resolveFull',cast:Boolean,value:false},Domain:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyV1ChartOption(optionInfo,'colorRangeInterval');return true}},cast:def.array.to},Min:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyV1ChartOption(optionInfo,'minColor');return true}},cast:pv.color},Max:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyV1ChartOption(optionInfo,'maxColor');return true}},cast:pv.color},Missing:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyV1ChartOption(optionInfo,'nullColor');return true}},cast:pv.color,value:pv.color("#efc5ad")},LegendVisible:{resolve:'_resolveFull',data:legendData,cast:Boolean,value:true},LegendClickMode:{resolve:'_resolveFull',data:legendData,cast:pvc.parseLegendClickMode,value:'toggleVisible'},LegendDrawLine:{resolve:'_resolveFull',data:legendData,cast:Boolean,value:false},LegendDrawMarker:{resolve:'_resolveFull',data:legendData,cast:Boolean,value:true},LegendShape:{resolve:'_resolveFull',data:legendData,cast:pvc.parseShape}})});
var sizeAxis_optionsDef;def.scope(function(){def.type('pvc.visual.SizeAxis',pvc.visual.Axis).init(function(chart,type,index,keyArgs){keyArgs=def.set(keyArgs,'byNaked',false);this.base(chart,type,index,keyArgs)}).add({scaleTreatsNullAs:function(){return'min'},scaleUsesAbs:function(){return this.option('UseAbs')},setScaleRange:function(range){var scale=this.scale;scale.min=range.min;scale.max=range.max;scale.size=range.max-range.min;scale.range(scale.min,scale.max);if(pvc.debug>=4){pvc.log("Scale: "+pvc.stringify(def.copyOwn(scale)))}return this},_getOptionsDefinition:function(){return sizeAxis_optionsDef}});sizeAxis_optionsDef=def.create(axis_optionsDef,{OriginIsZero:{resolve:'_resolveFull',cast:Boolean,value:false},FixedMin:{resolve:'_resolveFull',cast:pvc.castNumber},FixedMax:{resolve:'_resolveFull',cast:pvc.castNumber},UseAbs:{resolve:'_resolveFull',cast:Boolean,value:false}})});
def.scope(function(){def.type('pvc.visual.Legend',pvc.visual.OptionsBase).init(function(chart,type,index,keyArgs){keyArgs=def.set(keyArgs,'byNaked',false);this.base(chart,type,index,keyArgs)}).add({_getOptionsDefinition:function(){return legend_optionsDef}});function castSize(size){if(!def.object.is(size)){var position=this.option('Position');size=new pvc.Size().setSize(size,{singleProp:pvc.BasePanel.orthogonalLength[position]})}return size}function castAlign(align){var position=this.option('Position');return pvc.parseAlign(position,align)}var legend_optionsDef={Position:{resolve:'_resolveFull',cast:pvc.parsePosition,value:'bottom'},Size:{resolve:'_resolveFull',cast:castSize},SizeMax:{resolve:'_resolveFull',cast:castSize},Align:{resolve:'_resolveFull',data:{resolveDefault:function(optionInfo){var position=this.option('Position');var align;if(position!=='top'&&position!=='bottom'){align='top'}else if(this.chart.compatVersion()<=1){align='left'}optionInfo.defaultValue(align);return true}},cast:castAlign},Margins:{resolve:'_resolveFull',data:{resolveDefault:function(optionInfo){if(this.chart.compatVersion()>1){var position=this.option('Position');var margins=def.set({},pvc.BasePanel.oppositeAnchor[position],5);optionInfo.defaultValue(margins)}return true}},cast:pvc.Sides.as},Paddings:{resolve:'_resolveFull',cast:pvc.Sides.as,value:5},Font:{resolve:'_resolveFull',cast:String,value:'10px sans-serif'}}});
def.type('pvc.visual.legend.BulletRootScene',pvc.visual.Scene).init(function(parent,keyArgs){this.base(parent,keyArgs);var markerDiam=def.get(keyArgs,'markerSize',15);var itemPadding=new pvc.Sides(def.get(keyArgs,'itemPadding',5)).resolve(markerDiam,markerDiam);def.set(this.vars,'horizontal',def.get(keyArgs,'horizontal',false),'font',def.get(keyArgs,'font'),'markerSize',markerDiam,'textMargin',def.get(keyArgs,'textMargin',6),'itemPadding',itemPadding)}).add({layout:function(layoutInfo){var clientSize=layoutInfo.clientSize;if(!(clientSize.width>0&&clientSize.height>0)){return new pvc.Size(0,0)}var desiredClientSize=layoutInfo.desiredClientSize;var markerDiam=this.vars.markerSize;var textLeft=markerDiam+this.vars.textMargin;var itemPadding=this.vars.itemPadding;var a_width=this.vars.horizontal?'width':'height';var a_height=pvc.BasePanel.oppositeLength[a_width];var maxRowWidth=desiredClientSize[a_width];if(!maxRowWidth||maxRowWidth<0){maxRowWidth=clientSize[a_width]}var row;var rows=[];var contentSize={width:0,height:0};this.childNodes.forEach(function(groupScene){groupScene.childNodes.forEach(layoutItem,this)},this);if(!row){return new pvc.Size(0,0)}commitRow(true);def.set(this.vars,'rows',rows,'rowCount',row,'size',contentSize);var isV1Compat=this.compatVersion()<=1;var w=isV1Compat?maxRowWidth:contentSize.width;var h=desiredClientSize[a_height];if(!h||h<0){h=contentSize.height}return def.set({},a_width,Math.min(w,clientSize[a_width]),a_height,Math.min(h,clientSize[a_height]));function layoutItem(itemScene){var textSize=itemScene.labelTextSize();var hidden=!textSize||!textSize.width||!textSize.height;itemScene.isHidden=hidden;if(hidden){return}var widthMargin=0;var itemClientSize={width:textLeft+textSize.width+widthMargin,height:Math.max(textSize.height,markerDiam)};var isFirstInRow;if(!row){row=new pvc.visual.legend.BulletItemSceneRow(0);isFirstInRow=true}else{isFirstInRow=!row.items.length}var newRowWidth=row.size.width+itemClientSize[a_width];if(!isFirstInRow){newRowWidth+=itemPadding[a_width]}if(!isFirstInRow&&(newRowWidth>maxRowWidth)){commitRow(false);newRowWidth=itemClientSize[a_width]}var rowSize=row.size;rowSize.width=newRowWidth;rowSize.height=Math.max(rowSize.height,itemClientSize[a_height]);var rowItemIndex=row.items.length;row.items.push(itemScene);def.set(itemScene.vars,'row',row,'rowIndex',rowItemIndex,'clientSize',itemClientSize)}function commitRow(isLast){var rowSize=row.size;contentSize.height+=rowSize.height;if(rows.length){contentSize.height+=itemPadding[a_height]}contentSize.width=Math.max(contentSize.width,rowSize.width);rows.push(row);if(!isLast){row=new pvc.visual.legend.BulletItemSceneRow(rows.length)}}},defaultGroupSceneType:function(){var GroupType=this._bulletGroupType;if(!GroupType){GroupType=def.type(pvc.visual.legend.BulletGroupScene);this._bulletGroupType=GroupType}return GroupType},createGroup:function(keyArgs){var GroupType=this.defaultGroupSceneType();return new GroupType(this,keyArgs)}});def.type('pvc.visual.legend.BulletItemSceneRow').init(function(index){this.index=index;this.items=[];this.size={width:0,height:0}});
def.type('pvc.visual.legend.BulletGroupScene',pvc.visual.Scene).init(function(rootScene,keyArgs){this.base(rootScene,keyArgs);this.extensionPrefix=def.get(keyArgs,'extensionPrefix')||'';this._renderer=def.get(keyArgs,'renderer');this.colorAxis=def.get(keyArgs,'colorAxis');this.clickMode=def.get(keyArgs,'clickMode');if(this.colorAxis&&!this.clickMode){this.clickMode=this.colorAxis.option('LegendClickMode')}}).add({hasRenderer:function(){return this._renderer},renderer:function(renderer){if(renderer!=null){this._renderer=renderer}else{renderer=this._renderer;if(!renderer){var keyArgs;var colorAxis=this.colorAxis;if(colorAxis){keyArgs={drawRule:colorAxis.option('LegendDrawLine'),drawMarker:colorAxis.option('LegendDrawMarker'),markerShape:colorAxis.option('LegendShape')}}renderer=new pvc.visual.legend.BulletItemDefaultRenderer(keyArgs);this._renderer=renderer}}return renderer},itemSceneType:function(){var ItemType=this._itemSceneType;if(!ItemType){ItemType=def.type(pvc.visual.legend.BulletItemScene);var clickMode=this.clickMode;switch(clickMode){case'toggleSelected':ItemType.add(pvc.visual.legend.BulletItemSceneSelection);break;case'toggleVisible':ItemType.add(pvc.visual.legend.BulletItemSceneVisibility);break}this.panel()._extendSceneType('item',ItemType,['isOn','isClickable','click']);this._itemSceneType=ItemType}return ItemType},createItem:function(keyArgs){var ItemType=this.itemSceneType();return new ItemType(this,keyArgs)}});
def.type('pvc.visual.legend.BulletItemScene',pvc.visual.Scene).init(function(bulletGroup,keyArgs){this.base(bulletGroup,keyArgs);var value,rawValue,label;if(keyArgs){value=keyArgs.value;rawValue=keyArgs.rawValue;label=keyArgs.label}if(value===undefined){var source=this.group||this.datum;if(source){value=source.value;rawValue=source.rawValue;label=source.ensureLabel();var dataPartDim=this.chart()._getDataPartDimName();if(dataPartDim){var dataPartAtom=source.atoms[dataPartDim];if(isNaN(+dataPartAtom.value)){label+=" ("+dataPartAtom.label+")"}}}}this.vars.value=new pvc.visual.ValueLabelVar(value||null,label||"",rawValue)}).add({isOn:function(){return true},isClickable:function(){return false},click:function(){},labelTextSize:function(){var valueVar=this.vars.value;return valueVar&&pv.Text.measure(valueVar.label,this.vars.font)}});
def.type('pvc.visual.legend.BulletItemSceneSelection').add({isOn:function(){var owner=(this.group||this.datum).owner;return!owner.selectedCount()||this.datums().any(function(datum){return!datum.isNull&&datum.isSelected})},isClickable:function(){return this.chart()._canSelectWithClick()},click:function(){var datums=this.datums().array();if(datums.length){var chart=this.chart();chart._updatingSelections(function(){datums=chart._onUserSelection(datums);if(datums){var on=def.query(datums).any(function(datum){return datum.isSelected});pvc.data.Data.setSelected(datums,!on)}})}}});
def.type('pvc.visual.legend.BulletItemSceneVisibility').add({isOn:function(){return this.datums().any(function(datum){return!datum.isNull&&datum.isVisible})},isClickable:function(){return true},click:function(){if(pvc.data.Data.toggleVisible(this.datums())){this.chart().render(true,true,false)}}});
def.type('pvc.visual.legend.BulletItemRenderer');
def.type('pvc.visual.legend.BulletItemDefaultRenderer',pvc.visual.legend.BulletItemRenderer).init(function(keyArgs){this.noSelect=def.get(keyArgs,'noSelect',false);this.noHover=def.get(keyArgs,'noHover',false);this.drawRule=def.get(keyArgs,'drawRule',false);if(this.drawRule){this.rulePvProto=def.get(keyArgs,'rulePvProto')}this.drawMarker=!this.drawRule||def.get(keyArgs,'drawMarker',true);if(this.drawMarker){this.markerShape=def.get(keyArgs,'markerShape','square');this.markerPvProto=def.get(keyArgs,'markerPvProto')}}).add({drawRule:false,drawMarker:true,markerShape:null,rulePvProto:null,markerPvProto:null,create:function(legendPanel,pvBulletPanel,extensionPrefix,wrapper){var renderInfo={};var drawRule=this.drawRule;var sceneColorProp=function(scene){return scene.color};if(drawRule){var rulePvBaseProto=new pv.Mark().left(0).top(function(){return this.parent.height()/2}).width(function(){return this.parent.width()}).lineWidth(1,pvc.extensionTag).strokeStyle(sceneColorProp,pvc.extensionTag);if(this.rulePvProto){rulePvBaseProto=this.rulePvProto.extend(rulePvBaseProto)}renderInfo.pvRule=new pvc.visual.Rule(legendPanel,pvBulletPanel,{proto:rulePvBaseProto,noSelect:this.noSelect,noHover:this.noHover,activeSeriesAware:false,extensionId:extensionPrefix+"Rule",wrapper:wrapper}).pvMark}if(this.drawMarker){var markerPvBaseProto=new pv.Mark().left(function(){return this.parent.width()/2}).top(function(){return this.parent.height()/2}).shapeSize(function(){return this.parent.width()},pvc.extensionTag).lineWidth(2,pvc.extensionTag).fillStyle(sceneColorProp,pvc.extensionTag).strokeStyle(sceneColorProp,pvc.extensionTag).shape(this.markerShape,pvc.extensionTag).angle(drawRule?0:Math.PI/2,pvc.extensionTag).antialias(function(){var cos=Math.abs(Math.cos(this.angle()));if(cos!==0&&cos!==1){switch(this.shape()){case'square':case'bar':return false}}return true},pvc.extensionTag);if(this.markerPvProto){markerPvBaseProto=this.markerPvProto.extend(markerPvBaseProto)}renderInfo.pvDot=new pvc.visual.Dot(legendPanel,pvBulletPanel,{proto:markerPvBaseProto,freePosition:true,activeSeriesAware:false,noTooltip:true,noSelect:this.noSelect,noHover:this.noHover,extensionId:extensionPrefix+"Dot",wrapper:wrapper}).pvMark}return renderInfo}});
def.scope(function(){def.type('pvc.visual.Plot',pvc.visual.OptionsBase).init(function(chart,keyArgs){var typePlots=def.getPath(chart,['plotsByType',this.type]);var index=typePlots?typePlots.length:0;var globalIndex=chart.plotList.length;keyArgs=def.set(keyArgs,'byNaked',!globalIndex);this.base(chart,this.type,index,keyArgs);chart._addPlot(this);var prefixes=this.extensionPrefixes=[this.id];if(!this.globalIndex){prefixes.push('')}if(this.name){prefixes.push(this.name)}}).add({_getOptionsDefinition:function(){return pvc.visual.Plot.optionsDef},_resolveByNaked:pvc.options.specify(function(optionInfo){if(!this.globalIndex){return this._chartOption(def.firstLowerCase(optionInfo.name))}})});pvc.visual.Plot.optionsDef={Orientation:{resolve:function(optionInfo){optionInfo.specify(this._chartOption('orientation')||'vertical');return true},cast:String},ValuesVisible:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){if(this.globalIndex===0){var show=this._chartOption('showValues');if(show!==undefined){optionInfo.specify(show)}else{show=this.type!=='point';optionInfo.defaultValue(show)}return true}}},cast:Boolean,value:false},ValuesAnchor:{resolve:'_resolveFull',cast:pvc.parseAnchor},ValuesFont:{resolve:'_resolveFull',cast:String,value:'10px sans-serif'},ValuesMask:{resolve:'_resolveFull',cast:String,value:"{value}"},DataPart:{resolve:'_resolveFixed',cast:String,value:'0'},ColorRole:{resolve:'_resolveFixed',cast:String,value:'color'},ColorAxis:{resolve:pvc.options.resolvers([function(optionInfo){if(this.globalIndex===0){optionInfo.specify(1);return true}},'_resolveFull']),cast:function(value){value=pvc.castNumber(value);if(value!=null){value=def.between(value,1,10)}else{value=1}return value},value:1}}});
def.scope(function(){def.type('pvc.visual.CartesianPlot',pvc.visual.Plot).add({_getOptionsDefinition:function(){return pvc.visual.CartesianPlot.optionsDef}});function castTrend(trend){if(this.name==='trend'){return null}var type=this.option('TrendType');if(!type&&trend){type=trend.type}if(!type||type==='none'){return null}if(!trend){trend={}}else{trend=Object.create(trend)}trend.type=type;var label=this.option('TrendLabel');if(label!==undefined){trend.label=label}return trend}pvc.visual.CartesianPlot.optionsDef=def.create(pvc.visual.Plot.optionsDef,{BaseAxis:{value:1},BaseRole:{resolve:'_resolveFixed',cast:String},OrthoAxis:{resolve:function(optionInfo){if(this.globalIndex===0){optionInfo.specify(1);return true}return this._resolveFull(optionInfo)},data:{resolveV1:function(optionInfo){if(this.name==='plot2'&&this.chart._allowV1SecondAxis&&this._chartOption('secondAxisIndependentScale')){optionInfo.specify(2)}return true}},cast:function(value){value=pvc.castNumber(value);if(value!=null){value=def.between(value,1,10)}else{value=1}return value},value:1},OrthoRole:{resolve:pvc.options.resolvers(['_resolveFixed','_resolveDefault'])},Trend:{resolve:'_resolveFull',data:{resolveDefault:function(optionInfo){var type=this.option('TrendType');if(type){optionInfo.defaultValue({type:type});return true}}},cast:castTrend},TrendType:{resolve:'_resolveFull',cast:pvc.parseTrendType},TrendLabel:{resolve:'_resolveFull',cast:String},NullInterpolationMode:{resolve:'_resolveFull',cast:pvc.parseNullInterpolationMode,value:'none'}})});
def.scope(function(){def.type('pvc.visual.CategoricalPlot',pvc.visual.CartesianPlot).add({_getOptionsDefinition:function(){return pvc.visual.CategoricalPlot.optionsDef}});pvc.visual.CategoricalPlot.optionsDef=def.create(pvc.visual.CartesianPlot.optionsDef,{Stacked:{resolve:'_resolveFull',cast:Boolean,value:false},BaseRole:{value:'category'},OrthoRole:{value:'value'}})});
def.scope(function(){def.type('pvc.visual.BarPlotAbstract',pvc.visual.CategoricalPlot).add({_getOptionsDefinition:function(){return pvc.visual.BarPlotAbstract.optionsDef}});pvc.visual.BarPlotAbstract.optionsDef=def.create(pvc.visual.CategoricalPlot.optionsDef,{BarSizeRatio:{resolve:'_resolveFull',cast:function(value){value=pvc.castNumber(value);if(value==null){value=1}else if(value<0.05){value=0.05}else if(value>1){value=1}return value},value:0.9},BarSizeMax:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyChartOption(optionInfo,'maxBarSize');return true}},cast:function(value){value=pvc.castNumber(value);if(value==null){value=Infinity}else if(value<1){value=1}return value},value:2000},BarStackedMargin:{resolve:'_resolveFull',cast:function(value){value=pvc.castNumber(value);if(value!=null&&value<0){value=0}return value},value:0},OverflowMarkersVisible:{resolve:'_resolveFull',cast:Boolean,value:true},ValuesAnchor:{value:'center'}})});
def.type('pvc.visual.BarPlot',pvc.visual.BarPlotAbstract).add({type:'bar'});
def.scope(function(){def.type('pvc.visual.NormalizedBarPlot',pvc.visual.BarPlotAbstract).add({type:'bar',_getOptionsDefinition:function(){return pvc.visual.NormalizedBarPlot.optionsDef}});pvc.visual.NormalizedBarPlot.optionsDef=def.create(pvc.visual.BarPlotAbstract.optionsDef,{Stacked:{resolve:null,value:true}})});
def.scope(function(){def.type('pvc.visual.WaterfallPlot',pvc.visual.BarPlotAbstract).add({type:'water',_getOptionsDefinition:function(){return pvc.visual.WaterfallPlot.optionsDef}});pvc.visual.WaterfallPlot.optionsDef=def.create(pvc.visual.BarPlotAbstract.optionsDef,{Stacked:{resolve:null,value:true},TotalLineLabel:{resolve:'_resolveFull',cast:String,value:"Accumulated"},TotalValuesVisible:{resolve:'_resolveFull',data:{resolveDefault:function(optionInfo){optionInfo.defaultValue(this.option('ValuesVisible'));return true}},cast:Boolean},Direction:{resolve:'_resolveFull',cast:pvc.parseWaterDirection,value:'down'},AreasVisible:{resolve:'_resolveFull',cast:Boolean,value:true},AllCategoryLabel:{resolve:'_resolveFull',cast:String,value:"All"}})});
def.scope(function(){def.type('pvc.visual.PointPlot',pvc.visual.CategoricalPlot).add({type:'point',_getOptionsDefinition:function(){return pvc.visual.PointPlot.optionsDef}});function visibleData(type,dv){return{resolveV1:function(optionInfo){if(this.globalIndex===0){if(!this._specifyChartOption(optionInfo,'show'+type)){optionInfo.defaultValue(dv)}return true}}}}pvc.visual.PointPlot.optionsDef=def.create(pvc.visual.CategoricalPlot.optionsDef,{DotsVisible:{resolve:'_resolveFull',data:visibleData('Dots',true),cast:Boolean,value:false},LinesVisible:{resolve:'_resolveFull',data:visibleData('Lines',true),cast:Boolean,value:false},AreasVisible:{resolve:'_resolveFull',data:visibleData('Areas',false),cast:Boolean,value:false},ValuesAnchor:{value:'right'}})});
def.scope(function(){def.type('pvc.visual.MetricXYPlot',pvc.visual.CartesianPlot).add({_getOptionsDefinition:function(){return pvc.visual.MetricXYPlot.optionsDef}});pvc.visual.MetricXYPlot.optionsDef=def.create(pvc.visual.CartesianPlot.optionsDef,{BaseRole:{value:'x'},OrthoAxis:{resolve:null},OrthoRole:{value:'y'}})});
def.scope(function(){def.type('pvc.visual.MetricPointPlot',pvc.visual.MetricXYPlot).add({type:'scatter',_getOptionsDefinition:function(){return pvc.visual.MetricPointPlot.optionsDef}});function visibleData(type){return{resolveV1:function(optionInfo){this._specifyChartOption(optionInfo,'show'+type);return true}}}pvc.visual.MetricPointPlot.optionsDef=def.create(pvc.visual.MetricXYPlot.optionsDef,{SizeRole:{resolve:'_resolveFixed',value:'size'},SizeAxis:{resolve:'_resolveFixed',value:1},Shape:{resolve:'_resolveFull',cast:pvc.parseShape,value:'circle'},DotsVisible:{resolve:'_resolveFull',data:visibleData('Dots'),cast:Boolean,value:false},LinesVisible:{resolve:'_resolveFull',data:visibleData('Lines'),cast:Boolean,value:false},ValuesAnchor:{value:'right'}})});
def.scope(function(){def.type('pvc.visual.PiePlot',pvc.visual.Plot).add({type:'pie',_getOptionsDefinition:function(){return pvc.visual.PiePlot.optionsDef}});pvc.visual.PiePlot.optionsDef=def.create(pvc.visual.Plot.optionsDef,{ActiveSliceRadius:{resolve:'_resolveFull',cast:pvc.PercentValue.parse,value:new pvc.PercentValue(0.05)},ExplodedSliceRadius:{resolve:'_resolveFull',cast:pvc.PercentValue.parse,value:0},ExplodedSliceIndex:{resolve:'_resolveFull',cast:pvc.castNumber,value:null},ValuesAnchor:{cast:pvc.parseAnchorWedge,value:'outer'},ValuesVisible:{value:true},ValuesLabelStyle:{resolve:function(optionInfo){var isV1Compat=this.chart.compatVersion()<=1;if(isV1Compat){optionInfo.specify('inside');return true}return this._resolveFull(optionInfo)},cast:function(value){switch(value){case'inside':case'linked':return value}if(pvc.debug>=2){pvc.log("[Warning] Invalid 'ValuesLabelStyle' value: '"+value+"'.")}return'linked'},value:'linked'},ValuesMask:{resolve:'_resolveFull',data:{resolveDefault:function(optionInfo){optionInfo.defaultValue(this.option('ValuesLabelStyle')==='linked'?"{value} ({value.percent})":"{value}");return true}}},LinkInsetRadius:{resolve:'_resolveFull',cast:pvc.PercentValue.parse,value:new pvc.PercentValue(0.05)},LinkOutsetRadius:{resolve:'_resolveFull',cast:pvc.PercentValue.parse,value:new pvc.PercentValue(0.025)},LinkMargin:{resolve:'_resolveFull',cast:pvc.PercentValue.parse,value:new pvc.PercentValue(0.025)},LinkHandleWidth:{resolve:'_resolveFull',cast:pvc.castNumber,value:0.5},LinkLabelSize:{resolve:'_resolveFull',cast:pvc.PercentValue.parse,value:new pvc.PercentValue(0.15)},LinkLabelSpacingMin:{resolve:'_resolveFull',cast:pvc.castNumber,value:0.5}})});
def.scope(function(){def.type('pvc.visual.HeatGridPlot',pvc.visual.CategoricalPlot).add({type:'heatGrid',_getOptionsDefinition:function(){return pvc.visual.HeatGridPlot.optionsDef}});pvc.visual.HeatGridPlot.optionsDef=def.create(pvc.visual.CategoricalPlot.optionsDef,{SizeRole:{value:'size'},SizeAxis:{value:1},UseShapes:{resolve:'_resolveFull',cast:Boolean,value:false},Shape:{resolve:'_resolveFull',cast:pvc.parseShape,value:'square'},NullShape:{resolve:'_resolveFull',cast:pvc.parseShape,value:'cross'},ValuesVisible:{value:true},OrthoRole:{value:'series'},OrthoAxis:{resolve:null},NullInterpolationMode:{resolve:null,value:'none'},Stacked:{resolve:null,value:false}})});
def.scope(function(){def.type('pvc.visual.BoxPlot',pvc.visual.CategoricalPlot).add({type:'box',_getOptionsDefinition:function(){return pvc.visual.BoxPlot.optionsDef}});pvc.visual.BoxPlot.optionsDef=def.create(pvc.visual.CategoricalPlot.optionsDef,{Stacked:{resolve:null,value:false},OrthoRole:{value:['median','lowerQuartil','upperQuartil','minimum','maximum']},BoxSizeRatio:{resolve:'_resolveFull',cast:function(value){value=pvc.castNumber(value);if(value==null){value=1}else if(value<0.05){value=0.05}else if(value>1){value=1}return value},value:1/3},BoxSizeMax:{resolve:'_resolveFull',data:{resolveV1:function(optionInfo){this._specifyChartOption(optionInfo,'maxBoxSize');return true}},cast:function(value){value=pvc.castNumber(value);if(value==null){value=Infinity}else if(value<1){value=1}return value},value:Infinity}})});
def.type('pvc.visual.BulletPlot',pvc.visual.Plot).add({type:'bullet',_getOptionsDefinition:function(){return pvc.visual.BulletPlot.optionsDef}});pvc.visual.BulletPlot.optionsDef=def.create(pvc.visual.Plot.optionsDef,{ValuesVisible:{value:true},ColorRole:{value:null}});
def.type('pvc.Abstract').init(function(){this._syncLog()}).add({invisibleLineWidth:0.001,defaultLineWidth:1.5,_logInstanceId:null,_syncLog:function(){if(pvc.debug&&typeof console!=="undefined"){var logId=this._getLogInstanceId();['log','info',['trace','debug'],'error','warn','group','groupEnd'].forEach(function(ps){ps=ps instanceof Array?ps:[ps,ps];pvc._installLog(this,'_'+ps[0],ps[1],logId)},this)}},_getLogInstanceId:function(){return this._logInstanceId||(this._logInstanceId=this._processLogInstanceId(this._createLogInstanceId()))},_createLogInstanceId:function(){return''+this.constructor},_processLogInstanceId:function(logInstanceId){var L=30;var s=logInstanceId.substr(0,L);if(s.length<L){s+=def.array.create(L-s.length,' ').join('')}return"["+s+"]"}});def.scope(function(){var o=pvc.Abstract.prototype;var syncLogHook=function(){this._syncLog()};['log','info','trace','error','warn','group','groupEnd'].forEach(function(p){o['_'+p]=syncLogHook})});
def.type('pvc.BaseChart',pvc.Abstract).init(function(options){var originalOptions=options;var parent=this.parent=def.get(options,'parent')||null;if(parent){options||def.fail.argumentRequired('options')}else{options=def.mixin.copy({},this.defaults,options)}this.options=options;if(parent){this.root=parent.root;this.smallColIndex=options.smallColIndex;this.smallRowIndex=options.smallRowIndex;this._tooltipEnabled=parent._tooltipEnabled;this._tooltipOptions=parent._tooltipOptions}else{this.root=this}this.base();if(pvc.debug>=3){this._info("NEW CHART\n"+pvc.logSeparator.replace(/-/g,'=')+"\n  DebugLevel: "+pvc.debug)}if(pvc.debug>=3&&!parent&&originalOptions){this._info("OPTIONS:\n",originalOptions);if(pvc.debug>=5){this._trace(pvc.stringify(options,{ownOnly:false,funs:true}))}}if(parent){parent._addChild(this)}this._constructData(options);this._constructVisualRoles(options)}).add({_disposed:false,_animatable:false,parent:null,children:null,root:null,isPreRendered:false,_createVersion:0,renderCallback:undefined,multiChartPageCount:null,multiChartPageIndex:null,left:0,top:0,width:null,height:null,margins:null,paddings:null,_allowV1SecondAxis:false,compatVersion:function(options){return(options||this.options).compatVersion},_createLogInstanceId:function(){return""+this.constructor+this._createLogChildSuffix()},_createLogChildSuffix:function(){return this.parent?(" ("+(this.smallRowIndex+1)+","+(this.smallColIndex+1)+")"):""},_addChild:function(childChart){(childChart.parent===this)||def.assert("Not a child of this chart.");this.children.push(childChart)},_preRender:function(keyArgs){this._preRenderPhase1(keyArgs);this._preRenderPhase2(keyArgs)},_preRenderPhase1:function(keyArgs){this._createVersion++;this.isPreRendered=false;if(pvc.debug>=3){this._log("Prerendering")}this.children=[];if(!this.parent){pvc.removeTipsyLegends()}this._processOptions();this._checkNoDataI();if(!this.parent&&this._createVersion===1){this._initVisualRoles();this._bindVisualRolesPreI();this._complexTypeProj=this._createComplexTypeProject();this._bindVisualRolesPreII()}this._initData(keyArgs);this._checkNoDataII();var hasMultiRole=this._isRoleAssigned('multiChart');this._initPlots(hasMultiRole);this._initAxes(hasMultiRole);this._bindAxes(hasMultiRole);if(this.parent||!hasMultiRole){this._interpolate(hasMultiRole);this._generateTrends(hasMultiRole)}this._setAxesScales(hasMultiRole)},_preRenderPhase2:function(){var hasMultiRole=this._isRoleAssigned('multiChart');this._initChartPanels(hasMultiRole);this.isPreRendered=true},_setSmallLayout:function(keyArgs){if(keyArgs){var basePanel=this.basePanel;if(this._setProp('left',keyArgs)|this._setProp('top',keyArgs)){if(basePanel){def.set(basePanel.position,'left',this.left,'top',this.top)}}if(this._setProp('width',keyArgs)|this._setProp('height',keyArgs)){if(basePanel){basePanel.size=new pvc.Size(this.width,this.height)}}if(this._setProp('margins',keyArgs)&&basePanel){basePanel.margins=new pvc.Sides(this.margins)}if(this._setProp('paddings',keyArgs)&&basePanel){basePanel.paddings=new pvc.Sides(this.paddings)}}},_setProp:function(p,keyArgs){var v=keyArgs[p];if(v!=null){this[p]=v;return true}},_processOptions:function(){var options=this.options;if(parseInt(options.width,10)+"%"==options.width){try{var viewportwidth,viewportheight,wdiv,r,scr=null,inn=null,wNoScroll=0,wScroll=0;if(typeof window.innerWidth!='undefined'){viewportwidth=window.innerWidth,viewportheight=window.innerHeight}else if(typeof document.documentElement!='undefined'&&typeof document.documentElement.clientWidth!='undefined'&&document.documentElement.clientWidth!=0){viewportwidth=document.documentElement.clientWidth,viewportheight=document.documentElement.clientHeight}else{viewportwidth=document.getElementsByTagName('body')[0].clientWidth,viewportheight=document.getElementsByTagName('body')[0].clientHeight}scr=document.createElement('div');scr.style.position='absolute';scr.style.top='-1000px';scr.style.left='-1000px';scr.style.width='100px';scr.style.height='50px';scr.style.overflow='hidden';inn=document.createElement('div');inn.style.width='100%';inn.style.height='200px';scr.appendChild(inn);document.body.appendChild(scr);wNoScroll=inn.offsetWidth;scr.style.overflow='auto';wScroll=inn.offsetWidth;document.body.removeChild(document.body.lastChild);viewportwidth=viewportwidth-(wNoScroll-wScroll);r=(parseInt(options.width,10)/100)*viewportwidth;options.width=parseInt(r,10)}catch(e){options.width=parseInt(options.width,10)}}if(!this.parent){this.width=options.width;this.height=options.height;this.margins=options.margins;this.paddings=options.paddings}if(this.compatVersion()<=1){options.plot2=this._allowV1SecondAxis&&!!options.secondAxis}this._processOptionsCore(options);this._processExtensionPoints();return options},_processOptionsCore:function(options){if(!this.parent){if(!$.support.svg||pv.renderer()==='batik'){options.animate=false}this._processTooltipOptions(options)}},_tooltipDefaults:{gravity:'s',delayIn:200,delayOut:80,offset:2,opacity:0.9,html:true,fade:true,useCorners:false,arrowVisible:true,followMouse:false,format:undefined},_processTooltipOptions:function(options){var isV1Compat=this.compatVersion()<=1;var tipOptions=options.tooltip;var tipEnabled=options.tooltipEnabled;if(tipEnabled==null){if(tipOptions){tipEnabled=tipOptions.enabled}if(tipEnabled==null){if(isV1Compat){tipEnabled=options.showTooltips}if(tipEnabled==null){tipEnabled=true}}}if(tipEnabled){if(!tipOptions){tipOptions={}}if(isV1Compat){this._importV1TooltipOptions(tipOptions,options)}def.eachOwn(this._tooltipDefaults,function(dv,p){var value=options['tooltip'+def.firstUpperCase(p)];if(value!==undefined){tipOptions[p]=value}else if(tipOptions[p]===undefined){tipOptions[p]=dv}})}else{tipOptions={}}this._tooltipEnabled=tipEnabled;this._tooltipOptions=tipOptions},_importV1TooltipOptions:function(tipOptions,options){var v1TipOptions=options.tipsySettings;if(v1TipOptions){this.extend(v1TipOptions,"tooltip");for(var p in v1TipOptions){if(tipOptions[p]===undefined){tipOptions[p]=v1TipOptions[p]}}if(tipOptions.html==null){tipOptions.html=false}}},render:function(bypassAnimation,recreate,reloadData){var hasError;if(pvc.debug>1){pvc.group("CCC RENDER")}this._suspendSelectionUpdate();try{this.useTextMeasureCache(function(){try{if(!this.isPreRendered||recreate){this._preRender({reloadData:reloadData})}else if(!this.parent&&this.isPreRendered){pvc.removeTipsyLegends()}this.basePanel.render({bypassAnimation:bypassAnimation,recreate:recreate})}catch(e){if(e instanceof NoDataException){if(pvc.debug>1){this._log("No data found.")}this._addErrorPanelMessage("No data found",true)}else{hasError=true;pvc.logError(e.message);if(pvc.debug>0){this._addErrorPanelMessage("Error: "+e.message,false)}}}})}finally{if(!hasError){this._resumeSelectionUpdate()}if(pvc.debug>1){pvc.groupEnd()}}return this},_addErrorPanelMessage:function(text,isNoData){var options=this.options,pvPanel=new pv.Panel().canvas(options.canvas).width(this.width).height(this.height),pvMsg=pvPanel.anchor("center").add(pv.Label).text(text);if(isNoData){this.extend(pvMsg,"noDataMessage")}pvPanel.render()},useTextMeasureCache:function(fun,ctx){var root=this.root;var textMeasureCache=root._textMeasureCache||(root._textMeasureCache=pv.Text.createCache());return pv.Text.usingCache(textMeasureCache,fun,ctx||this)},animate:function(start,end){return this.basePanel.animate(start,end)},isAnimatingStart:function(){return this.basePanel.isAnimatingStart()},isOrientationVertical:function(orientation){return(orientation||this.options.orientation)===pvc.orientation.vertical},isOrientationHorizontal:function(orientation){return(orientation||this.options.orientation)===pvc.orientation.horizontal},dispose:function(){if(!this._disposed){this._disposed=true}},defaults:{width:400,height:300,orientation:'vertical',ignoreNulls:true,crosstabMode:true,isMultiValued:false,seriesInRows:false,groupedLabelSep:undefined,animate:true,titlePosition:"top",titleAlign:"center",legend:false,legendPosition:"bottom",v1StyleTooltipFormat:function(s,c,v,datum){return s+", "+c+":  "+this.chart.options.valueFormat(v)+(datum&&datum.percent?(" ("+datum.percent.label+")"):"")},valueFormat:def.scope(function(){var pvFormat=pv.Format.number().fractionDigits(0,2);return function(d){return pvFormat.format(d)}}),percentValueFormat:def.scope(function(){var pvFormat=pv.Format.number().fractionDigits(0,1);return function(d){return pvFormat.format(d*100)+"%"}}),clickable:false,doubleClickMaxDelay:300,hoverable:false,selectable:false,selectionMode:'rubberband',ctrlSelectMode:true,clearSelectionMode:'emptySpaceClick',compatVersion:Infinity}});
pvc.BaseChart.add({_visualRoles:null,_visualRoleList:null,_serRole:null,_dataPartRole:null,_measureVisualRoles:null,_constructVisualRoles:function(){var parent=this.parent;if(parent){this._visualRoles=parent._visualRoles;this._visualRoleList=parent._visualRoleList;this._measureVisualRoles=parent._measureVisualRoles;if(parent._multiChartRole){this._multiChartRole=parent._multiChartRole}if(parent._serRole){this._serRole=parent._serRole}if(parent._colorRole){this._colorRole=parent._colorRole}if(parent._dataPartRole){this._dataPartRole=parent._dataPartRole}}else{this._visualRoles={};this._visualRoleList=[];this._measureVisualRoles=[]}},_hasDataPartRole:function(){return false},_getSeriesRoleSpec:function(){return null},_getColorRoleSpec:function(){return null},_addVisualRole:function(name,keyArgs){keyArgs=def.set(keyArgs,'index',this._visualRoleList.length);var visualRole=new pvc.visual.Role(name,keyArgs);this._visualRoleList.push(visualRole);this._visualRoles[name]=visualRole;if(visualRole.isMeasure){this._measureVisualRoles.push(visualRole)}return visualRole},_initVisualRoles:function(){this._multiChartRole=this._addVisualRole('multiChart',{defaultDimension:'multiChart*',requireIsDiscrete:true});if(this._hasDataPartRole()){this._dataPartRole=this._addVisualRole('dataPart',{defaultDimension:'dataPart',requireSingleDimension:true,requireIsDiscrete:true,dimensionDefaults:{isHidden:true,comparer:def.compare}})}var serRoleSpec=this._getSeriesRoleSpec();if(serRoleSpec){this._serRole=this._addVisualRole('series',serRoleSpec)}var colorRoleSpec=this._getColorRoleSpec();if(colorRoleSpec){this._colorRole=this._addVisualRole('color',colorRoleSpec)}},_bindVisualRolesPreI:function(){def.eachOwn(this._visualRoles,function(role){role.setIsReversed(false)});var sourcedRoles=[];var options=this.options;var roleOptions=options.visualRoles;this._visualRoleList.forEach(function(visualRole){var name=visualRole.name;var roleSpec=options[name+'Role'];if(roleSpec!==undefined){if(!roleOptions){roleOptions=options.visualRoles={}}if(roleOptions[name]===undefined){roleOptions[name]=roleSpec}}});var dimsBoundToSingleRole;if(roleOptions){dimsBoundToSingleRole={};var rolesWithOptions=def.query(def.keys(roleOptions)).select(function(name){return this._visualRoles[name]||def.fail.operationInvalid("Role '{0}' is not supported by the chart type.",[name])},this).array();rolesWithOptions.sort(function(a,b){return a.index-b.index});rolesWithOptions.forEach(function(visualRole){var name=visualRole.name;var roleSpec=roleOptions[name];var groupingSpec,sourceRoleName;if(def.object.is(roleSpec)){if(def.nullyTo(roleSpec.isReversed,false)){visualRole.setIsReversed(true)}sourceRoleName=roleSpec.from;if(sourceRoleName&&(sourceRoleName!==name)){var sourceRole=this._visualRoles[sourceRoleName]||def.fail.operationInvalid("Source role '{0}' is not supported by the chart type.",[sourceRoleName]);visualRole.setSourceRole(sourceRole);sourcedRoles.push(visualRole)}else{groupingSpec=roleSpec.dimensions}}else{groupingSpec=roleSpec}if(groupingSpec!==undefined){var grouping=pvc.data.GroupingSpec.parse(groupingSpec);visualRole.preBind(grouping);grouping.dimensions().each(function(groupDimSpec){if(def.hasOwn(dimsBoundToSingleRole,groupDimSpec.name)){delete dimsBoundToSingleRole[groupDimSpec.name]}else{dimsBoundToSingleRole[groupDimSpec.name]=visualRole}})}},this)}this._sourcedRoles=sourcedRoles;this._dimsBoundToSingleRole=dimsBoundToSingleRole},_bindVisualRolesPreII:function(){var dimsBoundToSingleRole=this._dimsBoundToSingleRole;if(dimsBoundToSingleRole){delete this._dimsBoundToSingleRole;def.eachOwn(dimsBoundToSingleRole,this._setRoleBoundDimensionDefaults,this)}var sourcedRoles=this._sourcedRoles;delete this._sourcedRoles;def.query(this._visualRoleList).where(function(role){return role.defaultSourceRoleName&&!role.sourceRole&&!role.isPreBound()}).each(function(role){var sourceRole=this._visualRoles[role.defaultSourceRoleName];if(sourceRole){role.setSourceRole(sourceRole);sourcedRoles.push(role)}},this);sourcedRoles.forEach(function(role){var sourceRole=role.sourceRole;if(sourceRole.isReversed){role.setIsReversed(!role.isReversed)}if(!role.defaultDimensionName&&sourceRole.isPreBound()){role.preBind(sourceRole.preBoundGrouping())}})},_setRoleBoundDimensionDefaults:function(role,dimName){this._complexTypeProj.setDimDefaults(dimName,role.dimensionDefaults)},_bindVisualRolesPostI:function(){var complexTypeProj=this._complexTypeProj;var boundDimTypes={};var unboundSourcedRoles=[];def.query(this._visualRoleList).where(function(role){return role.isPreBound()}).each(markPreBoundRoleDims,this);def.query(this._visualRoleList).where(function(role){return!role.isPreBound()}).each(autoBindUnboundRole,this);unboundSourcedRoles.forEach(tryPreBindSourcedRole,this);def.query(def.ownKeys(boundDimTypes)).where(function(dimName){return boundDimTypes[dimName].length===1}).each(function(dimName){var singleRole=boundDimTypes[dimName][0];this._setRoleBoundDimensionDefaults(singleRole,dimName)},this);function markDimBoundTo(dimName,role){def.array.lazy(boundDimTypes,dimName).push(role)}function dimIsDefined(dimName){return complexTypeProj.hasDim(dimName)}function preBindRoleTo(role,dimNames){if(def.array.is(dimNames)){dimNames.forEach(function(dimName){markDimBoundTo(dimName,role)})}else{markDimBoundTo(dimNames,role)}role.setSourceRole(null);role.preBind(pvc.data.GroupingSpec.parse(dimNames))}function preBindRoleToGroupDims(role,groupDimNames){if(groupDimNames.length){if(role.requireSingleDimension){preBindRoleTo(role,groupDimNames[0])}else{preBindRoleTo(role,groupDimNames)}}}function preBindRoleToNewDim(role,dimName){complexTypeProj.setDim(dimName,{isHidden:true});preBindRoleTo(role,dimName)}function roleIsUnbound(role){if(role.isRequired){throw def.error.operationInvalid("Chart type requires unassigned role '{0}'.",[role.name])}role.bind(null);role.setSourceRole(null)}function markPreBoundRoleDims(role){role.preBoundGrouping().dimensionNames().forEach(markDimBoundTo)}function autoBindUnboundRole(role){var name=role.name;var dimName=role.defaultDimensionName;if(!dimName){if(role.sourceRole){unboundSourcedRoles.push(role)}else{roleIsUnbound(role)}return}var match=dimName.match(/^(.*?)(\*)?$/)||def.fail.argumentInvalid('defaultDimensionName');var defaultName=match[1];var greedy=match[2];if(greedy){var groupDimNames=complexTypeProj.groupDimensionsNames(defaultName);if(groupDimNames){preBindRoleToGroupDims(role,groupDimNames);return}}else if(dimIsDefined(defaultName)){preBindRoleTo(role,defaultName);return}if(role.autoCreateDimension){preBindRoleToNewDim(role,defaultName);return}if(role.sourceRole){unboundSourcedRoles.push(role)}else{roleIsUnbound(role)}}function tryPreBindSourcedRole(role){var sourceRole=role.sourceRole;if(sourceRole.isPreBound()){role.preBind(sourceRole.preBoundGrouping())}else{roleIsUnbound(role)}}},_bindVisualRolesPostII:function(complexType){def.query(this._visualRoleList).where(function(role){return role.isPreBound()}).each(commitRolePreBinding,this);function commitRolePreBinding(role){role.postBind(complexType)}},_logVisualRoles:function(){var out=["VISUAL ROLES MAP SUMMARY",pvc.logSeparator,"  VisualRole         <-- Dimensions",pvc.logSeparator];def.eachOwn(this._visualRoles,function(role,name){out.push("  "+name+def.array.create(18-name.length," ").join("")+(role.grouping?(" <-- "+role.grouping):''))});this._log(out.join("\n"))},visualRoles:function(roleName,keyArgs){if(roleName==null){return def.own(this._visualRoles)}var role=def.getOwn(this._visualRoles,roleName)||null;if(!role&&def.get(keyArgs,'assertExists',true)){throw def.error.argumentInvalid('roleName',"Undefined role name '{0}'.",[roleName])}return role},measureVisualRoles:function(){return this._measureVisualRoles},measureDimensionsNames:function(){return def.query(this._measureVisualRoles).select(function(visualRole){return visualRole.firstDimensionName()}).where(def.notNully).array()},_isRoleAssigned:function(roleName){return!!this._visualRoles[roleName].grouping},_getDataPartDimName:function(){var role=this._dataPartRole;if(role){if(role.isBound()){return role.firstDimensionName()}var preGrouping=role.preBoundGrouping();if(preGrouping){return preGrouping.firstDimensionName()}return role.defaultDimensionName}}});
pvc.BaseChart.add({dataEngine:null,data:null,_partData:null,_visibleDataCache:null,resultset:[],metadata:[],_constructData:function(options){var parent=this.parent;if(parent){this.dataEngine=this.data=options.data||def.fail.argumentRequired('options.data')}},_checkNoDataI:function(){if(!this.parent){if(!this.allowNoData&&this.resultset.length===0){throw new NoDataException()}}},_checkNoDataII:function(){if(!this.parent){if(!this.allowNoData&&(!this.data||!this.data.count())){throw new NoDataException()}}},_initData:function(keyArgs){if(!this.parent){var data=this.data;if(!data||def.get(keyArgs,'reloadData',true)){this._onLoadData()}else{data.clearVirtuals();data.disposeChildren()}}delete this._partData;delete this._visibleDataCache;if(pvc.debug>=3){this._log(this.data.getInfo())}},_onLoadData:function(){var data=this.data;var options=this.options;var dataPartDimName=this._getDataPartDimName();var complexTypeProj=this._complexTypeProj;var translOptions=this._createTranslationOptions(dataPartDimName);var translation=this._createTranslation(translOptions);if(pvc.debug>=3){translation.logSource()}if(!data){translation.configureType();if(dataPartDimName&&!complexTypeProj.isReadOrCalc(dataPartDimName)){this._addDefaultDataPartCalculation(dataPartDimName)}}this._bindVisualRolesPostI();var complexType;if(!data){complexType=new pvc.data.ComplexType();complexTypeProj.configureComplexType(complexType,translOptions)}else{complexType=data.type}this._bindVisualRolesPostII(complexType);if(pvc.debug>=10){this._log(complexType.describe())}if(pvc.debug>=3){this._logVisualRoles()}if(!data){data=this.dataEngine=this.data=new pvc.data.Data({type:complexType,labelSep:options.groupedLabelSep})}var loadKeyArgs={where:this._getLoadFilter(),isNull:this._getIsNullDatum()};var resultQuery=translation.execute(data);data.load(resultQuery,loadKeyArgs)},_createComplexTypeProject:function(){var options=this.options;var complexTypeProj=new pvc.data.ComplexTypeProject(options.dimensionGroups);var userDimsSpec=options.dimensions;for(var dimName in userDimsSpec){complexTypeProj.setDim(dimName,userDimsSpec[dimName])}var dataPartDimName=this._getDataPartDimName();if(dataPartDimName){complexTypeProj.setDim(dataPartDimName);this._addPlot2SeriesDataPartCalculation(complexTypeProj,dataPartDimName)}var calcSpecs=options.calculations;if(calcSpecs){calcSpecs.forEach(function(calcSpec){complexTypeProj.setCalc(calcSpec)})}return complexTypeProj},_getLoadFilter:function(){if(this.options.ignoreNulls){var me=this;return function(datum){var isNull=datum.isNull;if(isNull&&pvc.debug>=4){me._info("Datum excluded.")}return!isNull}}},_getIsNullDatum:function(){var measureDimNames=this.measureDimensionsNames(),M=measureDimNames.length;if(M){return function(datum){var atoms=datum.atoms;for(var i=0;i<M;i++){if(atoms[measureDimNames[i]].value!=null){return false}}return true}}},_createTranslation:function(translOptions){var TranslationClass=this._getTranslationClass(translOptions);return new TranslationClass(this,this._complexTypeProj,this.resultset,this.metadata,translOptions)},_getTranslationClass:function(translOptions){return translOptions.crosstabMode?pvc.data.CrosstabTranslationOper:pvc.data.RelationalTranslationOper},_createTranslationOptions:function(dataPartDimName){var options=this.options;var dataOptions=options.dataOptions||{};var dataSeparator=options.dataSeparator;if(dataSeparator===undefined){dataSeparator=dataOptions.separator}var dataMeasuresInColumns=options.dataMeasuresInColumns;if(dataMeasuresInColumns===undefined){dataMeasuresInColumns=dataOptions.measuresInColumns}var dataCategoriesCount=options.dataCategoriesCount;if(dataCategoriesCount===undefined){dataCategoriesCount=dataOptions.categoriesCount}var plot2=options.plot2;var valueFormat=options.valueFormat,valueFormatter;if(valueFormat&&valueFormat!==this.defaults.valueFormat){valueFormatter=function(v){return v!=null?valueFormat(v):""}}var secondAxisIdx;if(plot2&&this._allowV1SecondAxis&&(this.compatVersion()<=1)){secondAxisIdx=pvc.parseDistinctIndexArray(options.secondAxisIdx)||-1}return{compatVersion:this.compatVersion(),plot2SeriesIndexes:secondAxisIdx,seriesInRows:options.seriesInRows,crosstabMode:options.crosstabMode,isMultiValued:options.isMultiValued,dataPartDimName:dataPartDimName,dimensionGroups:options.dimensionGroups,dimensions:options.dimensions,readers:options.readers,measuresIndexes:options.measuresIndexes,multiChartIndexes:options.multiChartIndexes,separator:dataSeparator,measuresInColumns:dataMeasuresInColumns,categoriesCount:dataCategoriesCount,measuresIndex:dataOptions.measuresIndex||dataOptions.measuresIdx,measuresCount:dataOptions.measuresCount||dataOptions.numMeasures,isCategoryTimeSeries:options.timeSeries,timeSeriesFormat:options.timeSeriesFormat,valueNumberFormatter:valueFormatter}},_addPlot2SeriesDataPartCalculation:function(complexTypeProj,dataPartDimName){if(this.compatVersion()<=1){return}var options=this.options;var serRole=this._serRole;var plot2Series=(serRole!=null)&&options.plot2&&options.plot2Series&&def.array.as(options.plot2Series);if(!plot2Series||!plot2Series.length){return}var inited=false;var plot2SeriesSet=def.query(plot2Series).uniqueIndex();var dimNames,dataPartDim,part1Atom,part2Atom;complexTypeProj.setCalc({names:dataPartDimName,calculation:function(datum,atoms){if(!inited){if(serRole.isBound()){dimNames=serRole.grouping.dimensionNames();dataPartDim=datum.owner.dimensions(dataPartDimName)}inited=true}if(dataPartDim){var seriesKey=pvc.data.Complex.values(datum,dimNames).join(',');atoms[dataPartDimName]=def.hasOwnProp.call(plot2SeriesSet,seriesKey)?(part2Atom||(part2Atom=dataPartDim.intern("1"))):(part1Atom||(part1Atom=dataPartDim.intern("0")))}}})},_addDefaultDataPartCalculation:function(dataPartDimName){var dataPartDim,part1Atom;this._complexTypeProj.setCalc({names:dataPartDimName,calculation:function(datum,atoms){if(!dataPartDim){dataPartDim=datum.owner.dimensions(dataPartDimName)}atoms[dataPartDimName]=part1Atom||(part1Atom=dataPartDim.intern("0"))}})},partData:function(dataPartValues){if(!this._partData){if(!this._dataPartRole||!this._dataPartRole.grouping){return this._partData=this.data}this._partData=this.data.flattenBy(this._dataPartRole)}if(!dataPartValues||!this._dataPartRole||!this._dataPartRole.grouping){return this._partData}var dataPartDimName=this._dataPartRole.firstDimensionName();if(def.array.is(dataPartValues)){if(dataPartValues.length>1){return this._partData.where([def.set({},dataPartDimName,dataPartValues)])}dataPartValues=dataPartValues[0]}var child=this._partData._childrenByKey[dataPartValues+''];if(!child){var dataPartCell={v:dataPartValues};if(dataPartValues==='trend'){var firstTrendAtom=this._firstTrendAtomProto;if(firstTrendAtom){dataPartCell.f=firstTrendAtom.f}}child=new pvc.data.Data({parent:this._partData,atoms:def.set({},dataPartDimName,dataPartCell),dimNames:[dataPartDimName],datums:[]})}return child},visibleData:function(dataPartValue,keyArgs){var ignoreNulls=def.get(keyArgs,'ignoreNulls',true);if(ignoreNulls&&this.options.ignoreNulls){ignoreNulls=false}keyArgs=keyArgs?Object.create(keyArgs):{};keyArgs.ignoreNulls=ignoreNulls;var key=ignoreNulls+'|'+dataPartValue,data=def.getOwn(this._visibleDataCache,key);if(!data){data=this._createVisibleData(dataPartValue,keyArgs);if(data){(this._visibleDataCache||(this._visibleDataCache={}))[key]=data}}return data},_createVisibleData:function(dataPartValue,keyArgs){var partData=this.partData(dataPartValue);if(!partData){return null}var ignoreNulls=def.get(keyArgs,'ignoreNulls');return this._serRole&&this._serRole.grouping?partData.flattenBy(this._serRole,{visible:true,isNull:ignoreNulls?false:null}):partData},_generateTrends:function(){if(this._dataPartRole){def.query(def.own(this.axes)).selectMany(function(axis){return axis.dataCells}).where(function(dataCell){return!!dataCell.trend}).distinct(function(dataCell){return dataCell.role.name+'|'+(dataCell.dataPartValue||'')}).each(this._generateTrendsDataCell,this)}},_interpolate:function(){def.query(def.own(this.axes)).selectMany(function(axis){return axis.dataCells}).where(function(dataCell){var nim=dataCell.nullInterpolationMode;return!!nim&&nim!=='none'}).distinct(function(dataCell){return dataCell.role.name+'|'+(dataCell.dataPartValue||'')}).each(this._interpolateDataCell,this)},_interpolateDataCell:function(dataCell){},_generateTrendsDataCell:function(dataCell){},setData:function(data,options){this.setResultset(data.resultset);this.setMetadata(data.metadata);$.extend(this.options,options);return this},setResultset:function(resultset){!this.parent||def.fail.operationInvalid("Can only set resultset on root chart.");this.resultset=resultset;if(!resultset.length){this._log("Warning: Resultset is empty")}return this},setMetadata:function(metadata){!this.parent||def.fail.operationInvalid("Can only set resultset on root chart.");this.metadata=metadata;if(!metadata.length){this._log("Warning: Metadata is empty")}return this}});
pvc.BaseChart.add({_initPlots:function(hasMultiRole){this.plotPanelList=null;if(!this.parent){this.plots={};this.plotList=[];this.plotsByType={};this._initPlotsCore(hasMultiRole)}else{var root=this.root;this.plots=root.plots;this.plotList=root.plotList;this.plotsByType=root.plotsByType}},_initPlotsCore:function(){},_addPlot:function(plot){var plotsByType=this.plotsByType;var plots=this.plots;var plotType=plot.type;var plotIndex=plot.index;var plotName=plot.name;var plotId=plot.id;if(plotName&&def.hasOwn(plots,plotName)){throw def.error.operationInvalid("Plot name '{0}' already taken.",[plotName])}if(def.hasOwn(plots,plotId)){throw def.error.operationInvalid("Plot id '{0}' already taken.",[plotId])}var typePlots=def.array.lazy(plotsByType,plotType);if(def.hasOwn(typePlots,plotIndex)){throw def.error.operationInvalid("Plot index '{0}' of type '{1}' already taken.",[plotIndex,plotType])}plot.globalIndex=this.plotList.length;typePlots[plotIndex]=plot;this.plotList.push(plot);plots[plotId]=plot;if(plotName){plots[plotName]=plot}},_collectPlotAxesDataCells:function(plot,dataCellsByAxisTypeThenIndex){var colorRoleName=plot.option('ColorRole');if(colorRoleName){var colorRole=this.visualRoles(colorRoleName);if(colorRole.isBound()){var colorDataCellsByAxisIndex=def.array.lazy(dataCellsByAxisTypeThenIndex,'color');def.array.lazy(colorDataCellsByAxisIndex,plot.option('ColorAxis')-1).push({plot:plot,role:colorRole,dataPartValue:plot.option('DataPart')})}}},_addPlotPanel:function(plotPanel){def.lazy(this,'plotPanels')[plotPanel.plot.id]=plotPanel;def.array.lazy(this,'plotPanelList').push(plotPanel)},_createPlotPanels:function(){throw def.error.notImplemented()}});
pvc.BaseChart.add({colors:null,axes:null,axesList:null,axesByType:null,_axisClassByType:{'color':pvc.visual.ColorAxis,'size':pvc.visual.SizeAxis,'base':pvc.visual.CartesianAxis,'ortho':pvc.visual.CartesianAxis},_axisCreateWhere:{'color':1,'size':2,'base':3,'ortho':3},_axisCreationOrder:['color','size','base','ortho'],_axisCreateIfUnbound:{},_initAxes:function(hasMultiRole){this.axes={};this.axesList=[];this.axesByType={};delete this._rolesColorScale;var dataCellsByAxisTypeThenIndex;if(!this.parent){dataCellsByAxisTypeThenIndex={};this.plotList.forEach(function(plot){this._collectPlotAxesDataCells(plot,dataCellsByAxisTypeThenIndex)},this);this._fixTrendsLabel(dataCellsByAxisTypeThenIndex)}else{dataCellsByAxisTypeThenIndex=this.root._dataCellsByAxisTypeThenIndex}this._dataCellsByAxisTypeThenIndex=dataCellsByAxisTypeThenIndex;var here=0;if(!this.parent){here|=1}if(this.parent||!hasMultiRole){here|=2}this._axisCreateHere=here;this._axisCreationOrder.forEach(function(type){if((this._axisCreateWhere[type]&here)!==0){var AxisClass;var dataCellsByAxisIndex=dataCellsByAxisTypeThenIndex[type];if(dataCellsByAxisIndex){AxisClass=this._axisClassByType[type];if(AxisClass){dataCellsByAxisIndex.forEach(function(dataCells,axisIndex){new AxisClass(this,type,axisIndex)},this)}}else if(this._axisCreateIfUnbound[type]){AxisClass=this._axisClassByType[type];if(AxisClass){new AxisClass(this,type,0)}}}},this);if(this.parent){this.root.axesList.forEach(function(axis){if(!def.hasOwn(this.axes,axis.id)){this._addAxis(axis)}},this)}},_fixTrendsLabel:function(dataCellsByAxisTypeThenIndex){var dataPartDimName=this._getDataPartDimName();if(dataPartDimName){var firstDataCell=def.query(def.ownKeys(dataCellsByAxisTypeThenIndex)).selectMany(function(axisType){return dataCellsByAxisTypeThenIndex[axisType]}).selectMany().first(function(dataCell){return!!dataCell.trend});if(firstDataCell){var trendInfo=pvc.trends.get(firstDataCell.trend.type);var dataPartAtom=trendInfo.dataPartAtom;var trendLabel=firstDataCell.trend.label;if(trendLabel===undefined){trendLabel=dataPartAtom.f}this._firstTrendAtomProto={v:dataPartAtom.v,f:trendLabel}}else{delete this._firstTrendAtomProto}}},_addAxis:function(axis){this.axes[axis.id]=axis;if(axis.chart===this){axis.axisIndex=this.axesList.length}this.axesList.push(axis);var typeAxes=def.array.lazy(this.axesByType,axis.type);var typeIndex=typeAxes.count||0;axis.typeIndex=typeIndex;typeAxes[axis.index]=axis;if(!typeIndex){typeAxes.first=axis}typeAxes.count=typeIndex+1;if(axis.type==='color'&&axis.isBound()){this._onColorAxisScaleSet(axis)}return this},_getAxis:function(type,index){var typeAxes=this.axesByType[type];if(typeAxes&&index!=null&&(+index>=0)){return typeAxes[index]}},_bindAxes:function(){var here=this._axisCreateHere;def.eachOwn(this._dataCellsByAxisTypeThenIndex,function(dataCellsByAxisIndex,type){if((this._axisCreateWhere[type]&here)!==0){dataCellsByAxisIndex.forEach(function(dataCells,index){var axisId=pvc.buildIndexedId(type,index);var axis=this.axes[axisId];if(!axis.isBound()){axis.bind(dataCells)}},this)}},this)},_setAxesScales:function(){if(!this.parent){var colorAxes=this.axesByType.color;if(colorAxes){colorAxes.forEach(function(axis){if(axis.isBound()){axis.calculateScale();this._onColorAxisScaleSet(axis)}},this)}}},_onColorAxisScaleSet:function(axis){switch(axis.index){case 0:this.colors=axis.scheme();break;case 1:if(this._allowV1SecondAxis){this.secondAxisColor=axis.scheme()}break}},_getRoleColorScale:function(roleName){return def.lazy(def.lazy(this,'_rolesColorScale'),roleName,this._createRoleColorScale,this)},_createRoleColorScale:function(roleName){var firstScale,scale;var valueToColorMap={};this.axesByType.color.forEach(function(axis){var axisRole=axis.role;var isRoleCompatible=(axisRole.name===roleName)||(axisRole.sourceRole&&axisRole.sourceRole.name===roleName);if(isRoleCompatible&&axis.scale&&(axis.index===0||axis.option.isSpecified('Colors')||axis.option.isSpecified('Map'))){scale=axis.scale;if(!firstScale){firstScale=scale}axis.domainValues.forEach(addDomainValue)}},this);function addDomainValue(value){var key=''+value;if(!def.hasOwnProp.call(valueToColorMap,key)){valueToColorMap[key]=scale(value)}}if(!firstScale){return pvc.createColorScheme()()}scale=function(value){var key=''+value;if(def.hasOwnProp.call(valueToColorMap,key)){return valueToColorMap[key]}var color=firstScale(value);valueToColorMap[key]=color;return color};def.copy(scale,firstScale);return scale},_onLaidOut:function(){}});
pvc.BaseChart.add({basePanel:null,titlePanel:null,legendPanel:null,_multiChartPanel:null,_initChartPanels:function(hasMultiRole){this._initBasePanel();this._initTitlePanel();var legendPanel=this._initLegendPanel();if(!this.parent&&hasMultiRole){this._initMultiChartPanel();if(legendPanel){this._initLegendScenes(legendPanel)}}else{var options=this.options;if(legendPanel){this._initLegendScenes(legendPanel)}this._preRenderContent({margins:hasMultiRole?options.smallContentMargins:options.contentMargins,paddings:hasMultiRole?options.smallContentPaddings:options.contentPaddings,clickAction:options.clickAction,doubleClickAction:options.doubleClickAction})}},_preRenderContent:function(contentOptions){},_initBasePanel:function(){var options=this.options;var basePanelParent=this.parent&&this.parent._multiChartPanel;this.basePanel=new pvc.BasePanel(this,basePanelParent,{margins:this.margins,paddings:this.paddings,size:{width:this.width,height:this.height}})},_initTitlePanel:function(){var options=this.options;if(!def.empty(options.title)){var isRoot=!this.parent;this.titlePanel=new pvc.TitlePanel(this,this.basePanel,{title:options.title,font:options.titleFont,anchor:options.titlePosition,align:options.titleAlign,alignTo:options.titleAlignTo,offset:options.titleOffset,keepInBounds:options.titleKeepInBounds,margins:options.titleMargins,paddings:options.titlePaddings,titleSize:options.titleSize,titleSizeMax:options.titleSizeMax})}},_initLegendPanel:function(){var options=this.options;if(options.legend){var legend=new pvc.visual.Legend(this,'legend',0);this.legendPanel=new pvc.LegendPanel(this,this.basePanel,{anchor:legend.option('Position'),align:legend.option('Align'),alignTo:options.legendAlignTo,offset:options.legendOffset,keepInBounds:options.legendKeepInBounds,size:legend.option('Size'),sizeMax:legend.option('SizeMax'),margins:legend.option('Margins'),paddings:legend.option('Paddings'),font:legend.option('Font'),scenes:def.getPath(options,'legend.scenes'),textMargin:options.legendTextMargin,itemPadding:options.legendItemPadding,markerSize:options.legendMarkerSize});return this.legendPanel}},_getLegendBulletRootScene:function(){return this.legendPanel&&this.legendPanel._getBulletRootScene()},_initMultiChartPanel:function(){var basePanel=this.basePanel;var options=this.options;this._multiChartPanel=new pvc.MultiChartPanel(this,basePanel,{margins:options.contentMargins,paddings:options.contentPaddings});this._multiChartPanel.createSmallCharts();basePanel._children.unshift(basePanel._children.pop())},_coordinateSmallChartsLayout:function(scopesByType){},_initLegendScenes:function(legendPanel){var rootScene,dataPartDimName;var legendIndex=0;var colorAxes=this.axesByType.color;if(colorAxes){colorAxes.forEach(processAxis,this)}function processAxis(colorAxis){if(colorAxis.option('LegendVisible')){var dataCells=colorAxis&&colorAxis.dataCells;if(dataCells){dataCells.forEach(function(dataCell){if(dataCell.role.isDiscrete()){var domainData=dataCell.data;if(!rootScene){dataPartDimName=this._getDataPartDimName();rootScene=legendPanel._getBulletRootScene()}var dataPartAtom;var locked=colorAxis.option('LegendClickMode')==='toggleVisible'&&(dataPartAtom=domainData.atoms[dataPartDimName])&&dataPartAtom.value==='trend';var groupScene=rootScene.createGroup({group:domainData,colorAxis:colorAxis,clickMode:locked?'none':undefined,extensionPrefix:pvc.buildIndexedId('',legendIndex++)});dataCell.legendBulletGroupScene=groupScene;var partColorScale=colorAxis.scale;domainData.children().each(function(itemData){var itemScene=groupScene.createItem({group:itemData});itemScene.color=partColorScale(itemData.value)})}},this)}}}}});
pvc.BaseChart.add({_updateSelectionSuspendCount:0,_lastSelectedDatums:null,clearSelections:function(){if(this.data.owner.clearSelected()){this.updateSelections()}return this},_updatingSelections:function(method,context){this._suspendSelectionUpdate();try{method.call(context||this)}finally{this._resumeSelectionUpdate()}},_suspendSelectionUpdate:function(){if(this===this.root){this._updateSelectionSuspendCount++}else{this.root._suspendSelectionUpdate()}},_resumeSelectionUpdate:function(){if(this===this.root){if(this._updateSelectionSuspendCount>0){if(!(--this._updateSelectionSuspendCount)){this.updateSelections()}}}else{this.root._resumeSelectionUpdate()}},updateSelections:function(keyArgs){if(this===this.root){if(this._inUpdateSelections){return this}if(this._updateSelectionSuspendCount){return this}var selectedChangedDatumMap=this._calcSelectedChangedDatums();if(!selectedChangedDatumMap){return}pvc.removeTipsyLegends();this._inUpdateSelections=true;try{var action=this.options.selectionChangedAction;if(action){var selectedDatums=this.data.selectedDatums();var selectedChangedDatums=selectedChangedDatumMap.values();action.call(this.basePanel._getContext(),selectedDatums,selectedChangedDatums)}if(def.get(keyArgs,'render',true)){this.useTextMeasureCache(function(){this.basePanel.renderInteractive()},this)}}finally{this._inUpdateSelections=false}}else{this.root.updateSelections()}return this},_calcSelectedChangedDatums:function(){var selectedChangedDatums;var nowSelectedDatums=this.data.selectedDatumMap();var lastSelectedDatums=this._lastSelectedDatums;if(!lastSelectedDatums){if(!nowSelectedDatums.count){return}selectedChangedDatums=nowSelectedDatums.clone()}else{selectedChangedDatums=lastSelectedDatums.symmetricDifference(nowSelectedDatums);if(!selectedChangedDatums.count){return}}this._lastSelectedDatums=nowSelectedDatums;var datums=this._lastSelectedDatums?this._lastSelectedDatums.values():[];return selectedChangedDatums},_onUserSelection:function(datums){if(!datums||!datums.length){return datums}if(this===this.root){var action=this.options.userSelectionAction;if(action){return action.call(null,datums)||datums}return datums}return this.root._onUserSelection(datums)},_isSelectable:function(){return this.options.selectable},_canSelectWithRubberband:function(){var options=this.options;return options.selectable&&options.selectionMode==='rubberband'},_canSelectWithClick:function(){return this._canSelectWithRubberband()},_canSelectWithFocusWindow:function(){var options=this.options;return options.selectable&&options.selectionMode==='focuswindow'}});
pvc.BaseChart.add({_processExtensionPoints:function(){var components;if(!this.parent){var points=this.options.extensionPoints;components={};if(points){for(var p in points){var id,prop;var splitIndex=p.indexOf("_");if(splitIndex>0){id=p.substring(0,splitIndex);prop=p.substr(splitIndex+1);if(id&&prop){var component=def.getOwn(components,id)||(components[id]=new def.OrderedMap());component.add(prop,points[p])}}}}}else{components=this.parent._components}this._components=components},extend:function(mark,ids,keyArgs){if(def.array.is(ids)){ids.forEach(function(id){this._extendCore(mark,id,keyArgs)},this)}else{this._extendCore(mark,ids,keyArgs)}},_extendCore:function(mark,id,keyArgs){if(mark){var component=def.getOwn(this._components,id);if(component){if(mark.borderPanel){mark=mark.borderPanel}var logOut=pvc.debug>=3?[]:null;var constOnly=def.get(keyArgs,'constOnly',false);var wrap=mark.wrap;var keyArgs2={tag:pvc.extensionTag};var isRealMark=mark instanceof pv.Mark;component.forEach(function(v,m){if(mark.isLocked&&mark.isLocked(m)){if(logOut){logOut.push(m+": locked extension point!")}}else if(mark.isIntercepted&&mark.isIntercepted(m)){if(logOut){logOut.push(m+":"+pvc.stringify(v)+" (controlled)")}}else{if(logOut){logOut.push(m+": "+pvc.stringify(v))}if(v!=null){var type=typeof v;if(type==='object'){if(m==='svg'||m==='css'){var v2=mark.propertyValue(m);if(v2){v=def.copy(v2,v)}}}else if(isRealMark&&(wrap||constOnly)&&type==='function'){if(constOnly){return}if(m!=='add'){v=wrap.call(mark,v,m)}}}if(typeof mark[m]==="function"){if(m!='add'&&mark.intercept){mark.intercept(m,v,keyArgs2)}else{mark[m](v)}}else{mark[m]=v}}});if(logOut){if(logOut.length){this._log("Applying Extension Points for: '"+id+"'\n\t* "+logOut.join("\n\t* "))}else if(pvc.debug>=5){this._log("No Extension Points for: '"+id+"'")}}}}else if(pvc.debug>=4){this._log("Applying Extension Points for: '"+id+"' (target mark does not exist)")}},_getExtension:function(id,prop){var component;if(!def.array.is(id)){component=def.getOwn(this._components,id);if(component){return component.get(prop)}}else{var i=id.length-1,value;while(i>=0){component=def.getOwn(this._components,id[i--]);if(component&&(value=component.get(prop))!==undefined){return value}}}},_getConstantExtension:function(id,prop){var value=this._getExtension(id,prop);if(!def.fun.is(value)){return value}}});
def.type('pvc.BasePanel',pvc.Abstract).init(function(chart,parent,options){this.chart=chart;this.base();this.axes={};if(options){if(options.scenes){this._sceneTypeExtensions=options.scenes;delete options.scenes}var axes=options.axes;if(axes){def.copy(this.axes,axes);delete options.axes}}$.extend(this,options);this.chart=chart;if(!this.axes.color){this.axes.color=chart.axes.color}this.position={};var margins=options&&options.margins;if(!parent&&margins===undefined){margins=3}this.margins=new pvc.Sides(margins);this.paddings=new pvc.Sides(options&&options.paddings);this.size=new pvc.Size(options&&options.size);this.sizeMax=new pvc.Size(options&&options.sizeMax);if(!parent){this.parent=null;this.root=this;this.topRoot=this;this.isRoot=true;this.isTopRoot=true;this.data=this.chart.data}else{this.parent=parent;this.isTopRoot=false;this.isRoot=(parent.chart!==chart);this.root=this.isRoot?this:parent.root;this.topRoot=parent.topRoot;this.data=parent.data;if(this.isRoot){this.position.left=chart.left;this.position.top=chart.top}parent._addChild(this)}if(this.isRoot){this.anchor=null;this.align=null;this.alignTo=null;this.offset=null}else{this.align=pvc.parseAlign(this.anchor,this.align);var alignTo=this.alignTo;var side=this.anchor;if(alignTo!=null&&alignTo!==''&&(side==='left'||side==='right')){if(alignTo!=='page-middle'){if(!isNaN(+alignTo.charAt(0))){alignTo=pvc.PercentValue.parse(alignTo)}else{alignTo=pvc.parseAlign(side,alignTo)}}}else{alignTo=this.align}this.alignTo=alignTo;this.offset=new pvc.Offset(this.offset)}if(this.borderWidth==null){var borderWidth;var extensionId=this._getExtensionId();if(extensionId){var strokeStyle=this._getExtension(extensionId,'strokeStyle');if(strokeStyle!=null){borderWidth=+this._getConstantExtension(extensionId,'lineWidth');if(isNaN(borderWidth)||!isFinite(borderWidth)){borderWidth=null}}}this.borderWidth=borderWidth==null?0:1.5}}).add({chart:null,parent:null,_children:null,type:pv.Panel,_extensionPrefix:'',height:null,width:null,borderWidth:null,anchor:"top",pvPanel:null,margins:null,paddings:null,isRoot:false,isTopRoot:false,root:null,topRoot:null,_layoutInfo:null,_signs:null,data:null,dataPartValue:null,_isAnimating:0,_isRubberBandSelecting:false,_ignoreClicks:0,_v1DimRoleName:{'series':'series','category':'category','value':'value'},_sceneTypeExtensions:null,clickAction:null,doubleClickAction:null,compatVersion:function(options){return this.chart.compatVersion(options)},_createLogInstanceId:function(){return""+this.constructor+this.chart._createLogChildSuffix()},defaultVisibleBulletGroupScene:function(){var colorAxis=this.axes.color;if(colorAxis&&colorAxis.option('LegendVisible')){var dataPartValue=this.dataPartValue;return def.query(colorAxis.dataCells).where(function(dataCell){return dataCell.dataPartValue===dataPartValue}).select(function(dataCell){return dataCell.legendBulletGroupScene}).first(def.truthy)}return null},_getLegendBulletRootScene:function(){return this.chart._getLegendBulletRootScene()},_addChild:function(child){child.parent===this||def.assert("Child has a != parent.");(this._children||(this._children=[])).push(child)},_addSign:function(sign){(this._signs||(this._signs=[])).push(sign)},visibleData:function(){return this.chart.visibleData(this.dataPartValue)},layout:function(availableSize,keyArgs){if(!this._layoutInfo||def.get(keyArgs,'force',false)){var referenceSize=def.get(keyArgs,'referenceSize');if(!referenceSize&&availableSize){referenceSize=def.copyOwn(availableSize)}var desiredSize=this.size.resolve(referenceSize);var sizeMax=this.sizeMax.resolve(referenceSize);if(!availableSize){if(desiredSize.width==null||desiredSize.height==null){throw def.error.operationInvalid("Panel layout without width or height set.")}availableSize=def.copyOwn(desiredSize)}if(!referenceSize&&availableSize){referenceSize=def.copyOwn(availableSize)}if(sizeMax.width!=null&&availableSize.width>sizeMax.width){availableSize.width=sizeMax.width}if(sizeMax.height!=null&&availableSize.height>sizeMax.height){availableSize.height=sizeMax.height}var halfBorder=this.borderWidth/2;var realMargins=(def.get(keyArgs,'margins')||this.margins).resolve(referenceSize);var realPaddings=(def.get(keyArgs,'paddings')||this.paddings).resolve(referenceSize);var margins=pvc.Sides.inflate(realMargins,halfBorder);var paddings=pvc.Sides.inflate(realPaddings,halfBorder);var spaceWidth=margins.width+paddings.width;var spaceHeight=margins.height+paddings.height;var availableClientSize=new pvc.Size(Math.max(availableSize.width-spaceWidth,0),Math.max(availableSize.height-spaceHeight,0));var desiredClientSize=def.copyOwn(desiredSize);if(desiredClientSize.width!=null){desiredClientSize.width=Math.max(desiredClientSize.width-spaceWidth,0)}if(desiredClientSize.height!=null){desiredClientSize.height=Math.max(desiredClientSize.height-spaceHeight,0)}var prevLayoutInfo=this._layoutInfo||null;var canChange=def.get(keyArgs,'canChange',true);var layoutInfo=this._layoutInfo={canChange:canChange,referenceSize:referenceSize,realMargins:realMargins,realPaddings:realPaddings,borderWidth:this.borderWidth,margins:margins,paddings:paddings,desiredClientSize:desiredClientSize,clientSize:availableClientSize,pageClientSize:prevLayoutInfo?prevLayoutInfo.pageClientSize:availableClientSize.clone(),previous:prevLayoutInfo};if(prevLayoutInfo){delete prevLayoutInfo.previous;delete prevLayoutInfo.pageClientSize}var clientSize=this._calcLayout(layoutInfo);var size;if(!clientSize){size=availableSize;clientSize=availableClientSize}else{layoutInfo.clientSize=clientSize;size={width:clientSize.width+spaceWidth,height:clientSize.height+spaceHeight}}this.isVisible=(clientSize.width>0&&clientSize.height>0);delete layoutInfo.desiredClientSize;this.width=size.width;this.height=size.height;if(!canChange&&prevLayoutInfo){delete layoutInfo.previous}if(pvc.debug>=5){this._log("Size       = "+pvc.stringify(size));this._log("Margins    = "+pvc.stringify(layoutInfo.margins));this._log("Paddings   = "+pvc.stringify(layoutInfo.paddings));this._log("ClientSize = "+pvc.stringify(layoutInfo.clientSize))}this._onLaidOut()}},_onLaidOut:function(){if(this.isRoot){this.chart._onLaidOut()}},_calcLayout:function(layoutInfo){var clientSize;var me=this;var margins,remSize,useLog;if(me._children){var aolMap=pvc.BasePanel.orthogonalLength;var aoMap=pvc.BasePanel.relativeAnchor;var altMap=pvc.BasePanel.leftTopAnchor;var aofMap=pvc.Offset.namesSidesToOffset;var fillChildren=[];var sideChildren=[];me._children.forEach(function(child){var a=child.anchor;if(a){if(a==='fill'){fillChildren.push(child)}else{def.hasOwn(aoMap,a)||def.fail.operationInvalid("Unknown anchor value '{0}'",[a]);sideChildren.push(child)}}});useLog=pvc.debug>=5;clientSize=def.copyOwn(layoutInfo.clientSize);var childKeyArgs={force:true,referenceSize:clientSize};if(useLog){me._group("CCC DOCK LAYOUT clientSize = "+pvc.stringify(clientSize))}try{doMaxTimes(5,layoutCycle,me)}finally{if(useLog){me._groupEnd()}}}return clientSize;function doMaxTimes(maxTimes,fun,ctx){var index=0;while(maxTimes--){if(fun.call(ctx,maxTimes,index)===false){return true}index++}return false}function layoutCycle(remTimes,iteration){if(useLog){me._group("LayoutCycle #"+(iteration+1)+" (remaining: "+remTimes+")")}try{var canResize=(remTimes>0);margins=new pvc.Sides(0);remSize=def.copyOwn(clientSize);var child;var index=0;var count=sideChildren.length;while(index<count){child=sideChildren[index];if(useLog){me._group("SIDE Child #"+(index+1)+" at "+child.anchor)}try{if(layoutChild.call(this,child,canResize)){return true}}finally{if(useLog){me._groupEnd()}}index++}index=0;count=fillChildren.length;while(index<count){child=fillChildren[index];if(useLog){me._group("FILL Child #"+(index+1))}try{if(layoutChild.call(this,child,canResize)){return true}}finally{if(useLog){me._groupEnd()}}index++}return false}finally{if(useLog){me._groupEnd()}}}function layoutChild(child,canResize){var resized=false;var paddings;childKeyArgs.canChange=canResize;doMaxTimes(3,function(remTimes,iteration){if(useLog){me._group("Attempt #"+(iteration+1))}try{childKeyArgs.paddings=paddings;childKeyArgs.canChange=remTimes>0;child.layout(new pvc.Size(remSize),childKeyArgs);if(child.isVisible){resized=checkChildResize.call(this,child,canResize);if(resized){return false}var requestPaddings=child._layoutInfo.requestPaddings;if(checkPaddingsChanged(paddings,requestPaddings)){paddings=requestPaddings;if(remTimes>0){paddings=new pvc.Sides(paddings);if(useLog){this._log("Child requested paddings change: "+pvc.stringify(paddings))}return true}if(pvc.debug>=2){this._warn("Child requests paddings change but iterations limit has been reached.")}}positionChild.call(this,child);if(child.anchor!=='fill'){updateSide.call(this,child)}}return false}finally{if(useLog){me._groupEnd()}}},this);return resized}function checkPaddingsChanged(paddings,newPaddings){if(!newPaddings){return false}return def.query(pvc.Sides.names).each(function(side){var curPad=(paddings&&paddings[side])||0;var newPad=(newPaddings&&newPaddings[side])||0;if(Math.abs(newPad-curPad)>=0.1){return false}})}function checkChildResize(child,canResize){var resized=false;var addWidth=child.width-remSize.width;if(addWidth>0){if(pvc.debug>=3){this._log("Child added width = "+addWidth)}if(!canResize){if(pvc.debug>=2){this._warn("Child wanted more width, but layout iterations limit has been reached.")}}else{resized=true;remSize.width+=addWidth;clientSize.width+=addWidth}}var addHeight=child.height-remSize.height;if(addHeight>0){if(pvc.debug>=3){this._log("Child added height ="+addHeight)}if(!canResize){if(pvc.debug>=2){this._warn("Child wanted more height, but layout iterations limit has been reached.")}}else{resized=true;remSize.height+=addHeight;clientSize.height+=addHeight}}return resized}function positionChild(child){var side=child.anchor;var align=child.align;var alignTo=child.alignTo;var sidePos;if(side==='fill'){side='left';sidePos=margins.left+remSize.width/2-(child.width/2);align=alignTo='middle'}else{sidePos=margins[side]}var sideo,sideOPosChildOffset;switch(align){case'top':case'bottom':case'left':case'right':sideo=align;sideOPosChildOffset=0;break;case'center':case'middle':sideo=altMap[aoMap[side]];sideOPosChildOffset=-child[aolMap[sideo]]/2;break}var sideOPosParentOffset;var sideOTo;switch(alignTo){case'top':case'bottom':case'left':case'right':sideOTo=alignTo;sideOPosParentOffset=(sideOTo!==sideo)?remSize[aolMap[sideo]]:0;break;case'center':case'middle':sideOTo=altMap[aoMap[side]];sideOPosParentOffset=remSize[aolMap[sideo]]/2;break;case'page-center':case'page-middle':sideOTo=altMap[aoMap[side]];var lenProp=aolMap[sideo];var pageLen=Math.min(remSize[lenProp],layoutInfo.pageClientSize[lenProp]);sideOPosParentOffset=pageLen/2;break}var sideOPos=margins[sideOTo]+sideOPosParentOffset+sideOPosChildOffset;var resolvedOffset=child.offset.resolve(remSize);if(resolvedOffset){sidePos+=resolvedOffset[aofMap[side]]||0;sideOPos+=resolvedOffset[aofMap[sideo]]||0}if(child.keepInBounds){if(sidePos<0){sidePos=0}if(sideOPos<0){sideOPos=0}}child.setPosition(def.set({},side,sidePos,sideo,sideOPos))}function updateSide(child){var side=child.anchor;var sideol=aolMap[side];var olen=child[sideol];margins[side]+=olen;remSize[sideol]-=olen}},invalidateLayout:function(){this._layoutInfo=null;if(this._children){this._children.forEach(function(child){child.invalidateLayout()})}},_create:function(force){if(!this.pvPanel||force){this.pvPanel=null;delete this._signs;this.layout();if(!this.isVisible){return}if(this.isRoot){this._creating()}var margins=this._layoutInfo.margins;var paddings=this._layoutInfo.paddings;if(this.isTopRoot){this.pvRootPanel=this.pvPanel=new pv.Panel().canvas(this.chart.options.canvas);if(margins.width>0||margins.height>0){this.pvPanel.width(this.width).height(this.height);this.pvPanel=this.pvPanel.add(pv.Panel)}}else{this.pvPanel=this.parent.pvPanel.add(this.type)}var pvBorderPanel=this.pvPanel;var width=this.width-margins.width;var height=this.height-margins.height;pvBorderPanel.width(width).height(height);if(pvc.debug>=15&&(margins.width>0||margins.height>0)){(this.isTopRoot?this.pvRootPanel:this.parent.pvPanel).add(this.type).width(this.width).height(this.height).left(this.position.left!=null?this.position.left:null).right(this.position.right!=null?this.position.right:null).top(this.position.top!=null?this.position.top:null).bottom(this.position.bottom!=null?this.position.bottom:null).strokeStyle('orange').lineWidth(1).strokeDasharray('- .')}var hasPositions={};def.eachOwn(this.position,function(v,side){pvBorderPanel[side](v+margins[side]);hasPositions[this.anchorLength(side)]=true},this);if(!hasPositions.width){if(margins.left>0){pvBorderPanel.left(margins.left)}if(margins.right>0){pvBorderPanel.right(margins.right)}}if(!hasPositions.height){if(margins.top>0){pvBorderPanel.top(margins.top)}if(margins.bottom>0){pvBorderPanel.bottom(margins.bottom)}}if(paddings.width>0||paddings.height>0){this.pvPanel=pvBorderPanel.add(pv.Panel).width(width-paddings.width).height(height-paddings.height).left(paddings.left).top(paddings.top)}pvBorderPanel.borderPanel=pvBorderPanel;pvBorderPanel.paddingPanel=this.pvPanel;this.pvPanel.paddingPanel=this.pvPanel;this.pvPanel.borderPanel=pvBorderPanel;if(pvc.debug>=15){this.pvPanel.strokeStyle('lightgreen').lineWidth(1).strokeDasharray('- ');if(this.pvPanel!==pvBorderPanel){pvBorderPanel.strokeStyle('blue').lineWidth(1).strokeDasharray('. ')}}var extensionId=this._getExtensionId();new pvc.visual.Panel(this,null,{panel:pvBorderPanel,extensionId:extensionId});this._createCore(this._layoutInfo);if(this.isTopRoot&&pv.renderer()!=='batik'&&this.chart._canSelectWithRubberband()){this._initRubberBand()}this.applyExtensions()}},_creating:function(){if(this._children){this._children.forEach(function(child){child._creating()})}},_createCore:function(){if(this._children){this._children.forEach(function(child){child._create()})}},render:function(keyArgs){if(!this.isTopRoot){return this.topRoot.render(keyArgs)}this._create(def.get(keyArgs,'recreate',false));if(!this.isVisible){return}this._onRender();var options=this.chart.options;var pvPanel=this.pvRootPanel;var animate=this.chart._animatable&&options.animate;this._isAnimating=animate&&!def.get(keyArgs,'bypassAnimation',false)?1:0;try{pvPanel.render();if(this._isAnimating){this._isAnimating=2;var me=this;pvPanel.transition().duration(2000).ease("cubic-in-out").start(function(){me._isAnimating=0;me._onRenderEnd(true)})}else{this._onRenderEnd(false)}}finally{this._isAnimating=0}},_onRender:function(){var renderCallback=this.chart.options.renderCallback;if(renderCallback){if(this.compatVersion()<=1){renderCallback.call(this.chart)}else{var context=this._getContext();renderCallback.call(context,context.scene)}}},_onRenderEnd:function(animated){if(this._children){this._children.forEach(function(child){child._onRenderEnd(animated)})}},renderInteractive:function(){if(this.isVisible){var pvMarks=this._getSelectableMarks();if(pvMarks&&pvMarks.length){pvMarks.forEach(function(pvMark){pvMark.render()})}else if(!this._children){this.pvPanel.render();return}if(this._children){this._children.forEach(function(child){child.renderInteractive()})}}},_getSelectableMarks:function(){return null},animate:function(start,end){return(this.topRoot._isAnimating===1)?start:end},isAnimatingStart:function(){return(this.topRoot._isAnimating===1)},isAnimating:function(){return(this.topRoot._isAnimating>0)},setPosition:function(position){for(var side in position){if(def.hasOwn(pvc.Sides.namesSet,side)){var s=position[side];if(s===null){delete this.position[side]}else{s=+s;if(!isNaN(s)&&isFinite(s)){this.position[side]=s}}}}},createAnchoredSize:function(anchorLength,size){if(this.isAnchorTopOrBottom()){return new pvc.Size(size.width,Math.min(size.height,anchorLength))}return new pvc.Size(Math.min(size.width,anchorLength),size.height)},applyExtensions:function(){if(this._signs){this._signs.forEach(function(sign){sign.applyExtensions()})}},extend:function(mark,id,keyArgs){this.chart.extend(mark,this._makeExtensionAbsId(id),keyArgs)},extendAbs:function(mark,absId,keyArgs){this.chart.extend(mark,absId,keyArgs)},_extendSceneType:function(typeKey,type,names){var typeExts=def.get(this._sceneTypeExtensions,typeKey);if(typeExts){pvc.extendType(type,typeExts,names)}},_absBaseExtId:{abs:'base'},_absSmallBaseExtId:{abs:'smallBase'},_getExtensionId:function(){if(this.isRoot){return!this.chart.parent?this._absBaseExtId:this._absSmallBaseExtId}},_getExtensionPrefix:function(){return this._extensionPrefix},_makeExtensionAbsId:function(id){return pvc.makeExtensionAbsId(id,this._getExtensionPrefix())},_getExtension:function(id,prop){return this.chart._getExtension(this._makeExtensionAbsId(id),prop)},_getExtensionAbs:function(absId,prop){return this.chart._getExtension(absId,prop)},_getConstantExtension:function(id,prop){return this.chart._getConstantExtension(this._makeExtensionAbsId(id),prop)},getPvPanel:function(layer){var mainPvPanel=this.pvPanel;if(!layer){return mainPvPanel}if(!this.parent){throw def.error.operationInvalid("Layers are not possible in a root panel.")}if(!mainPvPanel){throw def.error.operationInvalid("Cannot access layer panels without having created the main panel.")}var pvPanel=null;if(!this._layers){this._layers={}}else{pvPanel=this._layers[layer]}if(!pvPanel){var pvParentPanel=this.parent.pvPanel;pvPanel=pvParentPanel.borderPanel.add(this.type).extend(mainPvPanel.borderPanel);var pvBorderPanel=pvPanel;if(mainPvPanel!==mainPvPanel.borderPanel){pvPanel=pvBorderPanel.add(pv.Panel).extend(mainPvPanel)}pvBorderPanel.borderPanel=pvBorderPanel;pvBorderPanel.paddingPanel=pvPanel;pvPanel.paddingPanel=pvPanel;pvPanel.borderPanel=pvBorderPanel;this.initLayerPanel(pvPanel,layer);this._layers[layer]=pvPanel}return pvPanel},initLayerPanel:function(){},_getV1DimName:function(v1Dim){var dimNames=this._v1DimName||(this._v1DimNameCache={});var dimName=dimNames[v1Dim];if(dimName==null){var role=this.chart.visualRoles(this._v1DimRoleName[v1Dim],{assertExists:false});dimName=role?role.firstDimensionName():'';dimNames[v1Dim]=dimName}return dimName},_getV1Datum:function(scene){return scene.datum},_createContext:function(mark,ev){return new pvc.visual.Context(this,mark,ev)},_getContext:function(mark,ev){var context=this._context;if(!context||context.isPinned){this._context=this._createContext(mark,ev)}else{visualContext_update.call(context,mark,ev)}return this._context},_isTooltipEnabled:function(){return!this.isRubberBandSelecting()&&!this.isAnimating()},_ensurePropEvents:function(pvMark){var events=pvMark.propertyValue('events',true);if(!events||events==='none'){pvMark.events('all')}},_addPropHoverable:function(pvMark){var panel=this;var onEvent;var offEvent;onEvent='mouseover';offEvent='mouseout';pvMark.event(onEvent,function(scene){if(!panel.isRubberBandSelecting()&&!panel.isAnimating()){scene.setActive(true);panel.renderInteractive()}}).event(offEvent,function(scene){if(!panel.isRubberBandSelecting()&&!panel.isAnimating()){if(scene.clearActive()){panel.renderInteractive()}}});this._ensurePropEvents(pvMark)},_addPropTooltip:function(pvMark,keyArgs){var chartTipOptions=this.chart._tooltipOptions;var tipOptions;var nowTipOptions=def.get(keyArgs,'options');if(nowTipOptions){tipOptions=def.create(chartTipOptions,nowTipOptions)}else{tipOptions=Object.create(chartTipOptions)}var buildTooltip=def.get(keyArgs,'buildTooltip')||this._getTooltipBuilder(tipOptions);if(!buildTooltip){return}tipOptions.isEnabled=this._isTooltipEnabled.bind(this);var tipsyEvent=def.get(keyArgs,'tipsyEvent');if(!tipsyEvent){tipsyEvent='mouseover'}var isLazy=def.get(keyArgs,'isLazy',true);pvMark.localProperty("tooltip").tooltip(this._createTooltipProp(pvMark,buildTooltip,isLazy)).title(function(){return''}).event(tipsyEvent,pv.Behavior.tipsy(tipOptions));this._ensurePropEvents(pvMark)},_getTooltipBuilder:function(tipOptions){var options=this.chart.options;var isV1Compat=this.compatVersion()<=1;var tooltipFormat=tipOptions.format;if(!tooltipFormat){if(!isV1Compat){return this._buildDataTooltip}tooltipFormat=options.v1StyleTooltipFormat;if(!tooltipFormat){return}}if(isV1Compat){return function(context){return tooltipFormat.call(context.panel,context.getV1Series(),context.getV1Category(),context.getV1Value()||'',context.getV1Datum())}}return function(context){return tooltipFormat.call(context,context.scene)}},_createTooltipProp:function(pvMark,buildTooltip,isLazy){var myself=this;if(!isLazy){return function(){var context=myself._getContext(pvMark,null);if(context.scene.isIntermediate){return null}return buildTooltip.call(myself,context)}}return function(){var context=myself._getContext(pvMark,null);if(context.scene.isIntermediate){return null}context.pin();var tooltip;return function(){if(tooltip==null){tooltip=buildTooltip.call(myself,context);context=null}return tooltip}}},_requirePointEvent:function(radius){if(!this.isTopRoot){return this.topRoot._requirePointEvent(radius)}if(!this._attachedPointEvent){this.pvPanel.events('all').event("mousemove",pv.Behavior.point(radius||20));this._attachedPointEvent=true}},_buildDataTooltip:function(context){var scene=context.scene;if(!scene.datum){return""}var group=scene.group;var isMultiDatumGroup=group&&group.count()>1;var firstDatum=scene.datum;if(!isMultiDatumGroup&&(!firstDatum||firstDatum.isNull)){return""}var data=this.data;var visibleKeyArgs={visible:true};var tooltip=[];if(firstDatum.isInterpolated){tooltip.push('<i>Interpolation</i>: '+def.html.escape(firstDatum.interpolation)+'<br/>')}else if(firstDatum.isTrend){tooltip.push('<i>Trend</i>: '+def.html.escape(firstDatum.trendType)+'<br/>')}var complexType=data.type;var playingPercentMap=context.panel.stacked===false?null:complexType.getPlayingPercentVisualRoleDimensionMap();var percentValueFormat=playingPercentMap?this.chart.options.percentValueFormat:null;var commonAtoms=isMultiDatumGroup?group.atoms:scene.datum.atoms;var commonAtomsKeys=complexType.sortDimensionNames(def.keys(commonAtoms));function addDim(escapedDimLabel,label){tooltip.push('<b>'+escapedDimLabel+"</b>: "+(def.html.escape(label)||" - ")+'<br/>')}function calcPercent(atom,dimName){var pct;if(group){pct=group.dimensions(dimName).percentOverParent(visibleKeyArgs)}else{pct=data.dimensions(dimName).percent(atom.value)}return percentValueFormat(pct)}var anyCommonAtom=false;commonAtomsKeys.forEach(function(dimName){var atom=commonAtoms[dimName];var dimType=atom.dimension.type;if(!dimType.isHidden){if(!isMultiDatumGroup||atom.value!=null){anyCommonAtom=true;var valueLabel=atom.label;if(playingPercentMap&&playingPercentMap.has(dimName)){valueLabel+=" ("+calcPercent(atom,dimName)+")"}addDim(def.html.escape(atom.dimension.type.label),valueLabel)}}},this);if(isMultiDatumGroup){if(anyCommonAtom){tooltip.push('<hr />')}tooltip.push("<b>#</b>: "+group._datums.length+'<br/>');complexType.sortDimensionNames(group.freeDimensionNames()).forEach(function(dimName){var dim=group.dimensions(dimName);if(!dim.type.isHidden){var dimLabel=def.html.escape(dim.type.label),valueLabel;if(dim.type.valueType===Number){valueLabel=dim.format(dim.sum(visibleKeyArgs));if(playingPercentMap&&playingPercentMap.has(dimName)){valueLabel+=" ("+calcPercent(null,dimName)+")"}dimLabel="&sum; "+dimLabel}else{valueLabel=dim.atoms(visibleKeyArgs).map(function(atom){return atom.label||"- "}).join(", ")}addDim(dimLabel,valueLabel)}})}return'<div style="text-align: left;">'+tooltip.join('\n')+'</div>'},_addPropClick:function(pvMark){var myself=this;function onClick(){var ev=arguments[arguments.length-1];return myself._handleClick(this,ev)}pvMark.cursor("pointer").event("click",onClick);this._ensurePropEvents(pvMark)},_addPropDoubleClick:function(pvMark){var myself=this;function onDoubleClick(){var ev=arguments[arguments.length-1];return myself._handleDoubleClick(this,ev)}pvMark.cursor("pointer").event("dblclick",onDoubleClick);this._ensurePropEvents(pvMark)},_isDoubleClickable:function(keyArgs){var options=keyArgs||this.chart.options;return options.clickable&&!!this.doubleClickAction},_handleDoubleClick:function(pvMark,ev){if(!this._isDoubleClickable()){return}this._ignoreClicks=2;var sign=pvMark.sign;if(!sign||sign.isDoubleClickable()){var context=this._getContext(pvMark,ev);this._onDoubleClick(context)}},_onDoubleClick:function(context){var handler=this.doubleClickAction;if(handler){if(this.compatVersion()<=1){this._onV1DoubleClick(context,handler)}else{handler.call(context,context.scene)}}},_onV1DoubleClick:function(context,handler){handler.call(context.pvMark,context.getV1Series(),context.getV1Category(),context.getV1Value(),context.event,context.getV1Datum())},_isClickable:function(){return this.chart.options.clickable&&!!this.clickAction},_shouldHandleClick:function(){return this.chart._canSelectWithClick()||this._isClickable()},_handleClick:function(pvMark,ev){if(!this._shouldHandleClick()){return}var options=this.chart.options,context;if(!this.doubleClickAction){context=this._getContext(pvMark,ev);this._handleClickCore(context)}else{var myself=this;context=this._createContext(pvMark,ev);window.setTimeout(function(){myself._handleClickCore.call(myself,context)},options.doubleClickMaxDelay||300)}},_handleClickCore:function(context){if(this._ignoreClicks){this._ignoreClicks--}else{var sign=context.sign;if(!sign||sign.isClickable()){this._onClick(context)}if((sign&&sign.isSelectable())||(!sign&&this.chart.options.selectable&&context.scene.datum)){this._onSelect(context)}}},_onClick:function(context){var handler=this.clickAction;if(handler){if(this.compatVersion()<=1){this._onV1Click(context,handler)}else{handler.call(context,context.scene)}}},_onV1Click:function(context,handler){handler.call(context.pvMark,context.getV1Series(),context.getV1Category(),context.getV1Value(),context.event,context.getV1Datum())},_onSelect:function(context){var datums=context.scene.datums().array();if(datums.length){var chart=this.chart;chart._updatingSelections(function(){datums=chart._onUserSelection(datums);if(datums&&datums.length){if(chart.options.ctrlSelectMode&&!context.event.ctrlKey){chart.data.replaceSelected(datums)}else{pvc.data.Data.toggleSelected(datums)}}},this)}},isRubberBandSelecting:function(){return this.topRoot._isRubberBandSelecting},_initRubberBand:function(){var myself=this,chart=this.chart,options=chart.options,data=chart.data;var dMin2=4;this._isRubberBandSelecting=false;var rubberPvParentPanel=this.pvRootPanel||this.pvPanel.paddingPanel,toScreen,rb;var selectBar=this.selectBar=new pvc.visual.Bar(this,rubberPvParentPanel,{extensionId:'rubberBand',normalStroke:true,noHover:true,noSelect:true,noClick:true,noDoubleClick:true,noTooltip:true}).override('defaultStrokeWidth',function(){return 1.5}).override('defaultColor',function(type){return type==='stroke'?'#86fe00':'rgba(203, 239, 163, 0.6)'}).override('interactiveColor',function(color){return color}).pvMark.lock('visible',function(){return!!rb}).lock('left',function(){return rb.x}).lock('right').lock('top',function(){return rb.y}).lock('bottom').lock('width',function(){return rb.dx}).lock('height',function(){return rb.dy}).lock('cursor').lock('events','none');if(!this._getExtensionAbs('base','fillStyle')){rubberPvParentPanel.fillStyle(pvc.invisibleFill)}rubberPvParentPanel.lock('events','all');var scene=new pvc.visual.Scene(null,{panel:this});scene.x=scene.y=scene.dx=scene.dy=0;var selectionEndedDate;rubberPvParentPanel.lock('data',[scene]).event('mousedown',pv.Behavior.select().autoRender(false)).event('select',function(){if(!rb){if(myself.isAnimating()){return}if(scene.dx*scene.dx+scene.dy*scene.dy<=dMin2){return}rb=new pv.Shape.Rect(scene.x,scene.y,scene.dx,scene.dy);myself._isRubberBandSelecting=true;if(!toScreen){toScreen=rubberPvParentPanel.toScreenTransform()}myself.rubberBand=rb.apply(toScreen)}else{rb=new pv.Shape.Rect(scene.x,scene.y,scene.dx,scene.dy)}selectBar.render()}).event('selectend',function(){if(rb){var ev=arguments[arguments.length-1];if(!toScreen){toScreen=rubberPvParentPanel.toScreenTransform()}var rbs=rb.apply(toScreen);rb=null;myself._isRubberBandSelecting=false;selectBar.render();try{myself._processRubberBand(rbs,ev,{allowAdditive:true})}finally{selectionEndedDate=new Date()}}});if(options.clearSelectionMode==='emptySpaceClick'){rubberPvParentPanel.event("click",function(){if(selectionEndedDate){var timeSpan=new Date()-selectionEndedDate;if(timeSpan<300){selectionEndedDate=null;return}}if(data.owner.clearSelected()){myself.chart.updateSelections()}})}},_processRubberBand:function(rb,ev,keyArgs){this.rubberBand=rb;try{this._onRubberBandSelectionEnd(ev,keyArgs)}finally{this.rubberBand=null}},_onRubberBandSelectionEnd:function(ev,keyArgs){if(pvc.debug>=10){this._log("rubberBand "+pvc.stringify(this.rubberBand))}keyArgs=Object.create(keyArgs||{});keyArgs.toggle=false;var datums=this._getDatumsOnRubberBand(ev,keyArgs);if(datums){var allowAdditive=def.get(keyArgs,'allowAdditive',true);var chart=this.chart;chart._updatingSelections(function(){var clearBefore=!allowAdditive||(!ev.ctrlKey&&chart.options.ctrlSelectMode);if(clearBefore){chart.data.owner.clearSelected();pvc.data.Data.setSelected(datums,true)}else if(keyArgs.toggle){pvc.data.Data.toggleSelected(datums)}else{pvc.data.Data.setSelected(datums,true)}})}},_getDatumsOnRubberBand:function(ev,keyArgs){var datumMap=new def.Map();this._getDatumsOnRect(datumMap,this.rubberBand,keyArgs);var datums=datumMap.values();if(datums.length){datums=this.chart._onUserSelection(datums);if(datums&&!datums.length){datums=null}}return datums},_getDatumsOnRect:function(datumMap,rect,keyArgs){this._getOwnDatumsOnRect(datumMap,rect,keyArgs);if(this._children){this._children.forEach(function(child){child._getDatumsOnRect(datumMap,rect,keyArgs)},this)}},_getOwnDatumsOnRect:function(datumMap,rect,keyArgs){var any=false;if(this.isVisible){var pvMarks=this._getSelectableMarks();if(pvMarks&&pvMarks.length){pvMarks.forEach(function(pvMark){this._eachMarkDatumOnRect(pvMark,rect,function(datum){datumMap.set(datum.id,datum);any=true},this,def.get(keyArgs,'markSelectionMode'))},this)}}return any},_eachMarkDatumOnRect:function(pvMark,rect,fun,ctx,selectionMode){var sign=pvMark.sign;if(sign&&!sign.isSelectable()){return}if(selectionMode==null){selectionMode=def.get(pvMark,'rubberBandSelectionMode','partial')}var useCenter=(selectionMode==='center');pvMark.eachInstanceWithData(function(scenes,index,toScreen){var shape=pvMark.getShape(scenes,index);shape=(useCenter?shape.center():shape).apply(toScreen);processShape.call(this,shape,scenes[index],index)},this);function processShape(shape,instance,index){if(shape.intersectsRect(rect)){var cccScene=instance.data;if(cccScene&&cccScene.datum){var group=cccScene.group;var datums=group?group._datums:def.array.as(cccScene.datum);if(datums){datums.forEach(function(datum){if(!datum.isNull){if(pvc.debug>=20){this._log("Rubbered Datum.key="+datum.key+": "+pvc.stringify(shape)+" mark type: "+pvMark.type+" index="+index)}fun.call(ctx,datum)}},this)}}}}},isAnchorTopOrBottom:function(anchor){if(!anchor){anchor=this.anchor}return anchor==="top"||anchor==="bottom"},anchorOrtho:function(anchor){if(!anchor){anchor=this.anchor}return pvc.BasePanel.relativeAnchor[anchor]},anchorOrthoMirror:function(anchor){if(!anchor){anchor=this.anchor}return pvc.BasePanel.relativeAnchorMirror[anchor]},anchorOpposite:function(anchor){if(!anchor){anchor=this.anchor}return pvc.BasePanel.oppositeAnchor[anchor]},anchorLength:function(anchor){if(!anchor){anchor=this.anchor}return pvc.BasePanel.parallelLength[anchor]},anchorOrthoLength:function(anchor){if(!anchor){anchor=this.anchor}return pvc.BasePanel.orthogonalLength[anchor]},isOrientationVertical:function(orientation){return this.chart.isOrientationVertical(orientation)},isOrientationHorizontal:function(orientation){return this.chart.isOrientationHorizontal(orientation)}}).addStatic({relativeAnchor:{top:"left",bottom:"left",left:"bottom",right:"bottom"},leftBottomAnchor:{top:"bottom",bottom:"bottom",left:"left",right:"left"},leftTopAnchor:{top:"top",bottom:"top",left:"left",right:"left"},horizontalAlign:{top:"right",bottom:"left",middle:"center",right:"right",left:"left",center:"center"},verticalAlign:{top:"top",bottom:"bottom",middle:"middle",right:"bottom",left:"top",center:"middle"},verticalAlign2:{top:"top",bottom:"bottom",middle:"middle",right:"top",left:"bottom",center:"middle"},relativeAnchorMirror:{top:"right",bottom:"right",left:"top",right:"top"},oppositeAnchor:{top:"bottom",bottom:"top",left:"right",right:"left"},parallelLength:{top:"width",bottom:"width",right:"height",left:"height"},orthogonalLength:{top:"height",bottom:"height",right:"width",left:"width"},oppositeLength:{width:"height",height:"width"}});
def.type('pvc.PlotPanel',pvc.BasePanel).init(function(chart,parent,plot,options){this.base(chart,parent,options);this.plot=plot;this._extensionPrefix=plot.extensionPrefixes;this.dataPartValue=plot.option('DataPart');this.axes.color=chart._getAxis('color',(plot.option('ColorAxis')||0)-1);this.orientation=plot.option('Orientation');this.valuesVisible=plot.option('ValuesVisible');this.valuesAnchor=plot.option('ValuesAnchor');this.valuesMask=plot.option('ValuesMask');this.valuesFont=plot.option('ValuesFont');var roles=this.visualRoles=Object.create(chart._visualRoles);var colorRoleName=plot.option('ColorRole');roles.color=colorRoleName?chart.visualRoles(colorRoleName):null;this.chart._addPlotPanel(this)}).add({anchor:'fill',visualRoles:null,_getExtensionId:function(){var extensionIds=['chart','plot'];if(this.plotName){extensionIds.push(this.plotName)}return extensionIds},isOrientationVertical:function(){return this.orientation===pvc.orientation.vertical},isOrientationHorizontal:function(){return this.orientation===pvc.orientation.horizontal}});
def.type('pvc.MultiChartPanel',pvc.BasePanel).add({anchor:'fill',_multiInfo:null,createSmallCharts:function(){var chart=this.chart;var options=chart.options;var multiChartMax=Number(options.multiChartMax);if(isNaN(multiChartMax)||multiChartMax<1){multiChartMax=Infinity}var multiChartRole=chart.visualRoles('multiChart');var data=chart.data.flattenBy(multiChartRole,{visible:true});var leafCount=data._children.length;var count=Math.min(leafCount,multiChartMax);if(count===0){return}var multiChartColumnsMax=+options.multiChartColumnsMax;if(isNaN(multiChartColumnsMax)||multiChartMax<1){multiChartColumnsMax=3}var colCount=Math.min(count,multiChartColumnsMax);colCount>=1&&isFinite(colCount)||def.assert("Must be at least 1 and finite");var rowCount=Math.ceil(count/colCount);rowCount>=1||def.assert("Must be at least 1");var coordRootAxesByScopeType=this._getCoordinatedRootAxesByScopeType();var coordScopesByType,addChartToScope,indexChartByScope;if(coordRootAxesByScopeType){coordScopesByType={};addChartToScope=function(childChart,scopeType,scopeIndex){var scopes=def.array.lazy(coordScopesByType,scopeType);def.array.lazy(scopes,scopeIndex).push(childChart)};indexChartByScope=function(childChart){if(coordRootAxesByScopeType.row){addChartToScope(childChart,'row',childChart.smallRowIndex)}if(coordRootAxesByScopeType.column){addChartToScope(childChart,'column',childChart.smallColIndex)}if(coordRootAxesByScopeType.global){addChartToScope(childChart,'global',0)}}}var childOptionsBase=this._buildSmallChartsBaseOptions();var ChildClass=chart.constructor;for(var index=0;index<count;index++){var childData=data._children[index];var colIndex=(index%colCount);var rowIndex=Math.floor(index/colCount);var childOptions=def.set(Object.create(childOptionsBase),'smallColIndex',colIndex,'smallRowIndex',rowIndex,'title',childData.absLabel,'data',childData);var childChart=new ChildClass(childOptions);if(!coordRootAxesByScopeType){childChart._preRender()}else{childChart._preRenderPhase1();indexChartByScope(childChart)}}if(coordRootAxesByScopeType){def.eachOwn(coordRootAxesByScopeType,function(axes,scopeType){axes.forEach(function(axis){coordScopesByType[scopeType].forEach(function(scopeCharts){this._coordinateScopeAxes(axis.id,scopeCharts)},this)},this)},this);chart.children.forEach(function(childChart){childChart._preRenderPhase2()})}this._multiInfo={data:data,count:count,rowCount:rowCount,colCount:colCount,multiChartColumnsMax:multiChartColumnsMax,coordScopesByType:coordScopesByType}},_getCoordinatedRootAxesByScopeType:function(){var hasCoordination=false;var rootAxesByScopeType=def.query(this.chart.axesList).multipleIndex(function(axis){if(axis.scaleType!=='discrete'&&axis.option.isDefined('DomainScope')){var scopeType=axis.option('DomainScope');if(scopeType!=='cell'){hasCoordination=true;return scopeType}}});return hasCoordination?rootAxesByScopeType:null},_coordinateScopeAxes:function(axisId,scopeCharts){var unionExtent=def.query(scopeCharts).select(function(childChart){var scale=childChart.axes[axisId].scale;if(!scale.isNull){var domain=scale.domain();return{min:domain[0],max:domain[1]}}}).reduce(pvc.unionExtents,null);if(unionExtent){scopeCharts.forEach(function(childChart){var axis=childChart.axes[axisId];var scale=axis.scale;if(!scale.isNull){scale.domain(unionExtent.min,unionExtent.max);axis.setScale(scale)}})}},_buildSmallChartsBaseOptions:function(){var chart=this.chart;var options=chart.options;return def.set(Object.create(options),'parent',chart,'legend',false,'titleFont',options.smallTitleFont,'titlePosition',options.smallTitlePosition,'titleAlign',options.smallTitleAlign,'titleAlignTo',options.smallTitleAlignTo,'titleOffset',options.smallTitleOffset,'titleKeepInBounds',options.smallTitleKeepInBounds,'titleMargins',options.smallTitleMargins,'titlePaddings',options.smallTitlePaddings,'titleSize',options.smallTitleSize,'titleSizeMax',options.smallTitleSizeMax)},_calcLayout:function(layoutInfo){var multiInfo=this._multiInfo;if(!multiInfo){return}var chart=this.chart;var options=chart.options;var clientSize=layoutInfo.clientSize;var prevLayoutInfo=layoutInfo.previous;var initialClientWidth=prevLayoutInfo?prevLayoutInfo.initialClientWidth:clientSize.width;var initialClientHeight=prevLayoutInfo?prevLayoutInfo.initialClientHeight:clientSize.height;var smallWidth=pvc.PercentValue.parse(options.smallWidth);if(smallWidth!=null){smallWidth=pvc.PercentValue.resolve(smallWidth,initialClientWidth)}var smallHeight=pvc.PercentValue.parse(options.smallHeight);if(smallHeight!=null){smallHeight=pvc.PercentValue.resolve(smallHeight,initialClientHeight)}var ar=+options.smallAspectRatio;if(isNaN(ar)||ar<=0){ar=this._calulateDefaultAspectRatio()}if(smallWidth==null){if(isFinite(multiInfo.multiChartColumnsMax)){smallWidth=clientSize.width/multiInfo.colCount}else{if(smallHeight==null){smallHeight=initialClientHeight}smallWidth=ar*smallHeight}}if(smallHeight==null){if((multiInfo.rowCount===1&&def.get(options,'multiChartSingleRowFillsHeight',true))||(multiInfo.colCount===1&&def.get(options,'multiChartSingleColFillsHeight',true))){smallHeight=initialClientHeight}else{smallHeight=smallWidth/ar}}def.set(layoutInfo,'initialClientWidth',initialClientWidth,'initialClientHeight',initialClientHeight,'width',smallWidth,'height',smallHeight);return{width:smallWidth*multiInfo.colCount,height:Math.max(clientSize.height,smallHeight*multiInfo.rowCount)}},_calulateDefaultAspectRatio:function(){if(this.chart instanceof pvc.PieChart){return 10/7}return 5/4},_getExtensionId:function(){return'content'},_createCore:function(li){var mi=this._multiInfo;if(!mi){return}var chart=this.chart;var options=chart.options;var smallMargins=options.smallMargins;if(smallMargins==null){smallMargins=new pvc.Sides(new pvc.PercentValue(0.02))}else{smallMargins=new pvc.Sides(smallMargins)}var smallPaddings=new pvc.Sides(options.smallPaddings);chart.children.forEach(function(childChart){childChart._setSmallLayout({left:childChart.smallColIndex*li.width,top:childChart.smallRowIndex*li.height,width:li.width,height:li.height,margins:this._buildSmallMargins(childChart,smallMargins),paddings:smallPaddings})},this);var coordScopesByType=mi.coordScopesByType;if(coordScopesByType){chart._coordinateSmallChartsLayout(coordScopesByType)}this.base(li)},_buildSmallMargins:function(childChart,smallMargins){var mi=this._multiInfo;var lastColIndex=mi.colCount-1;var lastRowIndex=mi.rowCount-1;var colIndex=childChart.smallColIndex;var rowIndex=childChart.smallRowIndex;var margins={};if(colIndex>0){margins.left=smallMargins.left}if(colIndex<lastColIndex){margins.right=smallMargins.right}if(rowIndex>0){margins.top=smallMargins.top}if(rowIndex<lastRowIndex){margins.bottom=smallMargins.bottom}return margins}});
def.type('pvc.TitlePanelAbstract',pvc.BasePanel).init(function(chart,parent,options){if(!options){options={}}var anchor=options.anchor||this.anchor;if(options.size==null){var size=options.titleSize;if(size!=null){options.size=new pvc.Size().setSize(size,{singleProp:this.anchorOrthoLength(anchor)})}}if(options.sizeMax==null){var sizeMax=options.titleSizeMax;if(sizeMax!=null){options.sizeMax=new pvc.Size().setSize(sizeMax,{singleProp:this.anchorOrthoLength(anchor)})}}if(options.paddings==null){options.paddings=this.defaultPaddings}this.base(chart,parent,options);if(options.font===undefined){var extensionFont=this._getExtension('label','font');if(typeof extensionFont==='string'){this.font=extensionFont}}}).add({pvLabel:null,anchor:'top',title:null,titleSize:undefined,font:"12px sans-serif",defaultPaddings:2,_extensionPrefix:'title',_calcLayout:function(layoutInfo){var requestSize=new pvc.Size();var a=this.anchor;var a_width=this.anchorLength(a);var a_height=this.anchorOrthoLength(a);var textWidth=pv.Text.measure(this.title,this.font).width+2;var clientWidth=layoutInfo.clientSize[a_width];var desiredWidth=layoutInfo.desiredClientSize[a_width];if(desiredWidth==null){desiredWidth=textWidth>clientWidth?clientWidth:textWidth}else if(desiredWidth>clientWidth){desiredWidth=clientWidth}var lines;if(textWidth>desiredWidth){lines=pvc.text.justify(this.title,desiredWidth,this.font)}else{lines=this.title?[this.title]:[]}var lineHeight=pv.Text.fontHeight(this.font);var realHeight=lines.length*lineHeight;var availableHeight=layoutInfo.clientSize[a_height];var desiredHeight=layoutInfo.desiredClientSize[a_height];if(desiredHeight==null){desiredHeight=realHeight}else if(desiredHeight>availableHeight){desiredHeight=availableHeight}if(realHeight>desiredHeight){var maxLineCount=Math.max(1,Math.floor(desiredHeight/lineHeight));if(lines.length>maxLineCount){var firstCroppedLine=lines[maxLineCount];lines.length=maxLineCount;realHeight=desiredHeight=maxLineCount*lineHeight;var lastLine=lines[maxLineCount-1]+" "+firstCroppedLine;lines[maxLineCount-1]=pvc.text.trimToWidthB(desiredWidth,lastLine,this.font,"..")}}layoutInfo.lines=lines;layoutInfo.topOffset=(desiredHeight-realHeight)/2;layoutInfo.lineSize={width:desiredWidth,height:lineHeight};layoutInfo.a_width=a_width;layoutInfo.a_height=a_height;requestSize[a_width]=desiredWidth;requestSize[a_height]=desiredHeight;return requestSize},_createCore:function(layoutInfo){var rootScene=this._buildScene(layoutInfo);var rotationByAnchor={top:0,right:Math.PI/2,bottom:0,left:-Math.PI/2};var textAlign=pvc.BasePanel.horizontalAlign[this.align];var textAnchor=pvc.BasePanel.leftTopAnchor[this.anchor];var wrapper;if(this.compatVersion()<=1){wrapper=function(v1f){return function(itemScene){return v1f.call(this)}}}this.pvLabel=new pvc.visual.Label(this,this.pvPanel,{extensionId:'label',wrapper:wrapper}).lock('data',rootScene.lineScenes).pvMark[textAnchor](function(lineScene){return layoutInfo.topOffset+lineScene.vars.size.height/2+this.index*lineScene.vars.size.height}).textAlign(textAlign)[this.anchorOrtho(textAnchor)](function(lineScene){switch(this.textAlign()){case'center':return lineScene.vars.size.width/2;case'left':return 0;case'right':return lineScene.vars.size.width}}).text(function(lineScene){return lineScene.vars.textLines[this.index]}).font(this.font).textBaseline('middle').textAngle(rotationByAnchor[this.anchor])},_buildScene:function(layoutInfo){var rootScene=new pvc.visual.Scene(null,{panel:this,group:this.chart.data});var textLines=layoutInfo.lines;rootScene.vars.size=layoutInfo.lineSize;rootScene.vars.textLines=textLines;rootScene.lineScenes=def.array.create(textLines.length,rootScene);return rootScene},_getExtensionId:function(){return''}});
def.type('pvc.TitlePanel',pvc.TitlePanelAbstract).init(function(chart,parent,options){if(!options){options={}}var isV1Compat=chart.compatVersion()<=1;if(isV1Compat){var size=options.titleSize;if(size==null){options.titleSize=25}}this._extensionPrefix=!chart.parent?"title":"smallTitle";this.base(chart,parent,options)}).add({font:"14px sans-serif",defaultPaddings:4});
def.type('pvc.LegendPanel',pvc.BasePanel).add({pvRule:null,pvDot:null,pvLabel:null,anchor:'bottom',pvLegendPanel:null,textMargin:6,itemPadding:2.5,markerSize:15,font:'10px sans-serif',_calcLayout:function(layoutInfo){return this._getBulletRootScene().layout(layoutInfo)},_createCore:function(layoutInfo){var clientSize=layoutInfo.clientSize,rootScene=this._getBulletRootScene(),itemPadding=rootScene.vars.itemPadding,contentSize=rootScene.vars.size;var isHorizontal=this.isAnchorTopOrBottom();var a_top=isHorizontal?'top':'left';var a_bottom=this.anchorOpposite(a_top);var a_width=this.anchorLength(a_top);var a_height=this.anchorOrthoLength(a_top);var a_center=isHorizontal?'center':'middle';var a_left=isHorizontal?'left':'top';var a_right=this.anchorOpposite(a_left);var leftOffset=0;switch(this.align){case a_right:leftOffset=clientSize[a_width]-contentSize.width;break;case a_center:leftOffset=(clientSize[a_width]-contentSize.width)/2;break}this.pvPanel.overflow("hidden");var pvLegendRowPanel=this.pvPanel.add(pv.Panel).data(rootScene.vars.rows)[a_left](leftOffset)[a_top](function(){var prevRow=this.sibling();return prevRow?(prevRow[a_top]+prevRow[a_height]+itemPadding[a_height]):0})[a_width](function(row){return row.size.width})[a_height](function(row){return row.size.height});var wrapper;if(this.compatVersion()<=1){wrapper=function(v1f){return function(itemScene){return v1f.call(this,itemScene.vars.value.rawValue)}}}this.pvLegendPanel=new pvc.visual.Panel(this,pvLegendRowPanel,{extensionId:'panel',wrapper:wrapper,noSelect:false,noClickSelect:true}).lockMark('data',function(row){return row.items}).lock(a_right,null).lock(a_bottom,null).lockMark(a_left,function(clientScene){var itemPadding=clientScene.vars.itemPadding;var prevItem=this.sibling();return prevItem?(prevItem[a_left]+prevItem[a_width]+itemPadding[a_width]):0}).lockMark('height',function(itemScene){return itemScene.vars.clientSize.height}).lockMark(a_top,isHorizontal?function(itemScene){var vars=itemScene.vars;return vars.row.size.height/2-vars.clientSize.height/2}:0).lockMark('width',isHorizontal?function(itemScene){return itemScene.vars.clientSize.width}:function(){return this.parent.width()}).pvMark.def("hidden","false").fillStyle(function(){return this.hidden()=="true"?"rgba(200,200,200,1)":"rgba(200,200,200,0.0001)"}).cursor(function(itemScene){return itemScene.isClickable()?"pointer":null}).event("click",function(itemScene){if(itemScene.isClickable()){return itemScene.click()}});var pvLegendMarkerPanel=new pvc.visual.Panel(this,this.pvLegendPanel).pvMark.left(0).top(0).right(null).bottom(null).width(function(itemScene){return itemScene.vars.markerSize}).height(function(itemScene){return itemScene.vars.clientSize.height});if(pvc.debug>=20){pvLegendRowPanel.strokeStyle('red');this.pvLegendPanel.strokeStyle('green');pvLegendMarkerPanel.strokeStyle('blue')}rootScene.childNodes.forEach(function(groupScene){var pvGroupPanel=new pvc.visual.Panel(this,pvLegendMarkerPanel).pvMark.visible(function(itemScene){return itemScene.parent===groupScene});groupScene.renderer().create(this,pvGroupPanel,groupScene.extensionPrefix,wrapper)},this);this.pvLabel=new pvc.visual.Label(this,pvLegendMarkerPanel.anchor("right"),{extensionId:'label',wrapper:wrapper}).intercept('textStyle',function(itemScene){var baseTextStyle=this.delegateExtension()||"black";return itemScene.isOn()?baseTextStyle:pvc.toGrayScale(baseTextStyle,null,undefined,150)}).pvMark.textAlign('left').text(function(itemScene){return itemScene.vars.value.label}).lock('textMargin',function(itemScene){return itemScene.vars.textMargin-4}).font(function(itemScene){return itemScene.vars.font}).textDecoration(function(itemScene){return itemScene.isOn()?"":"line-through"})},_getExtensionId:function(){return'area'},_getExtensionPrefix:function(){return'legend'},_getSelectableMarks:function(){return[this.pvLegendPanel]},_getBulletRootScene:function(){var rootScene=this._rootScene;if(!rootScene){rootScene=new pvc.visual.legend.BulletRootScene(null,{panel:this,group:this.chart.data,horizontal:this.isAnchorTopOrBottom(),font:this.font,markerSize:this.markerSize,textMargin:this.textMargin,itemPadding:this.itemPadding});this._rootScene=rootScene}return rootScene}});
def.type('pvc.CartesianAbstract',pvc.BaseChart).init(function(options){this.axesPanels={};this.base(options)}).add({_gridDockPanel:null,axesPanels:null,yAxisPanel:null,xAxisPanel:null,secondXAxisPanel:null,secondYAxisPanel:null,yScale:null,xScale:null,_getSeriesRoleSpec:function(){return{isRequired:true,defaultDimension:'series*',autoCreateDimension:true,requireIsDiscrete:true}},_getColorRoleSpec:function(){return{isRequired:true,defaultDimension:'color*',defaultSourceRole:'series',requireIsDiscrete:true}},_collectPlotAxesDataCells:function(plot,dataCellsByAxisTypeThenIndex){this.base(plot,dataCellsByAxisTypeThenIndex);if(plot.option.isDefined('BaseAxis')){var baseDataCellsByAxisIndex=def.array.lazy(dataCellsByAxisTypeThenIndex,'base');def.array.lazy(baseDataCellsByAxisIndex,plot.option('BaseAxis')-1).push({plot:plot,role:this.visualRoles(plot.option('BaseRole')),dataPartValue:plot.option('DataPart')})}if(plot.option.isDefined('OrthoAxis')){var trend=plot.option('Trend');var isStacked=plot.option.isDefined('Stacked')?plot.option('Stacked'):undefined;var orthoDataCellsByAxisIndex=def.array.lazy(dataCellsByAxisTypeThenIndex,'ortho');var orthoRoleNames=def.array.to(plot.option('OrthoRole'));var dataCellBase={dataPartValue:plot.option('DataPart'),isStacked:isStacked,trend:trend,nullInterpolationMode:plot.option('NullInterpolationMode')};var orthoDataCells=def.array.lazy(orthoDataCellsByAxisIndex,plot.option('OrthoAxis')-1);orthoRoleNames.forEach(function(orthoRoleName){var dataCell=Object.create(dataCellBase);dataCell.role=this.visualRoles(orthoRoleName);orthoDataCells.push(dataCell)},this)}},_addAxis:function(axis){this.base(axis);switch(axis.type){case'base':case'ortho':this.axes[axis.orientedId]=axis;if(axis.v1SecondOrientedId){this.axes[axis.v1SecondOrientedId]=axis}break}return this},_generateTrendsDataCell:function(dataCell){var trend=dataCell.trend;if(trend){var trendInfo=pvc.trends.get(trend.type);var newDatums=[];this._generateTrendsDataCellCore(newDatums,dataCell,trendInfo);if(newDatums.length){this.data.owner.add(newDatums)}}},_generateTrendsDataCellCore:function(dataCell,trendInfo){},_setAxesScales:function(hasMultiRole){this.base(hasMultiRole);if(!hasMultiRole||this.parent){['base','ortho'].forEach(function(type){var axisOfType=this.axesByType[type];if(axisOfType){axisOfType.forEach(this._createAxisScale,this)}},this)}},_createAxisScale:function(axis){var isOrtho=axis.type==='ortho';var isCart=isOrtho||axis.type==='base';var scale=this._createScaleByAxis(axis);if(scale.isNull&&pvc.debug>=3){this._log(def.format("{0} scale for axis '{1}'- no data",[axis.scaleType,axis.id]))}scale=axis.setScale(scale).scale;if(isCart){if(isOrtho&&axis.index===1){this.secondScale=scale}else if(!axis.index){this[axis.orientation+'Scale']=scale}}return scale},_createScaleByAxis:function(axis){var createScale=this['_create'+def.firstUpperCase(axis.scaleType)+'ScaleByAxis'];return createScale.call(this,axis)},_preRenderContent:function(contentOptions){this._createFocusWindow();this._gridDockPanel=new pvc.CartesianGridDockingPanel(this,this.basePanel,{margins:contentOptions.margins,paddings:contentOptions.paddings});['base','ortho'].forEach(function(type){var typeAxes=this.axesByType[type];if(typeAxes){def.query(typeAxes).reverse().each(function(axis){this._createAxisPanel(axis)},this)}},this);this._createPlotPanels(this._gridDockPanel,{clickAction:contentOptions.clickAction,doubleClickAction:contentOptions.doubleClickAction})},_createFocusWindow:function(){if(this._canSelectWithFocusWindow()){var fwData;var fw=this.focusWindow;if(fw){fwData=fw._exportData()}fw=this.focusWindow=new pvc.visual.CartesianFocusWindow(this);if(fwData){fw._importData(fwData)}fw._initFromOptions()}else if(this.focusWindow){delete this.focusWindow}},_createAxisPanel:function(axis){if(axis.option('Visible')){var titlePanel;var title=axis.option('Title');if(!def.empty(title)){titlePanel=new pvc.AxisTitlePanel(this,this._gridDockPanel,axis,{title:title,font:axis.option('TitleFont')||axis.option('Font'),anchor:axis.option('Position'),align:axis.option('TitleAlign'),margins:axis.option('TitleMargins'),paddings:axis.option('TitlePaddings'),titleSize:axis.option('TitleSize'),titleSizeMax:axis.option('TitleSizeMax')})}var panel=new pvc.AxisPanel(this,this._gridDockPanel,axis,{anchor:axis.option('Position'),size:axis.option('Size'),sizeMax:axis.option('SizeMax'),clickAction:axis.option('ClickAction'),doubleClickAction:axis.option('DoubleClickAction'),useCompositeAxis:axis.option('Composite'),font:axis.option('Font'),labelSpacingMin:axis.option('LabelSpacingMin'),tickExponentMin:axis.option('TickExponentMin'),tickExponentMax:axis.option('TickExponentMax'),grid:axis.option('Grid'),gridCrossesMargin:axis.option('GridCrossesMargin'),ruleCrossesMargin:axis.option('RuleCrossesMargin'),zeroLine:axis.option('ZeroLine'),domainRoundMode:axis.option('DomainRoundMode'),desiredTickCount:axis.option('DesiredTickCount'),showTicks:axis.option('Ticks'),showMinorTicks:axis.option('MinorTicks')});if(titlePanel){panel.titlePanel=titlePanel}this.axesPanels[axis.id]=panel;this.axesPanels[axis.orientedId]=panel;if(axis.index<=1&&axis.v1SecondOrientedId){this[axis.v1SecondOrientedId+'AxisPanel']=panel}return panel}},_createDiscreteScaleByAxis:function(axis){var dataPartValues=axis.dataCells.map(function(dataCell){return dataCell.dataPartValue});var baseData=this.visibleData(dataPartValues,{ignoreNulls:false});var data=baseData&&baseData.flattenBy(axis.role);var scale=new pv.Scale.ordinal();if(!data||!data.count()){scale.isNull=true}else{var values=data.children().select(function(child){return def.nullyTo(child.value,"")}).array();scale.domain(values)}return scale},_createTimeSeriesScaleByAxis:function(axis){var extent=this._getContinuousVisibleExtent(axis);var scale=new pv.Scale.linear();if(!extent){scale.isNull=true}else{var dMin=extent.min;var dMax=extent.max;if((dMax-dMin)===0){dMax=new Date(dMax.getTime()+3600000)}scale.domain(dMin,dMax);scale.minLocked=extent.minLocked;scale.maxLocked=extent.maxLocked}return scale},_createNumericScaleByAxis:function(axis){var extent=this._getContinuousVisibleExtentConstrained(axis);var scale=new pv.Scale.linear();if(!extent){scale.isNull=true}else{var tmp;var dMin=extent.min;var dMax=extent.max;if(dMin>dMax){tmp=dMin;dMin=dMax;dMax=tmp}var originIsZero=axis.option('OriginIsZero');if(originIsZero){if(dMin===0){extent.minLocked=true}else if(dMax===0){extent.maxLocked=true}else if((dMin*dMax)>0){if(dMin>0){if(!extent.minLocked){extent.minLocked=true;dMin=0}}else{if(!extent.maxLocked){extent.maxLocked=true;dMax=0}}}}if(dMin>dMax){tmp=dMin;dMin=dMax;dMax=tmp}if(dMax-dMin<=1e-12){if(!extent.minLocked){dMin=dMin!==0?(dMin*0.99):-0.1}if(!extent.maxLocked||extent.minLocked){dMax=dMax!==0?dMax*1.01:0.1}}scale.domain(dMin,dMax);scale.minLocked=extent.minLocked;scale.maxLocked=extent.maxLocked}return scale},_onLaidOut:function(){if(this.plotPanelList&&this.plotPanelList[0]){['base','ortho'].forEach(function(type){var axes=this.axesByType[type];if(axes){axes.forEach(this._setCartAxisScaleRange,this)}},this)}},_setCartAxisScaleRange:function(axis){var info=this.plotPanelList[0]._layoutInfo;var size=info.clientSize;var length=(axis.orientation==='x')?size.width:size.height;axis.setScaleRange(length);return axis.scale},_getAxesRoundingPaddings:function(){var axesPaddings={};var axesByType=this.axesByType;['base','ortho'].forEach(function(type){var typeAxes=axesByType[type];if(typeAxes){typeAxes.forEach(processAxis)}});return axesPaddings;function setSide(side,pct,locked){var value=axesPaddings[side];if(value==null||pct>value){axesPaddings[side]=pct;axesPaddings[side+'Locked']=locked}else if(locked){axesPaddings[side+'Locked']=locked}}function processAxis(axis){if(axis){var tickRoundPads=axis.getScaleRoundingPaddings();if(tickRoundPads){var isX=axis.orientation==='x';setSide(isX?'left':'bottom',tickRoundPads.begin,tickRoundPads.beginLocked);setSide(isX?'right':'top',tickRoundPads.end,tickRoundPads.endLocked)}}}},_warnSingleContinuousValueRole:function(valueRole){if(!valueRole.grouping.isSingleDimension){this._log("[WARNING] A linear scale can only be obtained for a single dimension role.")}if(valueRole.grouping.isDiscrete()){this._log("[WARNING] The single dimension of role '{0}' should be continuous.",[valueRole.name])}},_getContinuousVisibleExtentConstrained:function(axis,min,max){var minLocked=false;var maxLocked=false;if(min==null){min=axis.option('FixedMin');minLocked=(min!=null)}if(max==null){max=axis.option('FixedMax');maxLocked=(max!=null)}if(min==null||max==null){var baseExtent=this._getContinuousVisibleExtent(axis);if(!baseExtent){return null}if(min==null){min=baseExtent.min}if(max==null){max=baseExtent.max}}return{min:min,max:max,minLocked:minLocked,maxLocked:maxLocked}},_getContinuousVisibleExtent:function(valueAxis){var dataCells=valueAxis.dataCells;if(dataCells.length===1){return this._getContinuousVisibleCellExtent(valueAxis,dataCells[0])}return def.query(dataCells).select(function(dataCell){return this._getContinuousVisibleCellExtent(valueAxis,dataCell)},this).reduce(pvc.unionExtents,null)},_getContinuousVisibleCellExtent:function(valueAxis,valueDataCell){var valueRole=valueDataCell.role;this._warnSingleContinuousValueRole(valueRole);if(valueRole.name==='series'){throw def.error.notImplemented()}var useAbs=valueAxis.scaleUsesAbs();var data=this.visibleData(valueDataCell.dataPartValue);var extent=data&&data.dimensions(valueRole.firstDimensionName()).extent({abs:useAbs});if(extent){var minValue=extent.min.value;var maxValue=extent.max.value;return{min:(useAbs?Math.abs(minValue):minValue),max:(useAbs?Math.abs(maxValue):maxValue)}}},markEventDefaults:{strokeStyle:"#5BCBF5",lineWidth:"0.5",textStyle:"#5BCBF5",verticalOffset:10,verticalAnchor:"bottom",horizontalAnchor:"right",forceHorizontalAnchor:false,horizontalAnchorSwapLimit:80},markEvent:function(dateString,label,options){var baseScale=this.axes.base.scale;if(baseScale.type!=='timeSeries'){this._log("Attempting to mark an event on a non timeSeries chart");return this}var o=$.extend({},this.markEventDefaults,options);var d=pv.Format.date(this.options.timeSeriesFormat).parse(dateString);var dpos=baseScale(d),range=baseScale.range();if(dpos<range[0]||dpos>range[1]){this._log("Event outside the allowed range, returning");return this}var panel=this.plotPanelList[0].pvPanel;var h=this.yScale.range()[1];if(!o.forceHorizontalAnchor){var availableSize=o.horizontalAnchor=="right"?range[1]-dpos:dpos;if(availableSize<o.horizontalAnchorSwapLimit){o.horizontalAnchor=o.horizontalAnchor=="right"?"left":"right"}}var line=panel.add(pv.Line).data([0,h]).strokeStyle(o.strokeStyle).lineWidth(o.lineWidth).bottom(function(d){return d}).left(dpos);line.anchor(o.horizontalAnchor).top(o.verticalAnchor=="top"?o.verticalOffset:(h-o.verticalOffset)).add(pv.Label).text(label).textStyle(o.textStyle).visible(function(){return!this.index});return this},defaults:{panelSizeRatio:0.9,timeSeries:false,timeSeriesFormat:"%Y-%m-%d"}});
def.type('pvc.GridDockingPanel',pvc.BasePanel).add({anchor:'fill',_calcLayout:function(layoutInfo){var me=this;if(!me._children){return}var useLog=pvc.debug>=5;var margins=new pvc.Sides(0);var paddings=new pvc.Sides(0);var remSize=def.copyOwn(layoutInfo.clientSize);var aolMap=pvc.BasePanel.orthogonalLength;var aoMap=pvc.BasePanel.relativeAnchor;var alMap=pvc.BasePanel.parallelLength;var childKeyArgs={force:true,referenceSize:layoutInfo.clientSize};var fillChildren=[];var sideChildren=[];var paddingHistory={};var LoopDetected=1;var NormalPaddingsChanged=2;var OverflowPaddingsChanged=4;var emptyNewPaddings=new pvc.Sides();var isDisasterRecovery=false;if(useLog){me._group("CCC GRID LAYOUT clientSize = "+pvc.stringify(remSize))}try{this._children.forEach(initChild);if(useLog){me._group("Phase 1 - Determine MARGINS and FILL SIZE from SIDE panels")}try{sideChildren.forEach(layoutChild1Side)}finally{if(useLog){me._groupEnd();me._log("Final FILL margins = "+pvc.stringify(margins));me._log("Final FILL border size = "+pvc.stringify(remSize))}}if(useLog){me._group("Phase 2 - Determine COMMON PADDINGS")}try{doMaxTimes(9,layoutCycle)}finally{if(useLog){me._groupEnd();me._log("Final FILL clientSize = "+pvc.stringify({width:(remSize.width-paddings.width),height:(remSize.height-paddings.height)}));me._log("Final COMMON paddings = "+pvc.stringify(paddings))}}layoutInfo.gridMargins=new pvc.Sides(margins);layoutInfo.gridPaddings=new pvc.Sides(paddings);layoutInfo.gridSize=new pvc.Size(remSize)}finally{if(useLog){me._groupEnd()}}function layoutCycle(remTimes,iteration){if(useLog){me._group("LayoutCycle "+(isDisasterRecovery?"- Disaster MODE":("#"+(iteration+1))))}try{var index,count;var canChange=layoutInfo.canChange!==false&&!isDisasterRecovery&&(remTimes>0);var paddingsChanged;var ownPaddingsChanged=false;var breakAndRepeat;index=0;count=sideChildren.length;while(index<count){if(useLog){me._group("SIDE Child #"+(index+1))}try{paddingsChanged=layoutChild2Side(sideChildren[index],canChange);if(!isDisasterRecovery&&paddingsChanged){breakAndRepeat=false;if((paddingsChanged&OverflowPaddingsChanged)!==0){if(useLog){me._log("SIDE Child #"+(index+1)+" changed overflow paddings")}if(!ownPaddingsChanged){ownPaddingsChanged=true;layoutInfo.requestPaddings=layoutInfo.paddings}}if((paddingsChanged&NormalPaddingsChanged)!==0){if(remTimes>0){if(useLog){me._log("SIDE Child #"+(index+1)+" changed normal paddings")}breakAndRepeat=true}else if(pvc.debug>=2){me._warn("SIDE Child #"+(index+1)+" changed paddings but no more iterations possible.")}}if((paddingsChanged&LoopDetected)!==0){isDisasterRecovery=true;layoutCycle(0);return false}if(breakAndRepeat){return true}}}finally{if(useLog){me._groupEnd()}}index++}if(ownPaddingsChanged){if(useLog){me._log("Restarting due to overflowPaddings change")}return false}index=0;count=fillChildren.length;while(index<count){if(useLog){me._group("FILL Child #"+(index+1))}try{paddingsChanged=layoutChildFill(fillChildren[index],canChange);if(!isDisasterRecovery&&paddingsChanged){breakAndRepeat=false;if((paddingsChanged&NormalPaddingsChanged)!==0){if(remTimes>0){if(pvc.debug>=5){me._log("FILL Child #"+(index+1)+" increased paddings")}breakAndRepeat=true}else if(pvc.debug>=2){me._warn("FILL Child #"+(index+1)+" increased paddings but no more iterations possible.")}}if((paddingsChanged&LoopDetected)!==0){isDisasterRecovery=true;layoutCycle(0);return false}if(breakAndRepeat){return true}}}finally{if(useLog){me._groupEnd()}}index++}return false}finally{if(useLog){me._groupEnd()}}}function doMaxTimes(maxTimes,fun){var index=0;while(maxTimes--){if(fun(maxTimes,index)===false){return true}index++}return false}function initChild(child){var a=child.anchor;if(a){if(a==='fill'){fillChildren.push(child);var childPaddings=child.paddings.resolve(childKeyArgs.referenceSize);paddings=pvc.Sides.resolvedMax(paddings,childPaddings)}else{def.hasOwn(aoMap,a)||def.fail.operationInvalid("Unknown anchor value '{0}'",[a]);sideChildren.push(child)}}}function layoutChild1Side(child,index){if(useLog){me._group("SIDE Child #"+(index+1))}try{var paddingsChanged=0;var a=child.anchor;childKeyArgs.paddings=filterAnchorPaddings(a,paddings);child.layout(new pvc.Size(remSize),childKeyArgs);if(child.isVisible){paddingsChanged|=checkAnchorPaddingsChanged(a,paddings,child);positionChildNormal(a,child);updateSide(a,child)}return paddingsChanged}finally{if(useLog){me._groupEnd()}}}function layoutChildFill(child,canChange){var paddingsChanged=0;var a=child.anchor;childKeyArgs.paddings=filterAnchorPaddings(a,paddings);childKeyArgs.canChange=canChange;child.layout(new pvc.Size(remSize),childKeyArgs);if(child.isVisible){paddingsChanged|=checkAnchorPaddingsChanged(a,paddings,child,canChange);positionChildNormal(a,child);positionChildOrtho(child,a)}return paddingsChanged}function layoutChild2Side(child,canChange){var paddingsChanged=0;if(child.isVisible){var a=child.anchor;var al=alMap[a];var aol=aolMap[a];var length=remSize[al];var olength=child[aol];var childSize2=new pvc.Size(def.set({},al,length,aol,olength));childKeyArgs.paddings=filterAnchorPaddings(a,paddings);childKeyArgs.canChange=canChange;child.layout(childSize2,childKeyArgs);if(child.isVisible){paddingsChanged=checkAnchorPaddingsChanged(a,paddings,child,canChange)|checkOverflowPaddingsChanged(a,layoutInfo.paddings,child,canChange);if(!paddingsChanged){positionChildOrtho(child,child.align)}}}return paddingsChanged}function positionChildNormal(side,child){var sidePos;if(side==='fill'){side='left';sidePos=margins.left+remSize.width/2-(child.width/2)}else{sidePos=margins[side]}child.setPosition(def.set({},side,sidePos))}function updateSide(side,child){var sideol=aolMap[side],olen=child[sideol];margins[side]+=olen;remSize[sideol]-=olen}function positionChildOrtho(child,align){var sideo;if(align==='fill'){align='middle'}var sideOPos;switch(align){case'top':case'bottom':case'left':case'right':sideo=align;sideOPos=margins[sideo];break;case'middle':sideo='bottom';sideOPos=margins.bottom+(remSize.height/2)-(child.height/2);break;case'center':sideo='left';sideOPos=margins.left+remSize.width/2-(child.width/2);break}child.setPosition(def.set({},sideo,sideOPos))}function filterAnchorPaddings(a,paddings){var filtered=new pvc.Sides();getAnchorPaddingsNames(a).forEach(function(side){filtered.set(side,paddings[side])});return filtered}function checkAnchorPaddingsChanged(a,paddings,child,canChange){var newPaddings=child._layoutInfo.requestPaddings;var changed=0;if(newPaddings){if(useLog&&pvc.debug>=10){me._log("=> clientSize="+pvc.stringify(child._layoutInfo.clientSize));me._log("<= requestPaddings="+pvc.stringify(newPaddings))}getAnchorPaddingsNames(a).forEach(function(side){var value=paddings[side]||0;var newValue=Math.floor(10000*(newPaddings[side]||0))/10000;var increase=newValue-value;var minChange=Math.max(1,Math.abs(0.01*value));if(increase!==0&&Math.abs(increase)>=minChange){if(!canChange){if(pvc.debug>=2){me._warn("CANNOT change but child wanted to: "+side+"="+newValue)}}else{changed|=NormalPaddingsChanged;paddings[side]=newValue;if(useLog){me._log("Changed padding "+side+" <- "+newValue)}}}});if(changed){var paddingKey=pvc.Sides.names.map(function(side){return(paddings[side]||0).toFixed(0)}).join('|');if(def.hasOwn(paddingHistory,paddingKey)){if(pvc.debug>=2){me._warn("LOOP detected!!!!")}changed|=LoopDetected}else{paddingHistory[paddingKey]=true}paddings.width=paddings.left+paddings.right;paddings.height=paddings.top+paddings.bottom}}return changed}function checkOverflowPaddingsChanged(a,ownPaddings,child,canChange){var overflowPaddings=child._layoutInfo.overflowPaddings||emptyNewPaddings;var changed=0;if(useLog&&pvc.debug>=10){me._log("<= overflowPaddings="+pvc.stringify(overflowPaddings))}getAnchorPaddingsNames(a).forEach(function(side){if(overflowPaddings.hasOwnProperty(side)){var value=ownPaddings[side]||0;var newValue=Math.floor(10000*(overflowPaddings[side]||0))/10000;newValue-=margins[side];var increase=newValue-value;var minChange=Math.max(1,Math.abs(0.05*value));if(increase>=minChange){if(!canChange){if(pvc.debug>=2){me._warn("CANNOT change overflow padding but child wanted to: "+side+"="+newValue)}}else{changed|=OverflowPaddingsChanged;ownPaddings[side]=newValue;if(useLog){me._log("changed overflow padding "+side+" <- "+newValue)}}}}});if(changed){ownPaddings.width=ownPaddings.left+ownPaddings.right;ownPaddings.height=ownPaddings.top+ownPaddings.bottom}return changed}function getAnchorPaddingsNames(a){switch(a){case'left':case'right':return pvc.Sides.vnames;case'top':case'bottom':return pvc.Sides.hnames;case'fill':return pvc.Sides.names}}}});
def.type('pvc.CartesianGridDockingPanel',pvc.GridDockingPanel).init(function(chart,parent,options){this.base(chart,parent,options);this._plotBgPanel=new pvc.PlotBgPanel(chart,this)}).add({_getExtensionId:function(){return!this.chart.parent?'content':'smallContent'},_createCore:function(layoutInfo){var chart=this.chart;var axes=chart.axes;var xAxis=axes.x;var yAxis=axes.y;if(xAxis.option('Visible')&&xAxis.option('Grid')){this.xGridRule=this._createGridRule(xAxis)}if(yAxis.option('Visible')&&yAxis.option('Grid')){this.yGridRule=this._createGridRule(yAxis)}this.base(layoutInfo);if(chart.focusWindow){this._createFocusWindow(layoutInfo)}var plotFrameVisible;if(chart.compatVersion()<=1){plotFrameVisible=!!(xAxis.option('EndLine')||yAxis.option('EndLine'))}else{plotFrameVisible=def.get(chart.options,'plotFrameVisible',true)}if(plotFrameVisible){this.pvFrameBar=this._createFrame(layoutInfo,axes)}if(xAxis.scaleType!=='discrete'&&xAxis.option('ZeroLine')){this.xZeroLine=this._createZeroLine(xAxis,layoutInfo)}if(yAxis.scaleType!=='discrete'&&yAxis.option('ZeroLine')){this.yZeroLine=this._createZeroLine(yAxis,layoutInfo)}},_createGridRule:function(axis){var scale=axis.scale;if(scale.isNull){return}var isDiscrete=axis.role.grouping.isDiscrete();var axisPanel=this.chart.axesPanels[axis.id];var rootScene=axisPanel._getRootScene();if(!rootScene){return}var margins=this._layoutInfo.gridMargins;var paddings=this._layoutInfo.gridPaddings;var tick_a=axis.orientation==='x'?'left':'bottom';var len_a=this.anchorLength(tick_a);var obeg_a=this.anchorOrtho(tick_a);var oend_a=this.anchorOpposite(obeg_a);var tick_offset=margins[tick_a]+paddings[tick_a];var obeg=margins[obeg_a];var oend=margins[oend_a];var tickScenes=rootScene.leafs().array();var tickCount=tickScenes.length;if(isDiscrete&&tickCount){tickScenes.push(tickScenes[tickCount-1])}var wrapper;if(this.compatVersion()<=1){wrapper=function(v1f){return function(tickScene){return v1f.call(this,tickScene.vars.tick.rawValue)}}}var pvGridRule=new pvc.visual.Rule(this,this.pvPanel,{extensionId:axis.extensionPrefixes.map(function(prefix){return prefix+'Grid'}),wrapper:wrapper}).lock('data',tickScenes).lock(len_a,null).override('defaultColor',function(){return pv.color("#f0f0f0")}).pvMark.lineWidth(1).antialias(true)[obeg_a](obeg)[oend_a](oend).zOrder(-12).events('none');if(isDiscrete){var halfStep=scale.range().step/2;pvGridRule.lock(tick_a,function(tickScene){var tickPosition=tick_offset+scale(tickScene.vars.tick.value);var isLastLine=this.index===tickCount;return tickPosition+(isLastLine?halfStep:-halfStep)})}else{pvGridRule.lock(tick_a,function(tickScene){return tick_offset+scale(tickScene.vars.tick.value)})}return pvGridRule},_createFrame:function(layoutInfo,axes){if(axes.base.scale.isNull||(axes.ortho.scale.isNull&&(!axes.ortho2||axes.ortho2.scale.isNull))){return}var margins=layoutInfo.gridMargins;var left=margins.left;var right=margins.right;var top=margins.top;var bottom=margins.bottom;var extensionIds=[];if(this.compatVersion()<=1){extensionIds.push('xAxisEndLine');extensionIds.push('yAxisEndLine')}extensionIds.push('plotFrame');return new pvc.visual.Panel(this,this.pvPanel,{extensionId:extensionIds}).pvMark.lock('left',left).lock('right',right).lock('top',top).lock('bottom',bottom).lock('fillStyle',null).events('none').strokeStyle("#666666").lineWidth(1).antialias(false).zOrder(-8)},_createZeroLine:function(axis,layoutInfo){var scale=axis.scale;if(!scale.isNull){var domain=scale.domain();if(domain[0]*domain[1]<-1e-12){var a=axis.orientation==='x'?'left':'bottom';var len_a=this.anchorLength(a);var obeg_a=this.anchorOrtho(a);var oend_a=this.anchorOpposite(obeg_a);var margins=layoutInfo.gridMargins;var paddings=layoutInfo.gridPaddings;var zeroPosition=margins[a]+paddings[a]+scale(0);var obeg=margins[obeg_a];var oend=margins[oend_a];var rootScene=new pvc.visual.Scene(null,{panel:this});return new pvc.visual.Rule(this,this.pvPanel,{extensionId:axis.extensionPrefixes.map(function(prefix){return prefix+'ZeroLine'})}).lock('data',[rootScene]).lock(len_a,null).lock(obeg_a,obeg).lock(oend_a,oend).lock(a,zeroPosition).override('defaultColor',function(){return pv.color("#666666")}).pvMark.events('none').lineWidth(1).antialias(true).zOrder(-9)}}},_createFocusWindow:function(layoutInfo){var me=this;var topRoot=me.topRoot;var chart=me.chart;var focusWindow=chart.focusWindow.base;var axis=focusWindow.axis;var scale=axis.scale;if(scale.isNull){return}var resizable=focusWindow.option('Resizable');var movable=focusWindow.option('Movable');var isDiscrete=axis.isDiscrete();var isV=chart.isOrientationVertical();var a_left=isV?'left':'top';var a_top=isV?'top':'left';var a_width=me.anchorOrthoLength(a_left);var a_right=me.anchorOpposite(a_left);var a_height=me.anchorOrthoLength(a_top);var a_bottom=me.anchorOpposite(a_top);var a_x=isV?'x':'y';var a_dx='d'+a_x;var a_y=isV?'y':'x';var a_dy='d'+a_y;var margins=layoutInfo.gridMargins;var paddings=layoutInfo.gridPaddings;var space={left:margins.left+paddings.left,right:margins.right+paddings.right,top:margins.top+paddings.top,bottom:margins.bottom+paddings.bottom};space.width=space.left+space.right;space.height=space.top+space.bottom;var clientSize=layoutInfo.clientSize;var wf=clientSize[a_width];var hf=clientSize[a_height];var w=wf-space[a_width];var h=hf-space[a_height];var padLeft=paddings[a_left];var padRight=paddings[a_right];var scene=new pvc.visual.Scene(null,{panel:this});var band=isDiscrete?scale.range().step:0;var halfBand=band/2;scene[a_x]=scale(focusWindow.begin)-halfBand,scene[a_dx]=band+(scale(focusWindow.end)-halfBand)-scene[a_x],resetSceneY();function resetSceneY(){scene[a_y]=0-paddings[a_top];scene[a_dy]=h+paddings[a_top]+paddings[a_bottom]}var sceneProp=function(p){return function(){return scene[p]}};var boundLeft=function(){var begin=scene[a_x];return Math.max(0,Math.min(w,begin))};var boundWidth=function(){var begin=boundLeft();var end=scene[a_x]+scene[a_dx];end=Math.max(0,Math.min(w,end));return end-begin};var addSelBox=function(panel,id){return new pvc.visual.Bar(me,panel,{extensionId:id,normalStroke:true,noHover:true,noSelect:true,noClick:true,noDoubleClick:true,noTooltip:true,showsInteraction:false}).pvMark.lock('data').lock('visible').lock(a_left,boundLeft).lock(a_width,boundWidth).lock(a_top,sceneProp(a_y)).lock(a_height,sceneProp(a_dy)).lock(a_bottom).lock(a_right).sign};var baseBgPanel=this._plotBgPanel.pvPanel.borderPanel;baseBgPanel.lock('data',[scene]);if(movable&&resizable){baseBgPanel.paddingPanel.lock('events','all').lock('cursor','crosshair').event('mousedown',pv.Behavior.select().autoRender(false).collapse(isV?'y':'x').positionConstraint(function(drag){var op=drag.phase==='start'?'new':'resize-end';return positionConstraint(drag,op)})).event('selectstart',function(ev){resetSceneY();onDrag(ev)}).event('select',onDrag).event('selectend',onDrag)}else{baseBgPanel.paddingPanel.events('all')}var focusBg=addSelBox(baseBgPanel.paddingPanel,'focusWindowBg').override('defaultColor',function(type){return pvc.invisibleFill}).pvMark;if(movable){focusBg.lock('events','all').lock('cursor','move').event("mousedown",pv.Behavior.drag().autoRender(false).collapse(isV?'y':'x').positionConstraint(function(drag){positionConstraint(drag,'move')})).event("drag",onDrag).event("dragend",onDrag)}else{focusBg.events('none')}var baseFgPanel=new pvc.visual.Panel(me,me.pvPanel).pvMark.lock('data',[scene]).lock('visible').lock('fillStyle',pvc.invisibleFill).lock('left',space.left).lock('right',space.right).lock('top',space.top).lock('bottom',space.bottom).lock('zOrder',10).lock('events',function(){var drag=scene.drag;return drag&&drag.phase!=='end'?'all':'none'}).lock('cursor',function(){var drag=scene.drag;return drag&&drag.phase!=='end'?((drag.type==='drag'||(drag.type==='select'&&!resizable))?'move':(isV?'ew-resize':'ns-resize')):null}).antialias(false);var curtainFillColor='rgba(20, 20, 20, 0.1)';new pvc.visual.Bar(me,baseFgPanel,{extensionId:'focusWindowBaseCurtain',normalStroke:true,noHover:true,noSelect:true,noClick:true,noDoubleClick:true,noTooltip:true,showsInteraction:false}).override('defaultColor',function(type){return type==='stroke'?null:curtainFillColor}).pvMark.lock('data',[scene,scene]).lock('visible').lock('events','none').lock(a_left,function(){return!this.index?-padLeft:boundLeft()+boundWidth()}).lock(a_right,function(){return!this.index?null:-padRight}).lock(a_width,function(){return!this.index?padLeft+boundLeft():null}).lock(a_top,sceneProp(a_y)).lock(a_height,sceneProp(a_dy)).lock(a_bottom);var selectBoxFg=addSelBox(baseFgPanel,'focusWindow').override('defaultColor',function(type){return null}).pvMark.lock('events','none');var addResizeSideGrip=function(side){var a_begin=(side==='left'||side==='top')?'begin':'end';var opposite=me.anchorOpposite(side);var fillColor='linear-gradient(to '+opposite+', '+curtainFillColor+', #444 90%)';var grip=new pvc.visual.Bar(me,selectBoxFg.anchor(side),{extensionId:focusWindow.id+'Grip'+def.firstUpperCase(a_begin),normalStroke:true,noHover:true,noSelect:true,noClick:true,noDoubleClick:true,noTooltip:true,showsInteraction:false}).override('defaultColor',function(type){return type==='stroke'?null:fillColor}).pvMark.lock('data').lock('visible')[a_top](scene[a_y])[a_height](scene[a_dy]);if(resizable){var opId='resize-'+a_begin;grip.lock('events','all')[a_width](5).cursor(isV?'ew-resize':'ns-resize').event("mousedown",pv.Behavior.resize(side).autoRender(false).positionConstraint(function(drag){positionConstraint(drag,opId)}).preserveOrtho(true)).event("resize",onDrag).event("resizeend",onDrag)}else{grip.events('none')[a_width](1)}return grip};addResizeSideGrip(a_left);addResizeSideGrip(a_right);function onDrag(){var ev=arguments[arguments.length-1];var isEnd=ev.drag.phase==='end';topRoot._isRubberBandSelecting=!isEnd;baseBgPanel.render();baseFgPanel.render();var pbeg=scene[a_x];var pend=scene[a_x]+scene[a_dx];if(!isV){var temp=w-pbeg;pbeg=w-pend;pend=temp}focusWindow._updatePosition(pbeg,pend,isEnd,true)}var a_p=a_x;var a_dp=a_dx;function positionConstraint(drag,op){var m=drag.m;var p=m[a_p];var b,e,l;var l0=scene[a_dp];var target;switch(op){case'new':l=0;target='begin';break;case'resize-begin':l=l0;target='begin';break;case'move':l=l0;target='begin';break;case'resize-end':l=p-scene[a_p];target='end';break}var min=drag.min[a_p];var max=drag.max[a_p];var oper={type:op,target:target,point:p,length:l,length0:l0,min:min,max:max,minView:0,maxView:w};focusWindow._constraintPosition(oper);m[a_p]=oper.point;switch(op){case'resize-begin':oper.max=Math.min(oper.max,scene[a_p]+scene[a_dp]);break;case'resize-end':oper.min=Math.max(oper.min,scene[a_p]);break}drag.min[a_p]=oper.min;drag.max[a_p]=oper.max}},_getOrthoAxis:function(type){var orthoType=type==='base'?'ortho':'base';return this.chart.axes[orthoType]},_getDatumsOnRect:function(datumMap,rect,keyArgs){var chart=this.chart,xAxisPanel=chart.axesPanels.x,yAxisPanel=chart.axesPanels.y,xDatumMap,yDatumMap;if(xAxisPanel){xDatumMap=new def.Map();xAxisPanel._getDatumsOnRect(xDatumMap,rect,keyArgs);if(!xDatumMap.count){xDatumMap=null}}if(yAxisPanel){yDatumMap=new def.Map();yAxisPanel._getOwnDatumsOnRect(yDatumMap,rect,keyArgs);if(!yDatumMap.count){yDatumMap=null}}if(xDatumMap&&yDatumMap){xDatumMap.intersect(yDatumMap,datumMap);keyArgs.toggle=true}else if(xDatumMap){datumMap.copy(xDatumMap)}else if(yDatumMap){datumMap.copy(yDatumMap)}else{chart.plotPanelList.forEach(function(plotPanel){plotPanel._getDatumsOnRect(datumMap,rect,keyArgs)},this)}}});
def.type('pvc.CartesianAbstractPanel',pvc.PlotPanel).init(function(chart,parent,plot,options){this.base(chart,parent,plot,options);var axes=this.axes;function addAxis(axis){axes[axis.type]=axis;axes[axis.orientedId]=axis;if(axis.v1SecondOrientedId){axes[axis.v1SecondOrientedId]=axis}}addAxis(chart._getAxis('base',plot.option('BaseAxis')-1));addAxis(chart._getAxis('ortho',plot.option('OrthoAxis')-1));var pctPaddings={};var hasAny=false;function setSide(side,pct){var value=pctPaddings[side];if(value==null||pct>value){hasAny=true;pctPaddings[side]=pct}}function processAxis(axis){var offset=axis&&axis.option('Offset');if(offset!=null&&offset>0&&offset<1){if(axis.orientation==='x'){setSide('left',offset);setSide('right',offset)}else{setSide('top',offset);setSide('bottom',offset)}}}var chartAxes=chart.axesByType;['base','ortho'].forEach(function(type){var typeAxes=chartAxes[type];if(typeAxes){typeAxes.forEach(processAxis)}});if(hasAny){this.offsetPaddings=pctPaddings}}).add({offsetPaddings:null,_calcLayout:function(layoutInfo){layoutInfo.requestPaddings=this._calcRequestPaddings(layoutInfo)},_calcRequestPaddings:function(layoutInfo){var reqPads;var offPads=this.offsetPaddings;if(offPads){var tickRoundPads=this.chart._getAxesRoundingPaddings();var clientSize=layoutInfo.clientSize;var pads=layoutInfo.paddings;pvc.Sides.names.forEach(function(side){var len_a=pvc.BasePanel.orthogonalLength[side];var clientLen=clientSize[len_a];var paddingLen=pads[len_a];var len=clientLen+paddingLen;if(!tickRoundPads[side+'Locked']){var offLen=len*(offPads[side]||0);var roundLen=clientLen*(tickRoundPads[side]||0);(reqPads||(reqPads={}))[side]=Math.max(offLen-roundLen,0)}},this)}return reqPads},_createCore:function(){this.pvPanel.zOrder(-10);var hideOverflow;var contentOverflow=this.chart.options.leafContentOverflow||'auto';if(contentOverflow==='auto'){hideOverflow=def.query(['ortho','base']).select(function(axisType){return this.axes[axisType]},this).any(function(axis){return axis.option('FixedMin')!=null||axis.option('FixedMax')!=null})}else{hideOverflow=(contentOverflow==='hidden')}if(hideOverflow){this.pvPanel.borderPanel.overflow('hidden')}}});
def.type('pvc.PlotBgPanel',pvc.BasePanel).init(function(chart,parent,options){this.base(chart,parent,options)}).add({anchor:'fill',_getExtensionId:function(){return'plotBg'},_createCore:function(layoutInfo){this.pvPanel.borderPanel.lock('zOrder',-13).antialias(false);this.base(layoutInfo)}});
def.type('pvc.CategoricalAbstract',pvc.CartesianAbstract).init(function(options){this.base(options);var parent=this.parent;if(parent){this._catRole=parent._catRole}}).add({_initVisualRoles:function(){this.base();this._catRole=this._addVisualRole('category',this._getCategoryRoleSpec())},_getCategoryRoleSpec:function(){return{isRequired:true,defaultDimension:'category*',autoCreateDimension:true}},_generateTrendsDataCellCore:function(newDatums,dataCell,trendInfo){var serRole=this._serRole;var xRole=this._catRole;var yRole=dataCell.role;var trendOptions=dataCell.trend;this._warnSingleContinuousValueRole(yRole);var dataPartDimName=this._dataPartRole.firstDimensionName();var yDimName=yRole.firstDimensionName();var xDimName;var isXDiscrete=xRole.isDiscrete();if(!isXDiscrete){xDimName=xRole.firstDimensionName()}var sumKeyArgs={zeroIfNone:false};var ignoreNullsKeyArgs={ignoreNulls:false};var data=this.visibleData(dataCell.dataPartValue);var allPartsData=this.visibleData(null,ignoreNullsKeyArgs);var allCatDataRoot=allPartsData.flattenBy(xRole,ignoreNullsKeyArgs);var allCatDatas=allCatDataRoot._children;def.scope(function(){return(serRole&&serRole.isBound())?data.flattenBy(serRole).children():def.query([null])}).each(genSeriesTrend,this);function genSeriesTrend(serData1){var funX=isXDiscrete?null:function(allCatData){return allCatData.atoms[xDimName].value};var funY=function(allCatData){var group=data._childrenByKey[allCatData.key];if(group&&serData1){group=group._childrenByKey[serData1.key]}return group?group.dimensions(yDimName).sum(sumKeyArgs):null};var options=def.create(trendOptions,{rows:def.query(allCatDatas),x:funX,y:funY});var trendModel=trendInfo.model(options);var dataPartAtom=data.owner.dimensions(dataPartDimName).intern(this.root._firstTrendAtomProto);if(trendModel){allCatDatas.forEach(function(allCatData,index){var trendX=isXDiscrete?index:allCatData.atoms[xDimName].value;var trendY=trendModel.sample(trendX,funY(allCatData),index);if(trendY!=null){var catData=data._childrenByKey[allCatData.key];var efCatData=catData||allCatData;var atoms;if(serData1){var catSerData=catData&&catData._childrenByKey[serData1.key];if(catSerData){atoms=Object.create(catSerData._datums[0].atoms)}else{atoms=Object.create(efCatData._datums[0].atoms);def.copyOwn(atoms,serData1.atoms)}}else{atoms=Object.create(efCatData._datums[0].atoms)}atoms[yDimName]=trendY;atoms[dataPartDimName]=dataPartAtom;var newDatum=new pvc.data.Datum(efCatData.owner,atoms);newDatum.isVirtual=true;newDatum.isTrend=true;newDatum.trendType=trendInfo.type;newDatums.push(newDatum)}},this)}}},_interpolateDataCell:function(dataCell){var nullInterpMode=dataCell.nullInterpolationMode;if(nullInterpMode){var InterpType;switch(dataCell.nullInterpolationMode){case'linear':InterpType=pvc.data.LinearInterpolationOper;break;case'zero':InterpType=pvc.data.ZeroInterpolationOper;break;case'none':break;default:throw def.error.argumentInvalid('nullInterpolationMode',''+nullInterpMode)}if(InterpType){this._warnSingleContinuousValueRole(dataCell.role);var visibleData=this.visibleData(dataCell.dataPartValue);if(visibleData.childCount()>0){var allPartsData=this.visibleData(null,{ignoreNulls:false});new InterpType(allPartsData,visibleData,this._catRole,this._serRole,dataCell.role,true).interpolate()}}}},_createVisibleData:function(dataPartValue,keyArgs){var serGrouping=this._serRole&&this._serRole.flattenedGrouping();var catGrouping=this._catRole.flattenedGrouping();var partData=this.partData(dataPartValue);var ignoreNulls=def.get(keyArgs,'ignoreNulls');var groupKeyArgs={visible:true,isNull:ignoreNulls?false:null};return serGrouping?partData.groupBy([catGrouping,serGrouping],groupKeyArgs):partData.groupBy(catGrouping,groupKeyArgs)},_getContinuousVisibleCellExtent:function(valueAxis,valueDataCell){var valueRole=valueDataCell.role;switch(valueRole.name){case'series':case'category':return this.base(valueAxis,valueDataCell)}this._warnSingleContinuousValueRole(valueRole);var dataPartValue=valueDataCell.dataPartValue;var valueDimName=valueRole.firstDimensionName();var data=this.visibleData(dataPartValue);var useAbs=valueAxis.scaleUsesAbs();if(valueAxis.type!=='ortho'||!valueDataCell.isStacked){return data.leafs().select(function(serGroup){var value=serGroup.dimensions(valueDimName).sum();return useAbs&&value<0?-value:value}).range()}return data.children().select(function(catGroup){var range=this._getStackedCategoryValueExtent(catGroup,valueDimName,useAbs);if(range){return{range:range,group:catGroup}}},this).where(def.notNully).reduce(function(result,rangeInfo){return this._reduceStackedCategoryValueExtent(result,rangeInfo.range,rangeInfo.group)}.bind(this),null)},_getStackedCategoryValueExtent:function(catGroup,valueDimName,useAbs){var posSum=null,negSum=null;catGroup.children().select(function(serGroup){var value=serGroup.dimensions(valueDimName).sum();return useAbs&&value<0?-value:value}).each(function(value){if(value!=null){if(value>=0){posSum+=value}else{negSum+=value}}});if(posSum==null&&negSum==null){return null}return{max:posSum||0,min:negSum||0}},_reduceStackedCategoryValueExtent:function(result,catRange,catGroup){return pvc.unionExtents(result,catRange)},_coordinateSmallChartsLayout:function(scopesByType){this.base(scopesByType);var titleSizeMax=0;var titleOrthoLen;var axisIds=null;var sizesMaxByAxisId={};this.children.forEach(function(childChart){childChart.basePanel.layout();var size;var panel=childChart.titlePanel;if(panel){if(!titleOrthoLen){titleOrthoLen=panel.anchorOrthoLength()}size=panel[titleOrthoLen];if(size>titleSizeMax){titleSizeMax=size}}var axesPanels=childChart.axesPanels;if(!axisIds){axisIds=def.query(def.ownKeys(axesPanels)).where(function(alias){return alias===axesPanels[alias].axis.id}).select(function(id){sizesMaxByAxisId[id]={axis:0,title:0};return id}).array()}axisIds.forEach(function(id){var axisPanel=axesPanels[id];var sizes=sizesMaxByAxisId[id];var ol=axisPanel.axis.orientation==='x'?'height':'width';size=axisPanel[ol];if(size>sizes.axis){sizes.axis=size}var titlePanel=axisPanel.titlePanel;if(titlePanel){size=titlePanel[ol];if(size>sizes.title){sizes.title=size}}})},this);this.children.forEach(function(childChart){if(titleSizeMax>0){var panel=childChart.titlePanel;panel.size=panel.size.clone().set(titleOrthoLen,titleSizeMax)}var axesPanels=childChart.axesPanels;axisIds.forEach(function(id){var axisPanel=axesPanels[id];var sizes=sizesMaxByAxisId[id];var ol=axisPanel.axis.orientation==='x'?'height':'width';axisPanel.size=axisPanel.size.clone().set(ol,sizes.axis);var titlePanel=axisPanel.titlePanel;if(titlePanel){titlePanel.size=titlePanel.size.clone().set(ol,sizes.title)}});childChart.basePanel.invalidateLayout()},this)},defaults:{orthoAxisOrdinal:false}});
def.type('pvc.CategoricalAbstractPanel',pvc.CartesianAbstractPanel).init(function(chart,parent,plot,options){this.base(chart,parent,plot,options);this.stacked=plot.option('Stacked')});
def.type('pvc.AxisPanel',pvc.BasePanel).init(function(chart,parent,axis,options){options=def.create(options,{anchor:axis.option('Position')});var anchor=options.anchor||this.anchor;this.axis=axis;this.base(chart,parent,options);this.roleName=axis.role.name;this.isDiscrete=axis.role.isDiscrete();this._extensionPrefix=axis.extensionPrefixes;if(this.labelSpacingMin==null){this.labelSpacingMin=this.isDiscrete?0.1:1.5}if(this.showTicks==null){this.showTicks=!this.isDiscrete}if(options.font===undefined){var extFont=this._getConstantExtension('label','font');if(extFont){this.font=extFont}}if(options.tickLength===undefined){var tickLength=+this._getConstantExtension('ticks',this.anchorOrthoLength(anchor));if(!isNaN(tickLength)&&isFinite(tickLength)){this.tickLength=tickLength}}}).add({pvRule:null,pvTicks:null,pvLabel:null,pvRuleGrid:null,pvScale:null,isDiscrete:false,roleName:null,axis:null,anchor:"bottom",tickLength:6,scale:null,ruleCrossesMargin:true,font:'9px sans-serif',labelSpacingMin:null,domainRoundMode:'none',desiredTickCount:null,tickExponentMin:null,tickExponentMax:null,showMinorTicks:true,showTicks:null,hiddenLabelText:"\u00B7",_isScaleSetup:false,_createLogInstanceId:function(){return this.base()+" - "+this.axis.id},getTicks:function(){return this._layoutInfo&&this._layoutInfo.ticks},_calcLayout:function(layoutInfo){var scale=this.axis.scale;if(!this._isScaleSetup){this.pvScale=scale;this.scale=scale;this.extend(scale,"scale");this._isScaleSetup=true}if(scale.isNull){layoutInfo.axisSize=0}else{this._calcLayoutCore(layoutInfo)}return this.createAnchoredSize(layoutInfo.axisSize,layoutInfo.clientSize)},_calcLayoutCore:function(layoutInfo){var axisSize=layoutInfo.desiredClientSize[this.anchorOrthoLength()];layoutInfo.axisSize=axisSize;if(this.isDiscrete&&this.useCompositeAxis){if(layoutInfo.axisSize==null){layoutInfo.axisSize=50}}else{layoutInfo.textAngle=def.number.as(this._getExtension('label','textAngle'),0);layoutInfo.textMargin=def.number.as(this._getExtension('label','textMargin'),3);this._calcTicks();if(this.scale.type==='discrete'){this._calcDiscreteTicksHidden()}this._calcAxisSizeFromLabel();if(layoutInfo.axisSize==null){layoutInfo.axisSize=layoutInfo.requiredAxisSize}this._calcMaxTextLengthThatFits();this._calcOverflowPaddings()}},_calcAxisSizeFromLabel:function(){this._calcLabelBBox();this._calcAxisSizeFromLabelBBox()},_calcLabelBBox:function(){var layoutInfo=this._layoutInfo;var align=this._getExtension('label','textAlign');if(typeof align!=='string'){align=this.isAnchorTopOrBottom()?"center":(this.anchor=="left")?"right":"left"}var baseline=this._getExtension('label','textBaseline');if(typeof baseline!=='string'){switch(this.anchor){case"right":case"left":case"center":baseline="middle";break;case"bottom":baseline="top";break;default:baseline="bottom"}}return(layoutInfo.labelBBox=pvc.text.getLabelBBox(layoutInfo.maxTextWidth!=null?layoutInfo.maxTextWidth:layoutInfo._maxTextWidth,layoutInfo.textHeight,align,baseline,layoutInfo.textAngle,layoutInfo.textMargin))},_calcAxisSizeFromLabelBBox:function(){var layoutInfo=this._layoutInfo;var labelBBox=layoutInfo.labelBBox;var length=this._getLabelBBoxQuadrantLength(labelBBox,this.anchor);var axisSize=this.tickLength+length;var angle=labelBBox.sourceAngle;if(!(angle===0&&this.isAnchorTopOrBottom())){axisSize+=this.tickLength}layoutInfo.requiredAxisSize=axisSize},_getLabelBBoxQuadrantLength:function(labelBBox,quadrantSide){var length;switch(quadrantSide){case'left':length=-labelBBox.x;break;case'right':length=labelBBox.x2;break;case'top':length=-labelBBox.y;break;case'bottom':length=labelBBox.y2;break}return Math.max(length,0)},_calcOverflowPaddings:function(){if(!this._layoutInfo.canChange){if(pvc.debug>=2){this._log("[WARNING] Layout cannot change. Skipping calculation of overflow paddings.")}return}if(!this._layoutInfo.labelBBox){this._calcLabelBBox()}this._calcOverflowPaddingsFromLabelBBox()},_calcOverflowPaddingsFromLabelBBox:function(){var overflowPaddings=null;var layoutInfo=this._layoutInfo;var ticks=layoutInfo.ticks;var tickCount=ticks.length;if(tickCount){var paddings=layoutInfo.paddings;var labelBBox=layoutInfo.labelBBox;var isTopOrBottom=this.isAnchorTopOrBottom();var begSide=isTopOrBottom?'left':'top';var endSide=isTopOrBottom?'right':'bottom';var isDiscrete=this.scale.type==='discrete';var clientLength=layoutInfo.clientSize[this.anchorLength()];this.axis.setScaleRange(clientLength);var sideTickOffset;if(isDiscrete){var halfBand=this.scale.range().step/2; sideTickOffset=def.set({},begSide,halfBand,endSide,halfBand)}else{sideTickOffset=def.set({},begSide,this.scale(ticks[0]),endSide,clientLength-this.scale(ticks[tickCount-1]))}[begSide,endSide].forEach(function(side){var overflowPadding=this._getLabelBBoxQuadrantLength(labelBBox,side);if(overflowPadding>0){overflowPadding-=(paddings[side]||0);if(overflowPadding>0){overflowPadding-=sideTickOffset[side];if(overflowPadding>1){if(isDiscrete){overflowPadding*=1.05}if(!overflowPaddings){overflowPaddings={}}overflowPaddings[side]=overflowPadding}}}},this);if(pvc.debug>=6&&overflowPaddings){this._log("OverflowPaddings = "+pvc.stringify(overflowPaddings))}}layoutInfo.overflowPaddings=overflowPaddings},_calcMaxTextLengthThatFits:function(){var layoutInfo=this._layoutInfo;if(this.compatVersion()<=1){layoutInfo.maxTextWidth=null;return}var availableClientLength=layoutInfo.clientSize[this.anchorOrthoLength()];var efSize=Math.min(layoutInfo.axisSize,availableClientLength);if(efSize>=(layoutInfo.requiredAxisSize-this.tickLength)){layoutInfo.maxTextWidth=null}else{var labelBBox=layoutInfo.labelBBox;var maxOrthoLength=efSize-2*this.tickLength;var mostOrthoDistantPoint;var parallelDirection;switch(this.anchor){case'left':parallelDirection=pv.vector(0,1);mostOrthoDistantPoint=pv.vector(-maxOrthoLength,0);break;case'right':parallelDirection=pv.vector(0,1);mostOrthoDistantPoint=pv.vector(maxOrthoLength,0);break;case'top':parallelDirection=pv.vector(1,0);mostOrthoDistantPoint=pv.vector(0,-maxOrthoLength);break;case'bottom':parallelDirection=pv.vector(1,0);mostOrthoDistantPoint=pv.vector(0,maxOrthoLength);break}var orthoOutwardsDir=mostOrthoDistantPoint.norm();var corners=labelBBox.source.points();var botL=corners[0];var botR=corners[1];var topR=corners[2];var topL=corners[3];var topLRSideDir=topR.minus(topL);var botLRSideDir=botR.minus(botL);var intersect=pv.SvgScene.lineIntersect;var botI=intersect(mostOrthoDistantPoint,parallelDirection,botL,botLRSideDir);var topI=intersect(mostOrthoDistantPoint,parallelDirection,topL,topLRSideDir);var sideLRWidth=labelBBox.sourceTextWidth;var maxTextWidth=sideLRWidth;var botLI=botI.minus(botL);var botLILen=botLI.length();if(botLILen<=sideLRWidth&&botLI.dot(topLRSideDir)>=0){if(botL.dot(orthoOutwardsDir)<botR.dot(orthoOutwardsDir)){maxTextWidth=botLILen}else{maxTextWidth=botI.minus(botR).length()}}var topLI=topI.minus(topL);var topLILen=topLI.length();if(topLILen<=sideLRWidth&&topLI.dot(topLRSideDir)>=0){if(topL.dot(orthoOutwardsDir)<topR.dot(orthoOutwardsDir)){maxTextWidth=Math.min(maxTextWidth,topLILen)}else{maxTextWidth=Math.min(maxTextWidth,topI.minus(topR).length())}}if(labelBBox.sourceAlign==='center'){var cutWidth=sideLRWidth-maxTextWidth;maxTextWidth-=cutWidth}layoutInfo.maxTextWidth=maxTextWidth;if(pvc.debug>=3){this._log("Trimming labels' text at length "+maxTextWidth.toFixed(2)+"px maxOrthoLength="+maxOrthoLength.toFixed(2)+"px")}}},_calcTicks:function(){var layoutInfo=this._layoutInfo;layoutInfo.textHeight=pv.Text.fontHeight(this.font);layoutInfo.maxTextWidth=null;this.axis.setTicks(null);switch(this.scale.type){case'discrete':this._calcDiscreteTicks();break;case'timeSeries':this._calcTimeSeriesTicks();break;case'numeric':this._calcNumberTicks(layoutInfo);break;default:throw def.error.operationInvalid("Undefined axis scale type")}this.axis.setTicks(layoutInfo.ticks);var clientLength=layoutInfo.clientSize[this.anchorLength()];this.axis.setScaleRange(clientLength);if(layoutInfo.maxTextWidth==null){layoutInfo.maxTextWidth=def.query(layoutInfo.ticksText).select(function(text){return pv.Text.measure(text,this.font).width},this).max()}layoutInfo._maxTextWidth=layoutInfo.maxTextWidth},_calcDiscreteTicks:function(){var layoutInfo=this._layoutInfo;var role=this.chart.visualRoles(this.roleName);var data=role.flatten(this.chart.data,{visible:true});layoutInfo.data=data;layoutInfo.ticks=data._children;var format,dimType;var grouping=role.grouping;if(grouping.isSingleDimension&&(dimType=grouping.firstDimensionType())&&(dimType.valueType===Date)){var extent=data.dimensions(dimType.name).extent();if(extent&&extent.min!==extent.max){var scale=new pv.Scale.linear(extent.min.value,extent.max.value);scale.ticks();var tickFormatter=this.axis.option('TickFormatter');if(tickFormatter){scale.tickFormatter(tickFormatter)}format=function(child){return scale.tickFormat(child.value)}}}if(!format){format=function(child){return child.absLabel}}layoutInfo.ticksText=data._children.map(format)},_calcTimeSeriesTicks:function(){this._calcContinuousTicks(this._layoutInfo)},_calcNumberTicks:function(){var desiredTickCount=this.desiredTickCount;if(desiredTickCount==null){if(this.isAnchorTopOrBottom()){this._calcNumberHTicks();return}desiredTickCount=this._calcNumberVDesiredTickCount()}this._calcContinuousTicks(this._layoutInfo,desiredTickCount)},_calcContinuousTicks:function(ticksInfo,desiredTickCount){this._calcContinuousTicksValue(ticksInfo,desiredTickCount);this._calcContinuousTicksText(ticksInfo)},_calcContinuousTicksValue:function(ticksInfo,desiredTickCount){ticksInfo.ticks=this.scale.ticks(desiredTickCount,{roundInside:this.domainRoundMode!=='tick',numberExponentMin:this.tickExponentMin,numberExponentMax:this.tickExponentMax});if(pvc.debug>4){this._log("DOMAIN: "+pvc.stringify(this.scale.domain()));this._log("TICKS:  "+pvc.stringify(ticksInfo.ticks))}},_calcContinuousTicksText:function(ticksInfo){ticksInfo.ticksText=def.query(ticksInfo.ticks).select(function(tick){return this.scale.tickFormat(tick)},this).array()},_calcDiscreteTicksHidden:function(){return this._tickIncludeModulo=this._calcDiscreteTicksHiddenCore()},_calcDiscreteTicksHiddenCore:function(){var mode=this.axis.option('OverlappedLabelsMode');if(mode!=='hide'){return 1}var layoutInfo=this._layoutInfo;var ticks=layoutInfo.ticks;var tickCount=ticks.length;if(tickCount<=1){return 1}var b=this.scale.range().step;var h=layoutInfo.textHeight;var w=layoutInfo.maxTextWidth;if(!(w>0&&h>0&&b>0)){return 1}var sMin=h*this.labelSpacingMin;var a=layoutInfo.textAngle;var isTopOrBottom=this.isAnchorTopOrBottom();var sinOrCos=isTopOrBottom?'sin':'cos';var cosOrSin=!isTopOrBottom?'sin':'cos';var tickIncludeModulo=1;do{var bEf=tickIncludeModulo*b;var sBase=bEf*Math.abs(Math[sinOrCos](a))-h;var sOrtho=bEf*Math.abs(Math[cosOrSin](a))-w;if(sBase>=sMin||sOrtho>=sMin){break}tickIncludeModulo++}while(Math.ceil(tickCount/tickIncludeModulo)>1);if(tickIncludeModulo>1&&pvc.debug>=3){this._log("Showing only one in every "+tickIncludeModulo+" tick labels")}return tickIncludeModulo},_calcNumberVDesiredTickCount:function(){var layoutInfo=this._layoutInfo;var lineHeight=layoutInfo.textHeight*(1+Math.max(0,this.labelSpacingMin));var clientLength=layoutInfo.clientSize[this.anchorLength()];return Math.max(1,~~(clientLength/lineHeight))},_calcNumberHTicks:function(){var layoutInfo=this._layoutInfo;var clientLength=layoutInfo.clientSize[this.anchorLength()];var spacing=layoutInfo.textHeight*Math.max(0,this.labelSpacingMin);var desiredTickCount=this._calcNumberHDesiredTickCount(spacing);var doLog=(pvc.debug>=7);var dir,prevResultTickCount;var ticksInfo,lastBelow,lastAbove;do{if(doLog){this._log("calculateNumberHTicks TickCount IN desired = "+desiredTickCount)}ticksInfo={};this._calcContinuousTicksValue(ticksInfo,desiredTickCount);var ticks=ticksInfo.ticks;var resultTickCount=ticks.length;if(ticks.exponentOverflow){if(dir==null){if(ticks.exponent===this.exponentMin){lastBelow=ticksInfo;dir=1}else{lastAbove=ticksInfo;dir=-1}}else if(dir===1){if(lastBelow){ticksInfo=lastBelow}break}else{if(lastAbove){ticksInfo=lastAbove}break}}else if(prevResultTickCount==null||resultTickCount!==prevResultTickCount){if(doLog){this._log("calculateNumberHTicks TickCount desired/resulting = "+desiredTickCount+" -> "+resultTickCount)}prevResultTickCount=resultTickCount;this._calcContinuousTicksText(ticksInfo);var length=this._calcNumberHLength(ticksInfo,spacing);var excessLength=ticksInfo.excessLength=length-clientLength;var pctError=ticksInfo.error=Math.abs(excessLength/clientLength);if(doLog){this._log("calculateNumberHTicks error="+(excessLength>=0?"+":"-")+(ticksInfo.error*100).toFixed(0)+"% count="+resultTickCount+" step="+ticks.step);this._log("calculateNumberHTicks Length client/resulting = "+clientLength+" / "+length+" spacing = "+spacing)}if(excessLength>0){if(desiredTickCount===1){if(resultTickCount===3&&pctError<=1){ticksInfo.ticks.splice(1,1);ticksInfo.ticksText.splice(1,1);ticksInfo.ticks.step*=2}else{ticksInfo.ticks.length=1;ticksInfo.ticksText.length=1}delete ticksInfo.maxTextWidth;break}if(lastBelow){ticksInfo=lastBelow;break}lastAbove=ticksInfo;dir=-1}else{if(pctError<=0.05||dir===-1){break}lastBelow=ticksInfo;dir=+1}}desiredTickCount+=dir}while(true);if(ticksInfo){layoutInfo.ticks=ticksInfo.ticks;layoutInfo.ticksText=ticksInfo.ticksText;layoutInfo.maxTextWidth=ticksInfo.maxTextWidth;if(pvc.debug>=5){this._log("calculateNumberHTicks RESULT error="+(ticksInfo.excessLength>=0?"+":"-")+(ticksInfo.error*100).toFixed(0)+"% count="+ticksInfo.ticks.length+" step="+ticksInfo.ticks.step)}}if(doLog){this._log("calculateNumberHTicks END")}},_calcNumberHDesiredTickCount:function(spacing){var layoutInfo=this._layoutInfo;var domainTextLength=this.scale.domain().map(function(tick){tick=+tick.toFixed(2);var text=this.scale.tickFormat(tick);return pv.Text.measure(text,this.font).width},this);var avgTextLength=Math.max((domainTextLength[1]+domainTextLength[0])/2,layoutInfo.textHeight);var clientLength=layoutInfo.clientSize[this.anchorLength()];return Math.max(1,~~(clientLength/(avgTextLength+spacing)))},_calcNumberHLength:function(ticksInfo,spacing){var ticksText=ticksInfo.ticksText;var maxTextWidth=def.query(ticksText).select(function(text){return pv.Text.measure(text,this.font).width},this).max();return Math.max(maxTextWidth,(ticksText.length-1)*(maxTextWidth+spacing))},_createCore:function(){if(this.scale.isNull){return}var clientSize=this._layoutInfo.clientSize;var paddings=this._layoutInfo.paddings;var begin_a=this.anchorOrtho();var end_a=this.anchorOpposite(begin_a);var size_a=this.anchorOrthoLength(begin_a);var rMin=this.ruleCrossesMargin?-paddings[begin_a]:0;var rMax=clientSize[size_a]+(this.ruleCrossesMargin?paddings[end_a]:0);var rSize=rMax-rMin;var ruleParentPanel=this.pvPanel;this._rSize=rSize;var rootScene=this._getRootScene();this.pvRule=new pvc.visual.Rule(this,this.pvPanel,{extensionId:'rule'}).lock('data',[rootScene]).override('defaultColor',def.fun.constant("#666666")).lock(this.anchorOpposite(),0).lock(begin_a,rMin).lock(size_a,rSize).pvMark.zOrder(30).strokeDasharray(null).lineCap('square');if(this.isDiscrete){if(this.useCompositeAxis){this.renderCompositeOrdinalAxis()}else{this.renderOrdinalAxis()}}else{this.renderLinearAxis()}},_getExtensionId:function(){return''},_getRootScene:function(){if(!this._rootScene){var rootScene=this._rootScene=new pvc.visual.CartesianAxisRootScene(null,{panel:this,group:this._getRootData()});var layoutInfo=this._layoutInfo;var ticksText=layoutInfo.ticksText;if(this.isDiscrete){if(this.useCompositeAxis){this._buildCompositeScene(rootScene)}else{layoutInfo.ticks.forEach(function(tickData,index){new pvc.visual.CartesianAxisTickScene(rootScene,{group:tickData,tick:tickData.value,tickRaw:tickData.rawValue,tickLabel:ticksText[index]})})}}else{layoutInfo.ticks.forEach(function(majorTick,index){new pvc.visual.CartesianAxisTickScene(rootScene,{tick:majorTick,tickRaw:majorTick,tickLabel:ticksText[index]})},this)}}return this._rootScene},_buildCompositeScene:function(rootScene){var isV1Compat=this.compatVersion()<=1;rootScene.vars.tick=new pvc.visual.ValueLabelVar('',"");recursive(rootScene);function recursive(scene){var data=scene.group;if(isV1Compat){var tickVar=scene.vars.tick;scene.nodeValue=scene.value=tickVar.rawValue;scene.nodeLabel=scene.label=tickVar.label}if(data.childCount()){data.children().each(function(childData){var childScene=new pvc.visual.CartesianAxisTickScene(scene,{group:childData,tick:childData.value,tickRaw:childData.rawValue,tickLabel:childData.label});recursive(childScene)})}}},_getRootData:function(){var chart=this.chart;var data=chart.data;if(this.isDiscrete&&this.useCompositeAxis){var orientation=this.anchor;var reverse=orientation=='bottom'||orientation=='left';data=chart.visualRoles(this.roleName).select(data,{visible:true,reverse:reverse})}return data},_getOrthoScale:function(){var orthoType=this.axis.type==='base'?'ortho':'base';return this.chart.axes[orthoType].scale},_getOrthoAxis:function(){var orthoType=this.axis.type==='base'?'ortho':'base';return this.chart.axes[orthoType]},renderOrdinalAxis:function(){var myself=this,scale=this.scale,hiddenLabelText=this.hiddenLabelText,anchorOpposite=this.anchorOpposite(),anchorLength=this.anchorLength(),anchorOrtho=this.anchorOrtho(),anchorOrthoLength=this.anchorOrthoLength(),layoutInfo=this._layoutInfo,pvRule=this.pvRule,ticks=layoutInfo.ticks,data=layoutInfo.data,itemCount=layoutInfo.ticks.length,rootScene=this._getRootScene(),includeModulo=this._tickIncludeModulo,isV1Compat=this.compatVersion()<=1;rootScene.vars.tickIncludeModulo=includeModulo;rootScene.vars.hiddenLabelText=hiddenLabelText;var wrapper;if(isV1Compat){var DataElement=function(tickVar){this.value=this.absValue=tickVar.rawValue;this.nodeName=''+(this.value||'');this.path=this.nodeName?[this.nodeName]:[];this.label=this.absLabel=tickVar.label};DataElement.prototype.toString=function(){return''+this.value};wrapper=function(v1f){return function(tickScene){var markWrapped=Object.create(this);markWrapped.index=this.parent.index;return v1f.call(markWrapped,new DataElement(tickScene.vars.tick))}}}var pvTicksPanel=new pvc.visual.Panel(this,this.pvPanel,{extensionId:'ticksPanel'}).lock('data',rootScene.childNodes).localProperty('hidden').lockMark('hidden',function(){return(this.index%includeModulo)!==0}).lock(anchorOpposite,0).lockMark(anchorOrtho,function(tickScene){return scale(tickScene.vars.tick.value)}).lock('strokeDasharray',null).lock('strokeStyle',null).lock('fillStyle',null).lock('lineWidth',0).pvMark.zOrder(20);if(isV1Compat||this.showTicks){var pvTicks=this.pvTicks=new pvc.visual.Rule(this,pvTicksPanel,{extensionId:'ticks',wrapper:wrapper}).lock('data').intercept('visible',function(){return!this.pvMark.parent.hidden()&&this.delegateExtension(true)}).optional('lineWidth',1).lock(anchorOpposite,0).lock(anchorOrtho,0).lock(anchorLength,null).optional(anchorOrthoLength,this.tickLength*2/3).override('defaultColor',function(type){if(isV1Compat){return pv.Color.names.transparent}return pvRule.scene?pvRule.scene[0].strokeStyle:"#666666"}).pvMark}var baseline;var align;switch(this.anchor){case'top':align='center';baseline='bottom';break;case'bottom':align='center';baseline='top';break;case'left':align='right';baseline='middle';break;case'right':align='left';baseline='middle';break}var font=this.font;var maxTextWidth=this._layoutInfo.maxTextWidth;if(!isFinite(maxTextWidth)){maxTextWidth=0}this.pvLabel=new pvc.visual.Label(this,pvTicksPanel,{extensionId:'label',noClick:false,noDoubleClick:false,noSelect:false,noTooltip:false,noHover:false,wrapper:wrapper,tooltipArgs:{buildTooltip:function(context){return context.scene.vars.tick.label},isLazy:false,options:{gravity:this._calcTipsyGravity()}}}).intercept('visible',function(tickScene){return!this.pvMark.parent.hidden()?this.delegateExtension(true):!!tickScene.vars.hiddenLabelText}).intercept('text',function(tickScene){var text;if(this.pvMark.parent.hidden()){text=tickScene.vars.hiddenLabelText}else{text=this.delegateExtension();if(text===undefined){text=tickScene.vars.tick.label}if(maxTextWidth){text=pvc.text.trimToWidthB(maxTextWidth,text,font,"..",false)}}return text}).pvMark.zOrder(40).lock(anchorOpposite,this.tickLength).lock(anchorOrtho,0).font(font).textStyle("#666666").textAlign(align).textBaseline(baseline);this._debugTicksPanel(pvTicksPanel)},_debugTicksPanel:function(pvTicksPanel){if(pvc.debug>=16){var corners=this._layoutInfo.labelBBox.source.points();if(corners.length>1){corners=corners.concat(corners[0])}pvTicksPanel.add(pv.Panel)[this.anchorOpposite()](this.tickLength)[this.anchorOrtho()](0)[this.anchorLength()](0)[this.anchorOrthoLength()](0).fillStyle(null).strokeStyle(null).lineWidth(0).add(pv.Line).visible(function(){var gp=this.parent.parent;return!gp.hidden||!gp.hidden()}).data(corners).left(function(p){return p.x}).top(function(p){return p.y}).strokeStyle('red').lineWidth(0.5).strokeDasharray('-')}},renderLinearAxis:function(){var scale=this.scale,orthoAxis=this._getOrthoAxis(),orthoScale=orthoAxis.scale,pvRule=this.pvRule,anchorOpposite=this.anchorOpposite(),anchorLength=this.anchorLength(),anchorOrtho=this.anchorOrtho(),anchorOrthoLength=this.anchorOrthoLength(),rootScene=this._getRootScene();var wrapper;if(this.compatVersion()<=1){wrapper=function(v1f){return function(tickScene){var markWrapped=Object.create(this);markWrapped.index=this.parent.index;return v1f.call(markWrapped,tickScene.vars.tick.rawValue)}}}var pvTicksPanel=new pvc.visual.Panel(this,this.pvPanel,{extensionId:'ticksPanel'}).lock('data',rootScene.childNodes).lock(anchorOpposite,0).lockMark(anchorOrtho,function(tickScene){return scale(tickScene.vars.tick.value)}).lock('strokeStyle',null).lock('fillStyle',null).lock('lineWidth',0).pvMark.zOrder(20);if(this.showTicks){var pvTicks=this.pvTicks=new pvc.visual.Rule(this,pvTicksPanel,{extensionId:'ticks',wrapper:wrapper}).lock('data').override('defaultColor',function(){return pvRule.scene?pvRule.scene[0].strokeStyle:"#666666"}).lock(anchorOpposite,0).lock(anchorOrtho,0).lock(anchorLength,null).optional(anchorOrthoLength,this.tickLength).pvMark;if(this.showMinorTicks){var layoutInfo=this._layoutInfo;var ticks=layoutInfo.ticks;var tickCount=ticks.length;var minorTickOffset=tickCount>1?Math.abs(scale(ticks[1])-scale(ticks[0]))/2:0;this.pvMinorTicks=new pvc.visual.Rule(this,this.pvTicks,{extensionId:'minorTicks',wrapper:wrapper}).lock('data').intercept('visible',function(){var visible=(this.index<tickCount-1)&&(!pvTicks.scene||pvTicks.scene[0].visible);return visible&&this.delegateExtension(true)}).override('defaultColor',function(){return pvTicks.scene?pvTicks.scene[0].strokeStyle:pv.Color.names.d}).lock(anchorOpposite,0).lock(anchorLength,null).optional(anchorOrthoLength,this.tickLength/2).lockMark(anchorOrtho,minorTickOffset).pvMark}}this.renderLinearAxisLabel(pvTicksPanel,wrapper);this._debugTicksPanel(pvTicksPanel)},renderLinearAxisLabel:function(pvTicksPanel,wrapper){var pvTicks=this.pvTicks;var anchorOpposite=this.anchorOpposite();var anchorOrtho=this.anchorOrtho();var scale=this.scale;var font=this.font;posFixoY="";if(this.chart.options.posFixoY){posFixoY=this.chart.options.posFixoY}var maxTextWidth=this._layoutInfo.maxTextWidth;if(!isFinite(maxTextWidth)){maxTextWidth=0}var label=this.pvLabel=new pvc.visual.Label(this,pvTicksPanel,{extensionId:'label',wrapper:wrapper}).lock('data').pvMark.lock(anchorOpposite,this.tickLength).lock(anchorOrtho,0).zOrder(40).text(function(tickScene){var text=tickScene.vars.tick.label+posFixoY;if(maxTextWidth){text=pvc.text.trimToWidthB(maxTextWidth,text,font,'..',false)}return text}).font(this.font).textStyle("#666666");var rootPanel=this.pvPanel.root;if(this.isAnchorTopOrBottom()){label.textBaseline(anchorOpposite).textAlign(function(tickScene){var absLeft;if(this.index===0){absLeft=label.toScreenTransform().transformHPosition(label.left());if(absLeft<=0){return'left'}}else if(this.index===tickScene.parent.childNodes.length-1){absLeft=label.toScreenTransform().transformHPosition(label.left());if(absLeft>=rootPanel.width()){return'right'}}return'center'})}else{label.textAlign(anchorOpposite).textBaseline(function(tickScene){var absTop;if(this.index===0){absTop=label.toScreenTransform().transformVPosition(label.top());if(absTop>=rootPanel.height()){return'bottom'}}else if(this.index===tickScene.parent.childNodes.length-1){absTop=label.toScreenTransform().transformVPosition(label.top());if(absTop<=0){return'top'}}return'middle'})}},_onV1Click:function(context,handler){if(this.isDiscrete&&this.useCompositeAxis){handler.call(context.pvMark,context.scene,context.event)}},_onV1DoubleClick:function(context,handler){if(this.isDiscrete&&this.useCompositeAxis){handler.call(context.pvMark,context.scene,context.event)}},_getSelectableMarks:function(){if(this.isDiscrete&&this.isVisible&&this.pvLabel){return[this.pvLabel]}},renderCompositeOrdinalAxis:function(){var myself=this,isTopOrBottom=this.isAnchorTopOrBottom(),axisDirection=isTopOrBottom?'h':'v',diagDepthCutoff=2,vertDepthCutoff=2,font=this.font;var diagMargin=pv.Text.fontHeight(font)/2;var layout=this._pvLayout=this.getLayoutSingleCluster();layout.node.def("fitInfo",null).height(function(tickScene,e,f){var fitInfo=pvc.text.getFitInfo(tickScene.dx,tickScene.dy,tickScene.vars.tick.label,font,diagMargin);if(!fitInfo.h){if(axisDirection==='v'&&fitInfo.v){vertDepthCutoff=Math.min(diagDepthCutoff,tickScene.depth)}else{diagDepthCutoff=Math.min(diagDepthCutoff,tickScene.depth)}}this.fitInfo(fitInfo);return tickScene.dy});layout.node.add(pv.Bar).fillStyle('rgba(127,127,127,.001)').strokeStyle(function(tickScene){if(tickScene.maxDepth===1||!tickScene.maxDepth){return null}return"rgba(127,127,127,0.3)"}).lineWidth(function(tickScene){if(tickScene.maxDepth===1||!tickScene.maxDepth){return 0}return 0.5}).text(function(tickScene){return tickScene.vars.tick.label});var H_CUTOFF_ANG=0.30,V_CUTOFF_ANG=1.27;var align=isTopOrBottom?"center":(this.anchor=="left")?"right":"left";var wrapper;if(this.compatVersion()<=1){wrapper=function(v1f){return function(tickScene){return v1f.call(this,tickScene)}}}this.pvLabel=new pvc.visual.Label(this,layout.label,{extensionId:'label',noClick:false,noDoubleClick:false,noSelect:false,noTooltip:false,noHover:false,wrapper:wrapper,tooltipArgs:{isLazy:false,buildTooltip:function(context){return context.scene.vars.tick.label},options:{gravity:this._calcTipsyGravity(),offset:diagMargin*2}}}).pvMark.def('lblDirection','h').textAngle(function(tickScene){if(tickScene.depth>=vertDepthCutoff&&tickScene.depth<diagDepthCutoff){this.lblDirection('v');return-Math.PI/2}if(tickScene.depth>=diagDepthCutoff){var tan=tickScene.dy/tickScene.dx;var angle=Math.atan(tan);if(angle>V_CUTOFF_ANG){this.lblDirection('v');return-Math.PI/2}if(angle>H_CUTOFF_ANG){this.lblDirection('d');return-angle}}this.lblDirection('h');return 0}).textMargin(1).textAlign(function(tickScene){return(axisDirection!='v'||tickScene.depth>=vertDepthCutoff||tickScene.depth>=diagDepthCutoff)?'center':align}).left(function(tickScene){return(axisDirection!='v'||tickScene.depth>=vertDepthCutoff||tickScene.depth>=diagDepthCutoff)?tickScene.x+tickScene.dx/2:((align=='right')?tickScene.x+tickScene.dx:tickScene.x)}).font(font).textStyle("#666666").text(function(tickScene){var fitInfo=this.fitInfo();var label=tickScene.vars.tick.label;switch(this.lblDirection()){case'h':if(!fitInfo.h){return pvc.text.trimToWidth(tickScene.dx,label,font,'..')}break;case'v':if(!fitInfo.v){return pvc.text.trimToWidth(tickScene.dy,label,font,'..')}break;case'd':if(!fitInfo.d){var diagonalLength=Math.sqrt(tickScene.dy*tickScene.dy+tickScene.dx*tickScene.dx);return pvc.text.trimToWidth(diagonalLength-diagMargin,label,font,'..')}break}return label})},getLayoutSingleCluster:function(){var rootScene=this._getRootScene(),orientation=this.anchor,maxDepth=rootScene.group.treeHeight,depthLength=this._layoutInfo.axisSize;maxDepth++;var baseDisplacement=depthLength/maxDepth,margin=maxDepth>2?((1/12)*depthLength):0;baseDisplacement-=margin;var scaleFactor=maxDepth/(maxDepth-1),orthoLength=pvc.BasePanel.orthogonalLength[orientation];var displacement=(orthoLength=='width')?(orientation==='left'?[-baseDisplacement,0]:[baseDisplacement,0]):(orientation==='top'?[0,-baseDisplacement]:[0,baseDisplacement]);this.pvRule.sign.override('defaultColor',def.fun.constant(null)).override('defaultStrokeWidth',def.fun.constant(0));var panel=this.pvRule.add(pv.Panel)[orthoLength](depthLength).strokeStyle(null).lineWidth(0).add(pv.Panel)[orthoLength](depthLength*scaleFactor).strokeStyle(null).lineWidth(0);panel.transform(pv.Transform.identity.translate(displacement[0],displacement[1]));return panel.add(pv.Layout.Cluster.Fill).nodes(rootScene.nodes()).orient(orientation)},_calcTipsyGravity:function(){switch(this.anchor){case'bottom':return's';case'top':return'n';case'left':return'w';case'right':return'e'}return's'}});
def.type('pvc.AxisTitlePanel',pvc.TitlePanelAbstract).init(function(chart,parent,axis,options){this.axis=axis;this.base(chart,parent,options);this._extensionPrefix=axis.extensionPrefixes.map(function(prefix){return prefix+'Title'})}).add({_calcLayout:function(layoutInfo){var scale=this.axis.scale;if(!scale||scale.isNull){return new pvc.Size(0,0)}return this.base(layoutInfo)},_createCore:function(layoutInfo){var scale=this.axis.scale;if(!scale||scale.isNull){return}return this.base(layoutInfo)}});
def.type('pvc.PieChartPanel',pvc.PlotPanel).init(function(chart,parent,plot,options){var labelStyle=plot.option('ValuesLabelStyle');this.base(chart,parent,plot,options);this.explodedOffsetRadius=plot.option('ExplodedSliceRadius');this.explodedSliceIndex=plot.option('ExplodedSliceIndex');this.activeOffsetRadius=plot.option('ActiveSliceRadius');this.labelStyle=labelStyle;if(labelStyle==='linked'){this.linkInsetRadius=plot.option('LinkInsetRadius');this.linkOutsetRadius=plot.option('LinkOutsetRadius');this.linkMargin=plot.option('LinkMargin');this.linkHandleWidth=plot.option('LinkHandleWidth');this.linkLabelSize=plot.option('LinkLabelSize');this.linkLabelSpacingMin=plot.option('LinkLabelSpacingMin')}}).add({pvPie:null,pvPieLabel:null,valueRoleName:'value',_getV1Datum:function(scene){var datum=scene.datum;if(datum){var datumEx=Object.create(datum);datumEx.percent=scene.vars.value.percent;datum=datumEx}return datum},_calcLayout:function(layoutInfo){var clientSize=layoutInfo.clientSize;var clientWidth=clientSize.width;var clientRadius=Math.min(clientWidth,clientSize.height)/2;if(!clientRadius){return new pvc.Size(0,0)}var center=pv.vector(clientSize.width/2,clientSize.height/2);function resolvePercentRadius(radius){return def.between(pvc.PercentValue.resolve(radius,clientRadius),0,clientRadius)}function resolvePercentWidth(width){return def.between(pvc.PercentValue.resolve(width,clientWidth),0,clientWidth)}var labelFont=this._getConstantExtension('label','font');if(!def.string.is(labelFont)){labelFont=this.valuesFont}var maxPieRadius=clientRadius;if(this.valuesVisible&&this.labelStyle==='linked'){var linkInsetRadius=resolvePercentRadius(this.linkInsetRadius);var linkOutsetRadius=resolvePercentRadius(this.linkOutsetRadius);var linkMargin=resolvePercentWidth(this.linkMargin);var linkLabelSize=resolvePercentWidth(this.linkLabelSize);var textMargin=def.number.to(this._getConstantExtension('label','textMargin'),3);var textHeight=pv.Text.fontHeight(labelFont);var linkHandleWidth=this.linkHandleWidth*textHeight;linkMargin+=linkHandleWidth;var linkLabelSpacingMin=this.linkLabelSpacingMin*textHeight;var freeWidthSpace=Math.max(0,clientWidth/2-clientRadius);var spaceH=Math.max(0,linkOutsetRadius+linkMargin+linkLabelSize-freeWidthSpace);var spaceV=linkOutsetRadius+textHeight;var linkAndLabelRadius=Math.max(0,spaceV,spaceH);if(linkAndLabelRadius>=maxPieRadius){this.valuesVisible=false;if(pvc.debug>=2){this._log("Hiding linked labels due to insufficient space.")}}else{maxPieRadius-=linkAndLabelRadius;layoutInfo.link={insetRadius:linkInsetRadius,outsetRadius:linkOutsetRadius,elbowRadius:maxPieRadius+linkOutsetRadius,linkMargin:linkMargin,handleWidth:linkHandleWidth,labelSize:linkLabelSize,maxTextWidth:linkLabelSize-textMargin,labelSpacingMin:linkLabelSpacingMin,textMargin:textMargin,lineHeight:textHeight}}}var explodedOffsetRadius=resolvePercentRadius(this.explodedOffsetRadius);var activeOffsetRadius=0;if(this.chart.options.hoverable){activeOffsetRadius=resolvePercentRadius(this.activeOffsetRadius)}var effectOffsetRadius=explodedOffsetRadius+activeOffsetRadius;var normalPieRadius=maxPieRadius-effectOffsetRadius;if(normalPieRadius<0){return new pvc.Size(0,0)}layoutInfo.center=center;layoutInfo.clientRadius=clientRadius;layoutInfo.normalRadius=normalPieRadius;layoutInfo.explodedOffsetRadius=explodedOffsetRadius;layoutInfo.activeOffsetRadius=activeOffsetRadius;layoutInfo.labelFont=labelFont},_createCore:function(layoutInfo){var myself=this;var chart=this.chart;var options=chart.options;var visibleKeyArgs={visible:true};var rootScene=this._buildScene();var center=layoutInfo.center;var normalRadius=layoutInfo.normalRadius;var wrapper;var extensionIds=['slice'];if(this.compatVersion()<=1){extensionIds.push('');wrapper=function(v1f){return function(pieCatScene){return v1f.call(this,pieCatScene.vars.value.value)}}}this.pvPie=new pvc.visual.PieSlice(this,this.pvPanel,{extensionId:extensionIds,center:center,activeOffsetRadius:layoutInfo.activeOffsetRadius,wrapper:wrapper,tooltipArgs:{options:{useCorners:true,gravity:function(){var isRightPlane=Math.cos(this.midAngle())>=0;var isTopPlane=Math.sin(this.midAngle())>=0;return isRightPlane?(isTopPlane?'nw':'sw'):(isTopPlane?'ne':'se')}}}}).lock('data',rootScene.childNodes).override('angle',function(){return this.scene.vars.value.angle}).override('baseOffsetRadius',function(){var explodeIndex=myself.explodedSliceIndex;if(explodeIndex==null||explodeIndex==this.pvMark.index){return layoutInfo.explodedOffsetRadius}return this.base()}).lock('outerRadius',function(){return chart.animate(0,normalRadius)}).localProperty('innerRadiusEx',pvc.PercentValue.parse).intercept('innerRadius',function(scene){var innerRadius=this.delegateExtension();if(innerRadius==null){var innerRadiusPct=this.pvMark.innerRadiusEx();if(innerRadiusPct!=null){innerRadius=pvc.PercentValue.resolve(innerRadiusPct,this.pvMark.outerRadius())||0}else{innerRadius=0}}return innerRadius>0?chart.animate(0,innerRadius):0}).pvMark;if(this.valuesVisible){if(this.labelStyle==='inside'){this.pvPieLabel=new pvc.visual.Label(this,this.pvPie.anchor(this.valuesAnchor),{extensionId:'label',wrapper:wrapper}).intercept('visible',function(scene){var angle=scene.vars.value.angle;if(angle<0.001){return false}return this.delegateExtension(true)}).pvMark.text(function(scene){return scene.vars.value.sliceLabel}).textMargin(10)}else if(this.labelStyle==='linked'){var linkLayout=layoutInfo.link;rootScene.layoutLinkLabels(layoutInfo);this.pvLinkPanel=this.pvPanel.add(pv.Panel).data(rootScene.childNodes).localProperty('pieSlice').pieSlice(function(scene){return myself.pvPie.scene[this.index]});this.pvLinkLine=new pvc.visual.Line(this,this.pvLinkPanel,{extensionId:'linkLine',freePosition:true,noClick:true,noDoubleClick:true,noSelect:true,noTooltip:true,noHover:true}).lockMark('data',function(scene){var pieSlice=this.parent.pieSlice();var midAngle=pieSlice.startAngle+pieSlice.angle/2;var outerRadius=pieSlice.outerRadius-linkLayout.insetRadius;var x=pieSlice.left+outerRadius*Math.cos(midAngle);var y=pieSlice.top+outerRadius*Math.sin(midAngle);var firstDotScene=scene.childNodes[0];if(!firstDotScene||!firstDotScene._isFirstDynamicScene){firstDotScene=new pvc.visual.PieLinkLineScene(scene,x,y,0);firstDotScene._isFirstDynamicScene=true}else{firstDotScene.x=x;firstDotScene.y=y}return scene.childNodes}).override('defaultColor',function(type){if(type==='stroke'){return'black'}return this.base(type)}).override('defaultStrokeWidth',def.fun.constant(0.5)).pvMark.lock('visible').lock('top',function(dot){return dot.y}).lock('left',function(dot){return dot.x});this.pvPieLabel=new pvc.visual.Label(this,this.pvLinkPanel,{extensionId:'label',noClick:false,noDoubleClick:false,noSelect:false,noHover:false}).lockMark('data',function(scene){return scene.lineScenes}).pvMark.lock('visible').left(function(scene){return scene.vars.link.labelX}).top(function(scene){return scene.vars.link.labelY+((this.index+1)*linkLayout.lineHeight)}).textAlign(function(scene){return scene.vars.link.labelAnchor}).textMargin(linkLayout.textMargin).textBaseline('bottom').text(function(scene){return scene.vars.link.labelLines[this.index]}).fillStyle('red');if(pvc.debug>=20){this.pvPanel.add(pv.Panel).zOrder(-10).left(center.x-layoutInfo.clientRadius).top(center.y-layoutInfo.clientRadius).width(layoutInfo.clientRadius*2).height(layoutInfo.clientRadius*2).strokeStyle('red');this.pvPanel.strokeStyle('green');var linkColors=pv.Colors.category10();this.pvLinkLine.segmented(true).strokeStyle(function(){return linkColors(this.index)})}}this.pvPieLabel.font(layoutInfo.labelFont)}},_getExtensionId:function(){var extensionIds=[{abs:'content'}];if(this.chart.parent){extensionIds.push({abs:'smallContent'})}return extensionIds.concat(this.base())},renderInteractive:function(){this.pvPanel.render()},_getSelectableMarks:function(){var marks=[this.pvPie];if(this.pvPieLabel){marks.push(this.pvPieLabel)}return marks},_buildScene:function(){var rootScene=new pvc.visual.PieRootScene(this);this.sum=rootScene.vars.sumAbs.value;return rootScene}});def.type('pvc.visual.PieRootScene',pvc.visual.Scene).init(function(panel){var chart=panel.chart;var data=chart.visualRoles('category').flatten(chart.data,pvc.data.visibleKeyArgs);var colorVarHelper=new pvc.visual.RoleVarHelper(chart,chart._colorRole);this.base(null,{panel:panel,group:data});var valueRoleName=panel.valueRoleName;var valueDimName=chart.visualRoles(valueRoleName).firstDimensionName();var valueDim=data.dimensions(valueDimName);var options=chart.options;var percentValueFormat=options.percentValueFormat;var rootScene=this;var sumAbs=0;var CategSceneClass=def.type(pvc.visual.PieCategoryScene).init(function(categData,value){this.base(rootScene,{group:categData});this.vars.category=pvc.visual.ValueLabelVar.fromComplex(categData);sumAbs+=Math.abs(value);this.vars.value=new pvc.visual.ValueLabelVar(value,formatValue(value,categData));colorVarHelper.onNewScene(this,true)});panel._extendSceneType('category',CategSceneClass,['sliceLabel','sliceLabelMask']);data.children().each(function(categData){var value=categData.dimensions(valueDimName).sum(pvc.data.visibleKeyArgs);if(value!==0){new CategSceneClass(categData,value)}});this.angleScale=pv.Scale.linear(0,sumAbs).range(0,2*Math.PI).by1(Math.abs);this.vars.sumAbs=new pvc.visual.ValueLabelVar(sumAbs,formatValue(sumAbs));this.childNodes.forEach(function(categScene){completeBuildCategScene.call(categScene)});function formatValue(value,categData){if(categData){var datums=categData._datums;if(datums.length===1){return datums[0].atoms[valueDimName].label}}return valueDim.format(value)}function completeBuildCategScene(){var valueVar=this.vars.value;valueVar.angle=this.parent.angleScale(valueVar.value);var percent=Math.abs(valueVar.value)/sumAbs;valueVar.percent=new pvc.visual.ValueLabelVar(percent,percentValueFormat(percent));valueVar.sliceLabel=this.sliceLabel()}}).add({layoutLinkLabels:function(layoutInfo){var startAngle=-Math.PI/2;var leftScenes=[];var rightScenes=[];this.childNodes.forEach(function(categScene){startAngle=categScene.layoutI(layoutInfo,startAngle);(categScene.vars.link.dir>0?rightScenes:leftScenes).push(categScene)});this._distributeLabels(-1,leftScenes,layoutInfo);this._distributeLabels(+1,rightScenes,layoutInfo)},_distributeLabels:function(dir,scenes,layoutInfo){scenes.sort(function(sceneA,sceneB){return def.compare(sceneA.vars.link.targetY,sceneB.vars.link.targetY)});this._distributeLabelsDownwards(scenes,layoutInfo)&&this._distributeLabelsUpwards(scenes,layoutInfo)&&this._distributeLabelsEvenly(scenes,layoutInfo);scenes.forEach(function(categScene){categScene.layoutII(layoutInfo)})},_distributeLabelsDownwards:function(scenes,layoutInfo){var linkLayout=layoutInfo.link;var labelSpacingMin=linkLayout.labelSpacingMin;var yMax=layoutInfo.clientSize.height;var overlapping=false;for(var i=0,J=scenes.length-1;i<J;i++){var linkVar0=scenes[i].vars.link;if(!i&&linkVar0.labelTop()<0){overlapping=true}var linkVar1=scenes[i+1].vars.link;var labelTopMin1=linkVar0.labelBottom()+labelSpacingMin;if(linkVar1.labelTop()<labelTopMin1){var halfLabelHeight1=linkVar1.labelHeight/2;var targetY1=labelTopMin1+halfLabelHeight1;var targetYMax=yMax-halfLabelHeight1;if(targetY1>targetYMax){overlapping=true;linkVar1.targetY=targetYMax}else{linkVar1.targetY=targetY1}}}return overlapping},_distributeLabelsUpwards:function(scenes,layoutInfo){var linkLayout=layoutInfo.link;var labelSpacingMin=linkLayout.labelSpacingMin;var overlapping=false;for(var i=scenes.length-1;i>0;i--){var linkVar1=scenes[i-1].vars.link;var linkVar0=scenes[i].vars.link;if(i===1&&linkVar1.labelTop()<0){overlapping=true}var labelBottomMax1=linkVar0.labelTop()-labelSpacingMin;if(linkVar1.labelBottom()>labelBottomMax1){var halfLabelHeight1=linkVar1.labelHeight/2;var targetY1=labelBottomMax1-halfLabelHeight1;var targetYMin=halfLabelHeight1;if(targetY1<targetYMin){overlapping=true;linkVar1.targetY=targetYMin}else{linkVar1.targetY=targetY1}}}return overlapping},_distributeLabelsEvenly:function(scenes,layoutInfo){var linkLayout=layoutInfo.link;var labelSpacingMin=linkLayout.labelSpacingMin;var totalHeight=0;scenes.forEach(function(categScene){totalHeight+=categScene.vars.link.labelHeight});var freeSpace=layoutInfo.clientSize.height-totalHeight;var labelSpacing=freeSpace;if(scenes.length>1){labelSpacing/=(scenes.length-1)}var y=0;scenes.forEach(function(scene){var linkVar=scene.vars.link;var halfLabelHeight=linkVar.labelHeight/2;y+=halfLabelHeight;linkVar.targetY=y;y+=halfLabelHeight+labelSpacing});return true}});def.type('pvc.visual.PieLinkLabelVar').add({labelTop:function(){return this.targetY-this.labelHeight/2},labelBottom:function(){return this.targetY+this.labelHeight/2}});def.type('pvc.visual.PieCategoryScene',pvc.visual.Scene).add({sliceLabelMask:function(){return this.panel().valuesMask},sliceLabel:function(){return this.format(this.sliceLabelMask())},layoutI:function(layoutInfo,startAngle){var valueVar=this.vars.value;var endAngle=startAngle+valueVar.angle;var midAngle=(startAngle+endAngle)/2;var linkVar=(this.vars.link=new pvc.visual.PieLinkLabelVar());var linkLayout=layoutInfo.link;var labelLines=pvc.text.justify(valueVar.sliceLabel,linkLayout.maxTextWidth,layoutInfo.labelFont);var lineCount=labelLines.length;linkVar.labelLines=labelLines;linkVar.labelHeight=lineCount*linkLayout.lineHeight;this.lineScenes=def.array.create(lineCount,this);var cosMid=Math.cos(midAngle);var sinMid=Math.sin(midAngle);var isAtRight=cosMid>=0;var dir=isAtRight?1:-1;linkVar.labelAnchor=isAtRight?'left':'right';var center=layoutInfo.center;var elbowRadius=linkLayout.elbowRadius;var elbowX=center.x+elbowRadius*cosMid;var elbowY=center.y+elbowRadius*sinMid;var anchorX=center.x+dir*elbowRadius;var targetX=anchorX+dir*linkLayout.linkMargin;new pvc.visual.PieLinkLineScene(this,elbowX,elbowY);new pvc.visual.PieLinkLineScene(this,anchorX,elbowY);linkVar.elbowY=elbowY;linkVar.targetY=elbowY+0;linkVar.targetX=targetX;linkVar.dir=dir;return endAngle},layoutII:function(layoutInfo){var linkVar=this.vars.link;var targetY=linkVar.targetY;var targetX=linkVar.targetX;var handleWidth=layoutInfo.link.handleWidth;if(handleWidth>0){new pvc.visual.PieLinkLineScene(this,targetX-linkVar.dir*handleWidth,targetY)}new pvc.visual.PieLinkLineScene(this,targetX,targetY);linkVar.labelX=targetX;linkVar.labelY=targetY-linkVar.labelHeight/2}});def.type('pvc.visual.PieLinkLineScene',pvc.visual.Scene).init(function(catScene,x,y,index){this.base(catScene,{group:catScene.group,index:index});this.x=x;this.y=y}).add(pv.Vector);
def.type('pvc.PieChart',pvc.BaseChart).add({_animatable:true,pieChartPanel:null,_getColorRoleSpec:function(){return{isRequired:true,defaultSourceRole:'category',defaultDimension:'color*',requireIsDiscrete:true}},_initVisualRoles:function(){this.base();this._addVisualRole('category',{isRequired:true,defaultDimension:'category*',autoCreateDimension:true});this._addVisualRole('value',{isMeasure:true,isRequired:true,isPercent:true,requireSingleDimension:true,requireIsDiscrete:false,valueType:Number,defaultDimension:'value'})},_initPlotsCore:function(){new pvc.visual.PiePlot(this)},_preRenderContent:function(contentOptions){this.base();var isV1Compat=this.compatVersion()<=1;if(isV1Compat){var innerGap=pvc.castNumber(this.options.innerGap)||0.95;innerGap=def.between(innerGap,0.1,1);contentOptions.paddings=((1-innerGap)*100/2).toFixed(2)+"%"}else if(contentOptions.paddings==null){contentOptions.paddings=new pvc.PercentValue(0.025)}var piePlot=this.plots.pie;this.pieChartPanel=new pvc.PieChartPanel(this,this.basePanel,piePlot,def.create(contentOptions,{scenes:def.getPath(this.options,'pie.scenes')}))}});
def.type('pvc.BarAbstractPanel',pvc.CategoricalAbstractPanel).add({pvBar:null,pvBarLabel:null,pvCategoryPanel:null,pvSecondLine:null,pvSecondDot:null,_creating:function(){var groupScene=this.defaultVisibleBulletGroupScene();if(groupScene&&!groupScene.hasRenderer()){var colorAxis=groupScene.colorAxis;var drawLine=colorAxis.option('LegendDrawLine');var drawMarker=!drawLine||colorAxis.option('LegendDrawMarker');if(drawMarker){var keyArgs={drawMarker:true,markerShape:colorAxis.option('LegendShape'),drawRule:drawLine,markerPvProto:new pv.Mark()};this.extend(keyArgs.markerPvProto,'',{constOnly:true});groupScene.renderer(new pvc.visual.legend.BulletItemDefaultRenderer(keyArgs))}}},_createCore:function(){this.base();var me=this,chart=me.chart,plot=me.plot,isStacked=!!me.stacked,isVertical=me.isOrientationVertical(),data=me.visibleData(),seriesData=me.visualRoles.series.flatten(data),rootScene=me._buildScene(data,seriesData),orthoAxis=me.axes.ortho,baseAxis=me.axes.base,orthoScale=orthoAxis.scale,orthoZero=orthoScale(0),sceneOrthoScale=orthoAxis.sceneScale({sceneVarName:'value',nullToZero:false}),sceneBaseScale=baseAxis.sceneScale({sceneVarName:'category'}),barSizeRatio=plot.option('BarSizeRatio'),barSizeMax=plot.option('BarSizeMax'),barStackedMargin=plot.option('BarStackedMargin'),baseRange=baseAxis.scale.range(),bandWidth=baseRange.band,barStepWidth=baseRange.step,barWidth,reverseSeries=isVertical===isStacked;if(isStacked){barWidth=bandWidth}else{var S=seriesData.childCount();barWidth=S>0?(bandWidth*barSizeRatio/S):0}if(barWidth>barSizeMax){barWidth=barSizeMax}me.barWidth=barWidth;me.barStepWidth=barStepWidth;var wrapper;if(me.compatVersion()<=1){wrapper=function(v1f){return function(scene){var markParent=Object.create(this.parent);var mark=Object.create(this);mark.parent=markParent;var serIndex=scene.parent.childIndex();var catIndex=scene.childIndex();if(isStacked){markParent.index=serIndex;mark.index=catIndex}else{markParent.index=catIndex;mark.index=serIndex}return v1f.call(mark,scene.vars.value.rawValue)}}}me.pvBarPanel=new pvc.visual.Panel(me,me.pvPanel,{panelType:pv.Layout.Band,extensionId:'panel'}).lock('layers',rootScene.childNodes).lockMark('values',function(seriesScene){return seriesScene.childNodes}).lockMark('orient',isVertical?'bottom-left':'left-bottom').lockMark('layout',isStacked?'stacked':'grouped').lockMark('verticalMode',me._barVerticalMode()).lockMark('yZero',orthoZero).pvMark.band.x(sceneBaseScale).w(bandWidth).differentialControl(me._barDifferentialControl()).item.order(reverseSeries?"reverse":null).h(function(scene){var y=sceneOrthoScale(scene);return y!=null?chart.animate(0,y-orthoZero):null}).w(barWidth).horizontalRatio(barSizeRatio).verticalMargin(barStackedMargin).end;this.pvBar=new pvc.visual.Bar(me,me.pvBarPanel.item,{extensionId:'',freePosition:true,wrapper:wrapper}).lockDimensions().pvMark.antialias(false);if(plot.option('OverflowMarkersVisible')){this._addOverflowMarkers(wrapper)}if(me.valuesVisible){me.pvBarLabel=new pvc.visual.Label(me,me.pvBar.anchor(me.valuesAnchor||'center'),{extensionId:'label',wrapper:wrapper}).pvMark.visible(function(){var length=this.scene.target[this.index][isVertical?'height':'width'];return length>=4}).font(me.valuesFont).text(function(scene){return scene.format(me.valuesMask)})}},_barVerticalMode:function(){return null},_barDifferentialControl:function(){return null},_getV1Datum:function(scene){var datum=scene.datum;if(datum){var datumEx=Object.create(datum);datumEx.percent=scene.vars.value.percent;datum=datumEx}return datum},_addOverflowMarkers:function(wrapper){var orthoAxis=this.axes.ortho;if(orthoAxis.option('FixedMax')!=null){this.pvOverflowMarker=this._addOverflowMarker(false,orthoAxis.scale,wrapper)}if(orthoAxis.option('FixedMin')!=null){this.pvUnderflowMarker=this._addOverflowMarker(true,orthoAxis.scale,wrapper)}},_addOverflowMarker:function(isMin,orthoScale,wrapper){var isVertical=this.isOrientationVertical(),a_bottom=isVertical?"bottom":"left",a_top=this.anchorOpposite(a_bottom),a_height=this.anchorOrthoLength(a_bottom),a_width=this.anchorLength(a_bottom),paddings=this._layoutInfo.paddings,rOrthoBound=isMin?(orthoScale.min-paddings[a_bottom]):(orthoScale.max+paddings[a_top]),angle;if(!isMin){angle=isVertical?Math.PI:-Math.PI/2}else{angle=isVertical?0:Math.PI/2}return new pvc.visual.Dot(this,this.pvBar.anchor('center'),{noSelect:true,noHover:true,noClick:true,noDoubleClick:true,noTooltip:true,freePosition:true,extensionId:isMin?'underflowMarker':'overflowMarker',wrapper:wrapper}).intercept('visible',function(scene){var visible=this.delegateExtension();if(visible!==undefined&&!visible){return false}var value=scene.vars.value.value;if(value==null){return false}var targetInstance=this.pvMark.scene.target[this.index];var orthoMaxPos=targetInstance[a_bottom]+(value>0?targetInstance[a_height]:0);return isMin?(orthoMaxPos<rOrthoBound):(orthoMaxPos>rOrthoBound)}).lock(a_top,null).lock('shapeSize').pvMark.shape("triangle").shapeRadius(function(){return Math.min(Math.sqrt(10),this.scene.target[this.index][a_width]/2)}).shapeAngle(angle).lineWidth(1.5).strokeStyle("red").fillStyle("white")[a_bottom](function(){return rOrthoBound+(isMin?1:-1)*(this.shapeRadius()+2)})},renderInteractive:function(){this.pvPanel.render()},_getSelectableMarks:function(){return[this.pvBar]},_buildScene:function(data,seriesData){var rootScene=new pvc.visual.Scene(null,{panel:this,group:data});var categDatas=data._children;var roles=this.visualRoles;var valueVarHelper=new pvc.visual.RoleVarHelper(rootScene,roles.value,{hasPercentSubVar:this.stacked});var colorVarHelper=new pvc.visual.RoleVarHelper(rootScene,roles.color);seriesData.children().each(createSeriesScene);return rootScene;function createSeriesScene(seriesData1){var seriesScene=new pvc.visual.Scene(rootScene,{group:seriesData1}),seriesKey=seriesData1.key;seriesScene.vars.series=pvc.visual.ValueLabelVar.fromComplex(seriesData1);colorVarHelper.onNewScene(seriesScene,false);categDatas.forEach(function(categData1){var group=data._childrenByKey[categData1.key]._childrenByKey[seriesKey],scene=new pvc.visual.Scene(seriesScene,{group:group});var categVar=scene.vars.category=pvc.visual.ValueLabelVar.fromComplex(categData1);categVar.group=categData1;valueVarHelper.onNewScene(scene,true);colorVarHelper.onNewScene(scene,true)})}}});
def.type('pvc.BarAbstract',pvc.CategoricalAbstract).init(function(options){this.base(options);var parent=this.parent;if(parent){this._valueRole=parent._valueRole}}).add({_initVisualRoles:function(){this.base();this._addVisualRole('value',{isMeasure:true,isRequired:true,isPercent:this.options.stacked,requireSingleDimension:true,requireIsDiscrete:false,valueType:Number,defaultDimension:'value'});this._valueRole=this.visualRoles('value')},_getCategoryRoleSpec:function(){var catRoleSpec=this.base();catRoleSpec.requireIsDiscrete=true;return catRoleSpec},_initData:function(){this.base.apply(this,arguments);var data=this.data;this._valueDim=data.dimensions(this._valueRole.firstDimensionName())}});
def.type('pvc.BarPanel',pvc.BarAbstractPanel).add({});
def.type('pvc.BarChart',pvc.BarAbstract).add({_animatable:true,_allowV1SecondAxis:true,_initPlotsCore:function(){var options=this.options;var barPlot=new pvc.visual.BarPlot(this);var trend=barPlot.option('Trend');if(options.plot2){var plot2Plot=new pvc.visual.PointPlot(this,{name:'plot2',fixed:{DataPart:'1'},defaults:{ColorAxis:2,LinesVisible:true,DotsVisible:true}});if(!trend){trend=plot2Plot.option('Trend')}}if(trend){new pvc.visual.PointPlot(this,{name:'trend',fixed:{DataPart:'trend',TrendType:'none',ColorRole:'series',NullInterpolatioMode:'none'},defaults:{ColorAxis:2,LinesVisible:true,DotsVisible:false}})}},_hasDataPartRole:function(){return true},_createPlotPanels:function(parentPanel,baseOptions){var plots=this.plots;var barPlot=plots.bar;var barPanel=new pvc.BarPanel(this,parentPanel,barPlot,Object.create(baseOptions));this.barChartPanel=barPanel;var plot2Plot=plots.plot2;if(plot2Plot){if(pvc.debug>=3){this._log("Creating Point panel.")}var pointPanel=new pvc.PointPanel(this,parentPanel,plot2Plot,Object.create(baseOptions));barPanel.pvSecondLine=pointPanel.pvLine;barPanel.pvSecondDot=pointPanel.pvDot;pointPanel._applyV1BarSecondExtensions=true}var trendPlot=plots.trend;if(trendPlot){if(pvc.debug>=3){this._log("Creating Trends Point panel.")}new pvc.PointPanel(this,parentPanel,trendPlot,Object.create(baseOptions))}}});
def.type('pvc.NormalizedBarPanel',pvc.BarAbstractPanel).add({_barVerticalMode:function(){return'expand'}});
def.type('pvc.NormalizedBarChart',pvc.BarAbstract).add({_processOptionsCore:function(options){options.stacked=true;this.base(options)},_getContinuousVisibleExtentConstrained:function(axis,min,max){if(axis.type==='ortho'){return{min:0,max:100,minLocked:true,maxLocked:true}}return this.base(axis,min,max)},_initPlotsCore:function(hasMultiRole){new pvc.visual.NormalizedBarPlot(this)},_createPlotPanels:function(parentPanel,baseOptions){var barPlot=this.plots.bar;this.barChartPanel=new pvc.NormalizedBarPanel(this,parentPanel,barPlot,Object.create(baseOptions))}});
def.type('pvc.visual.legend.WaterfallBulletGroupScene',pvc.visual.Scene).init(function(rootScene,keyArgs){this.base(rootScene,keyArgs);this.extensionPrefix=def.get(keyArgs,'extensionPrefix')||'';var item=this.createItem({value:null,rawValue:null,label:def.get(keyArgs,'label')});item.color=def.get(keyArgs,'color')}).add({hasRenderer:function(){return this._renderer},renderer:function(renderer){if(renderer!=null){this._renderer=renderer}return this._renderer},itemSceneType:function(){var ItemType=this._itemSceneType;if(!ItemType){ItemType=def.type(pvc.visual.legend.BulletItemScene);this.panel()._extendSceneType('item',ItemType,['isOn','isClickable','click']);this._itemSceneType=ItemType}return ItemType},createItem:function(keyArgs){var ItemType=this.itemSceneType();return new ItemType(this,keyArgs)}});
def.type('pvc.WaterfallPanel',pvc.BarAbstractPanel).add({pvWaterfallLine:null,ruleData:null,_barDifferentialControl:function(){var isFalling=this.chart._isFalling;return function(scene){if(isFalling&&!this.index){return 1}var group=scene.vars.category.group;if(group._isFlattenGroup&&!group._isDegenerateFlattenGroup){return-2}return isFalling?-1:1}},_creating:function(){var rootScene=this._getLegendBulletRootScene();if(rootScene){var waterfallGroupScene=rootScene.firstChild;if(waterfallGroupScene&&!waterfallGroupScene.hasRenderer()){var keyArgs={drawRule:true,drawMarker:false,noSelect:true,noHover:true,rulePvProto:new pv.Mark()};this.extend(keyArgs.rulePvProto,'line',{constOnly:true});waterfallGroupScene.renderer(new pvc.visual.legend.BulletItemDefaultRenderer(keyArgs))}}},_createCore:function(){this.base();var chart=this.chart,isVertical=this.isOrientationVertical(),anchor=isVertical?"bottom":"left",ao=this.anchorOrtho(anchor),ruleRootScene=this._buildRuleScene(),orthoScale=chart.axes.ortho.scale,orthoPanelMargin=0.04*(orthoScale.range()[1]-orthoScale.range()[0]),orthoZero=orthoScale(0),sceneOrthoScale=chart.axes.ortho.sceneScale({sceneVarName:'value'}),sceneBaseScale=chart.axes.base.sceneScale({sceneVarName:'category'}),baseScale=chart.axes.base.scale,barWidth2=this.barWidth/2,barWidth=this.barWidth,barStepWidth=this.barStepWidth,isFalling=chart._isFalling,waterColor=chart._waterColor;if(this.plot.option('AreasVisible')){var panelColors=pv.Colors.category10();var waterGroupRootScene=this._buildWaterGroupScene();this.pvWaterfallGroupPanel=new pvc.visual.Panel(this,this.pvPanel,{extensionId:'group'}).lock('data',waterGroupRootScene.childNodes).pvMark.zOrder(-1).fillStyle(function(){return panelColors(0).alpha(0.15)})[ao](function(scene){var categVar=scene.vars.category;return baseScale(categVar.leftValue)-barStepWidth/2})[this.anchorLength(anchor)](function(scene){var categVar=scene.vars.category,length=Math.abs(baseScale(categVar.rightValue)-baseScale(categVar.leftValue));return length+barStepWidth})[anchor](function(scene){return orthoScale(scene.vars.value.bottomValue)-orthoPanelMargin/2})[this.anchorOrthoLength(anchor)](function(scene){return orthoScale(scene.vars.value.heightValue)+orthoPanelMargin})}this.pvBar.sign.override('baseColor',function(type){var color=this.base(type);if(type==='fill'){if(!this.scene.vars.category.group._isFlattenGroup){return pv.color(color).alpha(0.5)}}return color});this.pvWaterfallLine=new pvc.visual.Rule(this,this.pvPanel,{extensionId:'line',noTooltip:false,noHover:false,noSelect:false,noClick:false,noDoubleClick:false}).lock('data',ruleRootScene.childNodes).optional('visible',function(){return(isFalling&&!!this.scene.previousSibling)||(!isFalling&&!!this.scene.nextSibling)}).optional(anchor,function(){return orthoZero+chart.animate(0,sceneOrthoScale(this.scene)-orthoZero)}).optional(this.anchorLength(anchor),barStepWidth+barWidth).optional(ao,isFalling?function(){return sceneBaseScale(this.scene)-barStepWidth-barWidth2}:function(){return sceneBaseScale(this.scene)-barWidth2}).override('defaultColor',function(){return waterColor}).pvMark.antialias(true).lineCap('butt');if(this.plot.option('TotalValuesVisible')){this.pvWaterfallLabel=new pvc.visual.Label(this,this.pvWaterfallLine,{extensionId:'lineLabel'}).intercept('visible',function(scene){if(scene.vars.category.group._isFlattenGroup){return false}return isFalling||!!scene.nextSibling}).pvMark[anchor](function(scene){return orthoZero+chart.animate(0,sceneOrthoScale(scene)-orthoZero)})[this.anchorOrtho(anchor)](sceneBaseScale).textAlign(isVertical?'center':'left').textBaseline(function(categScene){if(!isVertical){return'middle'}var direction=categScene.vars.direction;if(direction==null){return'bottom'}var isRising=!isFalling;return(isRising===(direction==='up')?'bottom':'top')}).textStyle(pv.Color.names.darkgray.darker(2)).textMargin(5).text(function(scene){return scene.vars.value.label})}},_buildRuleScene:function(){var rootScene=new pvc.visual.Scene(null,{panel:this,group:this.visibleData()});var prevValue;if(this.chart._ruleInfos){this.chart._ruleInfos.forEach(createCategScene,this)}return rootScene;function createCategScene(ruleInfo){var categData1=ruleInfo.group;var categScene=new pvc.visual.Scene(rootScene,{group:categData1});var categVar=categScene.vars.category=pvc.visual.ValueLabelVar.fromComplex(categData1);categVar.group=categData1;var value=ruleInfo.offset;categScene.vars.value=new pvc.visual.ValueLabelVar(value,this.chart._valueDim.format(value));categScene.vars.direction=(prevValue==null||prevValue===value)?null:(prevValue<value?'up':'down');prevValue=value}},_buildWaterGroupScene:function(){var chart=this.chart,ruleInfos=this.chart._ruleInfos,ruleInfoByCategKey=ruleInfos&&def.query(ruleInfos).object({name:function(ruleInfo){return ruleInfo.group.absKey},value:function(ruleInfo){return ruleInfo}}),isFalling=chart._isFalling,rootCatData=chart._catRole.select(chart.partData(this.dataPartValue),{visible:true}),rootScene=new pvc.visual.Scene(null,{panel:this,group:rootCatData});if(ruleInfoByCategKey){createCategSceneRecursive(rootCatData,0)}return rootScene;function createCategSceneRecursive(catData,level){var children=catData.children().where(function(child){return child.key!==""}).array();if(children.length){if(level){var categScene=new pvc.visual.Scene(rootScene,{group:catData});var categVar=categScene.vars.category=pvc.visual.ValueLabelVar.fromComplex(catData);categVar.group=catData;categVar.level=level;var valueVar=categScene.vars.value={};var ruleInfo=ruleInfoByCategKey[catData.absKey];var offset=ruleInfo.offset,range=ruleInfo.range,height=-range.min+range.max;if(isFalling){var lastChild=lastLeaf(catData);var lastRuleInfo=ruleInfoByCategKey[lastChild.absKey];categVar.leftValue=ruleInfo.group.value;categVar.rightValue=lastRuleInfo.group.value;valueVar.bottomValue=offset-range.max}else{var firstChild=firstLeaf(catData);var firstRuleInfo=ruleInfoByCategKey[firstChild.absKey];categVar.leftValue=firstRuleInfo.group.value;categVar.rightValue=ruleInfo.group.value;valueVar.bottomValue=offset-range.max}valueVar.heightValue=height}children.forEach(function(child){createCategSceneRecursive(child,level+1)})}}function firstLeaf(data){var firstChild=data._children&&data._children[0];return firstChild?firstLeaf(firstChild):data}function lastLeaf(data){var lastChild=data._children&&data._children[data._children.length-1];return lastChild?lastLeaf(lastChild):data}}});
def.type('pvc.WaterfallChart',pvc.BarAbstract).init(function(options){this.base(options);var parent=this.parent;if(parent){this._isFalling=parent._isFalling}}).add({_animatable:true,_isFalling:true,_ruleInfos:null,_waterColor:pv.color("#1f77b4").darker(),_processOptionsCore:function(options){options.stacked=true;options.baseAxisComposite=false;this.base(options);options.plot2=false},_initPlotsCore:function(){var options=this.options;var waterPlot=new pvc.visual.WaterfallPlot(this);this._isFalling=waterPlot.option('Direction')==='down';this._catRole.setFlatteningMode(this._isFalling?'tree-pre':'tree-post');this._catRole.setFlattenRootLabel(this.plots.water.option('AllCategoryLabel'))},_initLegendScenes:function(legendPanel){var waterPlot=this.plots.water;var extAbsId=pvc.makeExtensionAbsId('line',waterPlot.extensionPrefixes);var strokeStyle=this._getConstantExtension(extAbsId,"strokeStyle");if(strokeStyle){this._waterColor=pv.color(strokeStyle)}var rootScene=legendPanel._getBulletRootScene();new pvc.visual.legend.WaterfallBulletGroupScene(rootScene,{extensionPrefix:pvc.buildIndexedId('',1),label:waterPlot.option('TotalLineLabel'),color:this._waterColor});this.base(legendPanel)},_reduceStackedCategoryValueExtent:function(result,catRange,catGroup){var offset;if(!result){if(catRange){offset=catRange.min+catRange.max;this._ruleInfos=[{offset:offset,group:catGroup,range:catRange}];return{min:catRange.min,max:catRange.max,offset:offset}}return null}offset=result.offset;if(this._isFalling){this._ruleInfos.push({offset:offset,group:catGroup,range:catRange})}if(!catGroup._isFlattenGroup||catGroup._isDegenerateFlattenGroup){var dir=this._isFalling?-1:1;offset=result.offset=offset+dir*(catRange.min+catRange.max);if(offset>result.max){result.max=offset}if(offset<result.min){result.min=offset}}if(!this._isFalling){this._ruleInfos.push({offset:offset,group:catGroup,range:catRange})}return result},_createPlotPanels:function(parentPanel,baseOptions){this.wfChartPanel=new pvc.WaterfallPanel(this,parentPanel,this.plots.water,def.create(baseOptions,{waterfall:this.options.waterfall}))}});
def.type('pvc.PointPanel',pvc.CategoricalAbstractPanel).init(function(chart,parent,plot,options){this.base(chart,parent,plot,options);this.linesVisible=plot.option('LinesVisible');this.dotsVisible=plot.option('DotsVisible');this.areasVisible=plot.option('AreasVisible');if(!this.linesVisible&&!this.dotsVisible&&!this.areasVisible){this.linesVisible=true;plot.option.specify({'LinesVisible':true})}}).add({pvLine:null,pvArea:null,pvDot:null,pvLabel:null,pvScatterPanel:null,_creating:function(){var groupScene=this.defaultVisibleBulletGroupScene();if(groupScene&&!groupScene.hasRenderer()){var colorAxis=groupScene.colorAxis;var drawMarker=def.nullyTo(colorAxis.option('LegendDrawMarker',true),this.dotsVisible||this.areasVisible);var drawRule=!drawMarker||def.nullyTo(colorAxis.option('LegendDrawLine',true),this.linesVisible&&!this.areasVisible);if(drawMarker||drawRule){var keyArgs={};if((keyArgs.drawMarker=drawMarker)){var markerShape=colorAxis.option('LegendShape',true);if(this.dotsVisible){if(!markerShape){markerShape='circle'}keyArgs.markerPvProto=new pv.Dot().lineWidth(1.5,pvc.extensionTag).shapeSize(12,pvc.extensionTag)}else{keyArgs.markerPvProto=new pv.Mark()}keyArgs.markerShape=markerShape;if(this._applyV1BarSecondExtensions){this.chart.extend(keyArgs.markerPvProto,'barSecondDot',{constOnly:true})}this.extend(keyArgs.markerPvProto,'dot',{constOnly:true})}if((keyArgs.drawRule=drawRule)){keyArgs.rulePvProto=new pv.Line().lineWidth(1.5,pvc.extensionTag);if(this._applyV1BarSecondExtensions){this.chart.extend(keyArgs.rulePvProto,'barSecondLine',{constOnly:true})}this.extend(keyArgs.rulePvProto,'line',{constOnly:true})}groupScene.renderer(new pvc.visual.legend.BulletItemDefaultRenderer(keyArgs))}}},_createCore:function(){this.base();var myself=this;var chart=this.chart;var isStacked=this.stacked;var dotsVisible=this.dotsVisible;var areasVisible=this.areasVisible;var linesVisible=this.linesVisible;var anchor=this.isOrientationVertical()?"bottom":"left";this.valueRole=chart.visualRoles(this.plot.option('OrthoRole'));this.valueRoleName=this.valueRole.name;this.valueDimName=this.valueRole.firstDimensionName();var isBaseDiscrete=this.axes.base.role.grouping.isDiscrete();var data=this.visibleData();var rootScene=this._buildScene(data,isBaseDiscrete);if(areasVisible){this.pvPanel.zOrder(-7)}else{this.pvPanel.zOrder(1)}this.pvScatterPanel=new pvc.visual.Panel(this,this.pvPanel,{extensionId:'panel'}).lock('data',rootScene.childNodes).pvMark;var areaFillColorAlpha=areasVisible&&linesVisible&&!isStacked?0.5:null;var wrapper;if(this.compatVersion()<=1){if(isStacked){wrapper=function(v1f){return function(dotScene){return v1f.call(this,dotScene.vars.value.rawValue)}}}else{wrapper=function(v1f){return function(dotScene){var d={category:dotScene.vars.category.rawValue,value:dotScene.vars.value.rawValue};var pseudo=Object.create(this);pseudo.index=dotScene.dataIndex;return v1f.call(pseudo,d)}}}}var isLineAreaVisible=isBaseDiscrete&&isStacked?function(){return!this.scene.isNull||this.scene.isIntermediate}:function(){return!this.scene.isNull};var isLineAreaNoSelect=chart._canSelectWithFocusWindow();this.pvArea=new pvc.visual.Area(this,this.pvScatterPanel,{extensionId:'area',noTooltip:false,wrapper:wrapper,noSelect:isLineAreaNoSelect,showsSelection:!isLineAreaNoSelect}).lock('visible',isLineAreaVisible).lock('data',function(seriesScene){return seriesScene.childNodes}).override('x',function(){return this.scene.basePosition}).override('y',function(){return this.scene.orthoPosition}).override('dy',function(){return chart.animate(0,this.scene.orthoLength)}).override('color',function(type){return areasVisible?this.base(type):null}).override('baseColor',function(type){var color=this.base(type);if(!this._finished&&color&&areaFillColorAlpha!=null){color=color.alpha(areaFillColorAlpha)}return color}).override('dimColor',function(color,type){return isStacked?pvc.toGrayScale(color,1,null,null).brighter():this.base(color,type)}).lock('events',areasVisible?'painted':'none').pvMark;var dotsVisibleOnly=dotsVisible&&!linesVisible&&!areasVisible,lineCopiesAreaColor=!linesVisible&&areasVisible,darkerLineAndDotColor=isStacked&&areasVisible;var extensionIds=['line'];if(this._applyV1BarSecondExtensions){extensionIds.push({abs:'barSecondLine'})}var isLineVisible=!dotsVisibleOnly&&isLineAreaVisible;this.pvLine=new pvc.visual.Line(this,this.pvArea.anchor(this.anchorOpposite(anchor)),{extensionId:extensionIds,freePosition:true,wrapper:wrapper,noTooltip:false,noSelect:isLineAreaNoSelect,showsSelection:!isLineAreaNoSelect}).lock('visible',isLineVisible).override('defaultColor',function(type){var color=this.base(type);if(!this._finished&&darkerLineAndDotColor&&color){color=color.darker(0.6)}return color}).override('normalColor',function(color,type){return linesVisible?color:null}).override('baseStrokeWidth',function(){var strokeWidth;if(linesVisible){strokeWidth=this.base()}return strokeWidth==null?1.5:strokeWidth}).intercept('strokeDasharray',function(){var dashArray=this.delegateExtension();if(dashArray===undefined){var scene=this.scene;var useDash=scene.isInterpolated;if(!useDash){var next=scene.nextSibling;useDash=next&&next.isIntermediate&&next.isInterpolated;if(!useDash){var previous=scene.previousSibling;useDash=previous&&scene.isIntermediate&&previous.isInterpolated}}dashArray=useDash?'. ':null}return dashArray}).pvMark;var showAloneDots=!(areasVisible&&isBaseDiscrete&&isStacked);extensionIds=['dot'];if(this._applyV1BarSecondExtensions){extensionIds.push({abs:'barSecondDot'})}this.pvDot=new pvc.visual.Dot(this,this.pvLine,{extensionId:extensionIds,freePosition:true,wrapper:wrapper}).intercept('visible',function(){var scene=this.scene;return(!scene.isNull&&!scene.isIntermediate)&&this.delegateExtension(true)}).override('color',function(type){if(!dotsVisible){var visible=this.scene.isActive||(!showAloneDots&&this.scene.isSingle)||(showAloneDots&&this.scene.isAlone);if(!visible){return pvc.invisibleFill}}if(this.scene.isInterpolated&&type==='fill'){var color=this.base(type);return color&&pv.color(color).brighter(0.5)}return this.base(type)}).optionalMark('lineCap','round').override('defaultColor',function(type){var color=this.base(type);if(!this._finished&&darkerLineAndDotColor&&color){color=color.darker(0.6)}return color}).override('baseSize',function(){if(!dotsVisible){var visible=this.scene.isActive||(!showAloneDots&&this.scene.isSingle)||(showAloneDots&&this.scene.isAlone);if(visible&&!this.scene.isActive){var lineWidth=Math.max(myself.pvLine.lineWidth(),0.2)/2;return lineWidth*lineWidth}}if(this.scene.isInterpolated){return 0.8*this.base()}return this.base()}).pvMark;if(this.valuesVisible){this.pvLabel=new pvc.visual.Label(this,this.pvDot.anchor(this.valuesAnchor),{extensionId:'label',wrapper:wrapper}).pvMark.font(this.valuesFont).text(function(scene){return scene.vars.value.label})}},renderInteractive:function(){this.pvScatterPanel.render()},_getSelectableMarks:function(){var marks=[];marks.push(this.pvDot);if(this.linesVisible||this.areasVisible){marks.push(this.pvLine)}return marks},_buildScene:function(data,isBaseDiscrete){var rootScene=new pvc.visual.Scene(null,{panel:this,group:data});var categDatas=data._children;var chart=this.chart;var colorVarHelper=new pvc.visual.RoleVarHelper(chart,chart._colorRole);var valueDim=data.owner.dimensions(this.valueDimName);var isStacked=this.stacked;var visibleKeyArgs={visible:true,zeroIfNone:false};var orthoScale=this.axes.ortho.scale;var orthoNullValue=def.scope(function(){var domain=orthoScale.domain(),dmin=domain[0],dmax=domain[1];if(dmin*dmax>=0){return dmin>=0?dmin:dmax}return 0});var orthoZero=orthoScale(orthoNullValue);var sceneBaseScale=this.axes.base.sceneScale({sceneVarName:'category'});def.scope(function(){var serRole=chart._serRole;return(serRole&&serRole.grouping)?serRole.flatten(data).children():def.query([null])}).each(function(seriesData1){var seriesScene=new pvc.visual.Scene(rootScene,{group:seriesData1||data});seriesScene.vars.series=pvc.visual.ValueLabelVar.fromComplex(seriesData1);colorVarHelper.onNewScene(seriesScene,false);categDatas.forEach(function(categData,categIndex){var group=categData;if(seriesData1){group=group._childrenByKey[seriesData1.key]}var value=group?group.dimensions(valueDim.name).sum(visibleKeyArgs):null;var serCatScene=new pvc.visual.Scene(seriesScene,{group:group});serCatScene.dataIndex=categIndex;serCatScene.vars.category=pvc.visual.ValueLabelVar.fromComplex(categData);var valueVar=new pvc.visual.ValueLabelVar(value,valueDim.format(value),value);valueVar.accValue=value!=null?value:orthoNullValue;serCatScene.vars.value=valueVar;colorVarHelper.onNewScene(serCatScene,true);var isInterpolated=false;if(group){var firstDatum=group._datums[0];if(firstDatum&&firstDatum.isInterpolated){isInterpolated=true}}serCatScene.isInterpolated=isInterpolated;serCatScene.isNull=value==null;serCatScene.isIntermediate=false},this)},this);var reversedSeriesScenes=rootScene.children().reverse().array();var belowSeriesScenes2;reversedSeriesScenes.forEach(completeSeriesScenes,this);reversedSeriesScenes.forEach(trimNullSeriesScenes,this);return rootScene;function completeSeriesScenes(seriesScene){var seriesScenes2=[],seriesScenes=seriesScene.childNodes,fromScene,notNullCount=0,firstAloneScene=null;for(var c=0,toChildIndex=0,categCount=seriesScenes.length;c<categCount;c++,toChildIndex++){var toScene=seriesScenes[toChildIndex],c2=c*2;seriesScenes2[c2]=toScene;completeMainScene.call(this,fromScene,toScene,belowSeriesScenes2&&belowSeriesScenes2[c2]);if(toScene.isAlone&&!firstAloneScene){firstAloneScene=toScene}if(!toScene.isNull){notNullCount++}if(fromScene){var interScene=createIntermediateScene.call(this,seriesScene,fromScene,toScene,toChildIndex,belowSeriesScenes2&&belowSeriesScenes2[c2-1]);if(interScene){seriesScenes2[c2-1]=interScene;toChildIndex++}}fromScene=toScene}if(notNullCount===1&&firstAloneScene&&categCount===1){firstAloneScene.isSingle=true}if(isStacked){belowSeriesScenes2=seriesScenes2}}function completeMainScene(fromScene,toScene,belowScene){var toAccValue=toScene.vars.value.accValue;if(belowScene){if(toScene.isNull&&!isBaseDiscrete){toAccValue=orthoNullValue}else{toAccValue+=belowScene.vars.value.accValue}toScene.vars.value.accValue=toAccValue}toScene.basePosition=sceneBaseScale(toScene);toScene.orthoPosition=orthoZero;toScene.orthoLength=orthoScale(toAccValue)-orthoZero;var isNullFrom=(!fromScene||fromScene.isNull),isAlone=isNullFrom&&!toScene.isNull;if(isAlone){var nextScene=toScene.nextSibling;isAlone=!nextScene||nextScene.isNull}toScene.isAlone=isAlone;toScene.isSingle=false}function createIntermediateScene(seriesScene,fromScene,toScene,toChildIndex,belowScene){var interIsNull=fromScene.isNull||toScene.isNull;if(interIsNull&&!this.areasVisible){return null}var interValue,interAccValue,interBasePosition;if(interIsNull){if(belowScene&&isBaseDiscrete){var belowValueVar=belowScene.vars.value;interAccValue=belowValueVar.accValue;interValue=belowValueVar[this.valueRoleName]}else{interValue=interAccValue=orthoNullValue}if(isStacked&&isBaseDiscrete){interBasePosition=toScene.basePosition-(sceneBaseScale.range().step/2)}else if(fromScene.isNull){interBasePosition=toScene.basePosition}else{interBasePosition=fromScene.basePosition}}else{var fromValueVar=fromScene.vars.value,toValueVar=toScene.vars.value;interValue=(toValueVar.value+fromValueVar.value)/2;interAccValue=(toValueVar.accValue+fromValueVar.accValue)/2;interBasePosition=(toScene.basePosition+fromScene.basePosition)/2}var interScene=new pvc.visual.Scene(seriesScene,{index:toChildIndex,group:toScene.group,datum:toScene.group?null:toScene.datum});interScene.dataIndex=toScene.dataIndex;interScene.vars.category=toScene.vars.category;var interValueVar=new pvc.visual.ValueLabelVar(interValue,valueDim.format(interValue),interValue);interValueVar.accValue=interAccValue;interScene.vars.value=interValueVar;interScene.ownerScene=toScene;interScene.isInterpolated=toScene.isInterpolated;interScene.isIntermediate=true;interScene.isSingle=false;interScene.isNull=interIsNull;interScene.isAlone=interIsNull&&toScene.isNull&&fromScene.isNull;interScene.basePosition=interBasePosition;interScene.orthoPosition=orthoZero;interScene.orthoLength=orthoScale(interAccValue)-orthoZero;colorVarHelper.onNewScene(interScene,true);return interScene}function trimNullSeriesScenes(seriesScene){var seriesScenes=seriesScene.childNodes,L=seriesScenes.length;var scene,siblingScene;while(L&&(scene=seriesScenes[0]).isNull){siblingScene=scene.nextSibling;if(siblingScene&&!siblingScene.isNull){break}seriesScene.removeAt(0);L--}while(L&&(scene=seriesScenes[L-1]).isNull){siblingScene=scene.previousSibling;if(siblingScene&&!siblingScene.isNull){break}seriesScene.removeAt(L-1);L--}}}});
def.type('pvc.PointAbstract',pvc.CategoricalAbstract).add({_animatable:true,_processOptionsCore:function(options){options.panelSizeRatio=1;this.base(options)},_hasDataPartRole:function(){return true},_initVisualRoles:function(){this.base();this._addVisualRole('value',{isMeasure:true,isRequired:true,isPercent:this.options.stacked,requireSingleDimension:true,requireIsDiscrete:false,valueType:Number,defaultDimension:'value'})},_initPlotsCore:function(){var options=this.options;var pointPlot=this._createPointPlot();var trend=pointPlot.option('Trend');if(options.plot2){var plot2Plot=new pvc.visual.PointPlot(this,{name:'plot2',fixed:{DataPart:'1'},defaults:{ColorAxis:2,LinesVisible:true,DotsVisible:true}});if(!trend){trend=plot2Plot.option('Trend')}}if(trend){new pvc.visual.PointPlot(this,{name:'trend',fixed:{DataPart:'trend',TrendType:'none',ColorRole:'series',NullInterpolatioMode:'none'},defaults:{ColorAxis:2,LinesVisible:true,DotsVisible:false}})}},_bindAxes:function(hasMultiRole){this.base(hasMultiRole);var typeAxes=this.axesByType.base;if(typeAxes){typeAxes.forEach(function(axis){var isDiscrete=axis.scaleType==='discrete';if(!isDiscrete){axis.option.defaults({Offset:0.01})}})}typeAxes=this.axesByType.ortho;if(typeAxes){typeAxes.forEach(function(axis){axis.option.defaults({Offset:0.04})})}},_createPlotPanels:function(parentPanel,baseOptions){var plots=this.plots;var pointPlot=plots.point;this.scatterChartPanel=new pvc.PointPanel(this,parentPanel,pointPlot,Object.create(baseOptions));var plot2Plot=plots.plot2;if(plot2Plot){if(pvc.debug>=3){this._log("Creating second Point panel.")}new pvc.PointPanel(this,parentPanel,plot2Plot,Object.create(baseOptions))}var trendPlot=plots.trend;if(trendPlot){if(pvc.debug>=3){this._log("Creating Trends Point panel.")}new pvc.PointPanel(this,parentPanel,trendPlot,Object.create(baseOptions))}},defaults:{tooltipOffset:10}});def.type('pvc.DotChart',pvc.PointAbstract).add({_createPointPlot:function(){return new pvc.visual.PointPlot(this,{fixed:{DotsVisible:true}})}});def.type('pvc.LineChart',pvc.PointAbstract).add({_createPointPlot:function(){return new pvc.visual.PointPlot(this,{fixed:{LinesVisible:true}})}});def.type('pvc.AreaChart',pvc.PointAbstract).add({_createPointPlot:function(){return new pvc.visual.PointPlot(this,{fixed:{AreasVisible:true}})}});pvc.mStackedLineChart=def.type('pvc.StackedLineChart',pvc.PointAbstract).add({_createPointPlot:function(){return new pvc.visual.PointPlot(this,{fixed:{LinesVisible:true,Stacked:true}})}});def.type('pvc.StackedDotChart',pvc.PointAbstract).add({_createPointPlot:function(){return new pvc.visual.PointPlot(this,{fixed:{DotsVisible:true,Stacked:true}})}});pvc.mStackedAreaChart=def.type('pvc.StackedAreaChart',pvc.PointAbstract).add({_createPointPlot:function(){return new pvc.visual.PointPlot(this,{fixed:{AreasVisible:true,Stacked:true},defaults:{LinesVisible:true}})}});
def.type('pvc.HeatGridPanel',pvc.CategoricalAbstractPanel).init(function(chart,parent,plot,options){this.base(chart,parent,plot,options);this.axes.size=chart._getAxis('size',plot.option('SizeAxis')-1);var roles=this.visualRoles;var sizeRoleName=plot.option('SizeRole');roles.size=chart.visualRoles(sizeRoleName);var valueDimName;if(roles.color.isBound()){valueDimName=roles.color.firstDimensionName()}else if(roles.size.isBound()){valueDimName=roles.size.firstDimensionName()}this._valueDimName=valueDimName;this.useShapes=plot.option('UseShapes');this.shape=plot.option('Shape');this.nullShape=plot.option('NullShape')}).add({pvHeatGrid:null,pvHeatGridLabel:null,defaultBorder:1,nullBorder:2,selectedBorder:2,_createCore:function(){this.base();var chart=this.chart;var a_bottom=this.isOrientationVertical()?"bottom":"left";var xScale=this.axes.x.scale;var yScale=this.axes.y.scale;var w=(xScale.max-xScale.min)/xScale.domain().length;var h=(yScale.max-yScale.min)/yScale.domain().length;if(a_bottom!=="bottom"){var tmp=w;w=h;h=tmp}this._cellWidth=w;this._cellHeight=h;var keyArgs={visible:true},rowRootData=chart.data.flattenBy(chart._serRole,keyArgs),data=this.visibleData(),rootScene=this._buildScene(data,rowRootData),hasColor=rootScene.hasColorRole,hasSize=rootScene.hasSizeRole;var getFillColor;var colorAxis=this.axes.color;var colorNull=colorAxis.option('Missing');if(hasColor){var fillColorScaleByColKey=colorAxis.scalesByCateg;if(fillColorScaleByColKey){getFillColor=function(leafScene){var colorValue=leafScene.vars.color.value;if(colorValue==null){return colorNull}var colAbsKey=leafScene.group.parent.absKey;return fillColorScaleByColKey[colAbsKey](colorValue)}}else{var colorScale=colorAxis.scale;getFillColor=function(leafScene){return colorScale(leafScene.vars.color.value)}}}else{getFillColor=def.fun.constant(colorNull)}var a_left=pvc.BasePanel.relativeAnchor[a_bottom];var a_width=pvc.BasePanel.parallelLength[a_bottom];var a_height=pvc.BasePanel.orthogonalLength[a_bottom];var pvRowPanel=new pvc.visual.Panel(this,this.pvPanel).pvMark.data(rootScene.childNodes)[a_bottom](function(){return this.index*h})[a_height](h);var wrapper;if(this.compatVersion()<=1){var colorValuesBySerAndCat=def.query(rootScene.childNodes).object({name:function(serScene){return''+serScene.vars.series.value},value:function(serScene){return def.query(serScene.childNodes).object({name:function(leafScene){return''+leafScene.vars.category.value},value:function(leafScene){var colorVar=leafScene.vars.color;return colorVar?(''+colorVar.value):null}})}});wrapper=function(v1f){return function(leafScene){var colorValuesByCat=colorValuesBySerAndCat[leafScene.vars.series.value];var cat=leafScene.vars.category.rawValue;var wrapperParent=Object.create(this.parent);var wrapper=Object.create(this);wrapper.parent=wrapperParent;var catIndex=leafScene.childIndex();var serIndex=leafScene.parent.childIndex();wrapperParent.index=catIndex;wrapper.index=serIndex;return v1f.call(wrapper,colorValuesByCat,cat)}}}var extensionIds=['panel'];if(this.compatVersion()<=1){extensionIds.push('')}keyArgs={extensionId:extensionIds,wrapper:wrapper};if(!this.useShapes){keyArgs.noSelect=keyArgs.noHover=keyArgs.noClick=keyArgs.noDoubleClick=keyArgs.freeColor=false;keyArgs.noTooltip=!!wrapper}var pvHeatGrid=this.pvHeatGrid=new pvc.visual.Panel(this,pvRowPanel,keyArgs).lock('data',function(serScene){return serScene.childNodes}).pvMark.localProperty('colorValue').lock('colorValue',function(leafScene){return leafScene.vars.color.value}).localProperty('sizeValue').lock('sizeValue',function(leafScene){return leafScene.vars.size.value}).lock(a_left,function(){return this.index*w}).lock(a_width,w).antialias(false);if(this.useShapes){this.shapes=this.createHeatMap(w,h,getFillColor,wrapper,hasColor,hasSize)}else{this.shapes=pvHeatGrid.sign.override('defaultColor',function(type){if(type==='stroke'){return null}return getFillColor.call(this.pvMark,this.scene)}).override('interactiveColor',function(color,type){var scene=this.scene;if(scene.isActive){return color.alpha(0.6)}if(scene.anySelected()&&!scene.isSelected()){return this.dimColor(color,type)}return this.base(color,type)}).override('dimColor',function(color){return pvc.toGrayScale(color,0.6)}).pvMark.lineWidth(1.5)}if(this.valuesVisible&&this._valueDimName){var valueDimName=this._valueDimName;this.pvHeatGridLabel=new pvc.visual.Label(this,this.pvHeatGrid.anchor("center"),{extensionId:'label',wrapper:wrapper}).pvMark.font(this.valuesFont).text(function(leafScene){return leafScene.atoms[valueDimName].label})}},_calcDotAreaRange:function(w,h){var maxRadius=Math.min(w,h)/2;if(this.shape==='diamond'){maxRadius/=Math.SQRT2}maxRadius-=2;var maxArea=maxRadius*maxRadius,minArea=12,areaSpan=maxArea-minArea;if(areaSpan<=1){maxArea=Math.max(maxArea,2);minArea=1;areaSpan=maxArea-minArea;if(pvc.debug>=2){this._log("Using rescue mode dot area calculation due to insufficient space.")}}return{min:minArea,max:maxArea,span:areaSpan}},createHeatMap:function(w,h,getFillColor,wrapper,hasColor,hasSize){var me=this,chart=me.chart,nullShapeType=me.nullShape,shapeType=me.shape;var areaRange=me._calcDotAreaRange(w,h);var maxArea=areaRange.max;var sizeScale;if(hasSize){sizeScale=me.axes.size.setScaleRange(areaRange).scale}var notNullSelectedBorder=(me.selectedBorder==null||(+me.selectedBorder)===0)?me.defaultBorder:me.selectedBorder;var nullSelectedBorder=(me.selectedBorder==null||(+me.selectedBorder)===0)?me.nullBorder:me.selectedBorder;var nullDeselectedBorder=me.defaultBorder>0?me.defaultBorder:me.nullBorder;var getShapeSize,getShapeType;if(!hasSize){getShapeType=def.fun.constant(shapeType);getShapeSize=function(){return(hasColor&&!nullShapeType&&this.parent.colorValue()==null)?0:maxArea}}else{getShapeType=function(){return this.parent.sizeValue()!=null?shapeType:nullShapeType};getShapeSize=function(){var sizeValue=this.parent.sizeValue();return(sizeValue==null&&!nullShapeType)?0:sizeScale(sizeValue)}}var keyArgs={extensionId:'dot',freePosition:true,activeSeriesAware:false,noHover:false,wrapper:wrapper};var options=chart.options;if(wrapper&&chart._tooltipEnabled){var customTooltip=options.customTooltip;if(!customTooltip){customTooltip=function(s,c,d){if(d!=null&&d[0]!==undefined){return d.join(', ')}return d}}keyArgs.tooltipArgs={buildTooltip:options.isMultiValued?function(context){var group=context.scene.group;var s=pvc.data.Complex.values(group,chart._serRole.grouping.dimensionNames());var c=pvc.data.Complex.values(group,chart._catRole.grouping.dimensionNames());var d=[];if(hasSize){d[options.sizeValIdx||0]=context.scene.vars.size.value}if(hasColor){d[options.colorValIdx||0]=context.scene.vars.color.value}return customTooltip.call(options,s,c,d)}:function(context){var s=context.scene.vars.series.rawValue;var c=context.scene.vars.category.rawValue;var valueVar=context.scene.vars[hasColor?'color':'size'];var d=valueVar?valueVar.value:null;return customTooltip.call(options,s,c,d)}}}return new pvc.visual.Dot(me,me.pvHeatGrid,keyArgs).override('defaultSize',function(){return getShapeSize.call(this.pvMark,this.scene)}).override('interactiveSize',function(size){if(this.scene.isActive){return Math.max(size,5)*1.5}return size}).override('baseColor',function(){return getFillColor.call(this.pvMark.parent,this.scene)}).override('normalColor',function(color,type){if(type==='stroke'){return color.darker()}return this.base(color,type)}).override('interactiveColor',function(color,type){var scene=this.scene;if(type==='stroke'){if(scene.anySelected()&&!scene.isSelected()){return color}return color.darker()}if(scene.isActive){return color.alpha(0.6)}return this.base(color,type)}).override('dimColor',function(color){return pvc.toGrayScale(color,0.6)}).pvMark.shape(getShapeType).lock('shapeAngle').lineWidth(function(leafScene){if(!hasSize||!me._isNullShapeLineOnly()||this.parent.sizeValue()!=null){return leafScene.isSelected()?notNullSelectedBorder:me.defaultBorder}return leafScene.isSelected()?nullSelectedBorder:nullDeselectedBorder})},_isNullShapeLineOnly:function(){return this.nullShape=='cross'},_getSelectableMarks:function(){return[this.shapes]},renderInteractive:function(){this.pvPanel.render()},_buildScene:function(data,seriesRootData){var me=this;var rootScene=new pvc.visual.Scene(null,{panel:me,group:data});var categDatas=data._children;var roles=me.visualRoles;var colorVarHelper=new pvc.visual.RoleVarHelper(rootScene,roles.color);var sizeVarHelper=new pvc.visual.RoleVarHelper(rootScene,roles.size);rootScene.hasColorRole=colorVarHelper.isBound();rootScene.hasSizeRole=sizeVarHelper.isBound();seriesRootData.children().each(createSeriesScene);return rootScene;function createSeriesScene(serData1){var serScene=new pvc.visual.Scene(rootScene,{group:serData1});serScene.vars.series=pvc.visual.ValueLabelVar.fromComplex(serData1);categDatas.forEach(function(catData1){createSeriesCategoryScene.call(me,serScene,catData1,serData1)})}function createSeriesCategoryScene(serScene,catData1,serData1){var group=data._childrenByKey[catData1.key]._childrenByKey[serData1.key];var serCatScene=new pvc.visual.Scene(serScene,{group:group});serCatScene.vars.category=pvc.visual.ValueLabelVar.fromComplex(catData1);colorVarHelper.onNewScene(serCatScene,true);sizeVarHelper.onNewScene(serCatScene,true)}}});
def.type('pvc.HeatGridChart',pvc.CategoricalAbstract).add({_allowColorPerCategory:true,_axisCreateIfUnbound:{'color':true},_processOptionsCore:function(options){this.base(options);def.set(options,'orthoAxisOrdinal',true,'legend',false,'panelSizeRatio',1);var colorDimName='value',sizeDimName='value2';if(this.compatVersion()<=1){switch(this.options.colorValIdx){case 0:colorDimName='value';break;case 1:colorDimName='value2';break;default:colorDimName='value'}switch(this.options.sizeValIdx){case 0:sizeDimName='value';break;case 1:sizeDimName='value2';break;default:sizeDimName='value'}}this._colorDimName=colorDimName;this._sizeDimName=sizeDimName},_getCategoryRoleSpec:function(){var catRoleSpec=this.base();catRoleSpec.requireIsDiscrete=true;return catRoleSpec},_getColorRoleSpec:function(){return{isMeasure:true,requireSingleDimension:true,requireIsDiscrete:false,valueType:Number,defaultDimension:this._colorDimName}},_initVisualRoles:function(){this.base();this._addVisualRole('size',{isMeasure:true,requireSingleDimension:true,requireIsDiscrete:false,valueType:Number,defaultDimension:this._sizeDimName})},_initPlotsCore:function(){new pvc.visual.HeatGridPlot(this)},_collectPlotAxesDataCells:function(plot,dataCellsByAxisTypeThenIndex){this.base(plot,dataCellsByAxisTypeThenIndex);if(plot.type==='heatGrid'&&plot.option('UseShapes')){var sizeRole=this.visualRoles(plot.option('SizeRole'));if(sizeRole.isBound()){var sizeDataCellsByAxisIndex=def.array.lazy(dataCellsByAxisTypeThenIndex,'size');def.array.lazy(sizeDataCellsByAxisIndex,plot.option('SizeAxis')-1).push({plot:plot,role:sizeRole,dataPartValue:plot.option('DataPart')})}}},_setAxesScales:function(hasMultiRole){this.base(hasMultiRole);if(!hasMultiRole||this.parent){var sizeAxis=this.axes.size;if(sizeAxis&&sizeAxis.isBound()){this._createAxisScale(sizeAxis)}}},_createPlotPanels:function(parentPanel,baseOptions){var heatGridPlot=this.plots.heatGrid;this.heatGridChartPanel=new pvc.HeatGridPanel(this,parentPanel,heatGridPlot,Object.create(baseOptions))},defaults:{colorValIdx:0,sizeValIdx:1,measuresIndexes:[2],axisOffset:0,plotFrameVisible:false,colorNormByCategory:true,numSD:2}});
def.type('pvc.MetricXYAbstract',pvc.CartesianAbstract).init(function(options){this.base(options);var parent=this.parent;if(parent){this._xRole=parent._xRole;this._yRole=parent._yRole}}).add({_processOptionsCore:function(options){this.base(options);options.panelSizeRatio=1},_initVisualRoles:function(){this.base();this._xRole=this._addVisualRole('x',{isMeasure:true,isRequired:true,requireSingleDimension:true,requireIsDiscrete:false,defaultDimension:'x',dimensionDefaults:{valueType:this.options.timeSeries?Date:Number}});this._yRole=this._addVisualRole('y',{isMeasure:true,isRequired:true,requireSingleDimension:true,requireIsDiscrete:false,defaultDimension:'y',dimensionDefaults:{valueType:Number}})},_initData:function(){this.base.apply(this,arguments);this._xDim=this.data.dimensions(this._xRole.firstDimensionName());this._yDim=this.data.dimensions(this._yRole.firstDimensionName())},_generateTrendsDataCellCore:function(newDatums,dataCell,trendInfo){var serRole=this._serRole;var xRole=this._xRole;var yRole=dataCell.role;var trendOptions=dataCell.trend;this._warnSingleContinuousValueRole(yRole);var dataPartDimName=this._dataPartRole.firstDimensionName();var xDimName=xRole.firstDimensionName();var yDimName=yRole.firstDimensionName();var data=this.visibleData(dataCell.dataPartValue);def.scope(function(){return serRole.isBound()?data.children():def.query([data])}).each(genSeriesTrend,this);function genSeriesTrend(serData){var funX=function(datum){return datum.atoms[xDimName].value};var funY=function(datum){return datum.atoms[yDimName].value};var datums=serData.datums().sort(null,funX).array();var options=def.create(trendOptions,{rows:def.query(datums),x:funX,y:funY});var trendModel=trendInfo.model(options);if(trendModel){var dataPartAtom=data.owner.dimensions(dataPartDimName).intern(this.root._firstTrendAtomProto);datums.forEach(function(datum,index){var trendX=funX(datum);if(trendX){var trendY=trendModel.sample(trendX,funY(datum),index);if(trendY!=null){var atoms=def.set(Object.create(serData.atoms),xDimName,trendX,yDimName,trendY,dataPartDimName,dataPartAtom);newDatums.push(def.set(new pvc.data.Datum(data.owner,atoms),'isVirtual',true,'isTrend',true,'trendType',trendInfo.type))}}})}}}});
def.type('pvc.data.MetricPointChartTranslationOper').add({_meaLayoutRoles:['x','y','color','size'],configureType:function(){var itemTypes=this._itemTypes;var V=itemTypes.length;var freeMeaIndexes=[];var freeDisIndexes=[];def.range(0,V).each(function(j){if(!this._userUsedIndexes[j]){if(itemTypes[j]===1){freeMeaIndexes.push(j)}else{freeDisIndexes.push(j)}}},this);var N;var autoDimNames=[];var F=freeMeaIndexes.length;if(F>0){var R=this._meaLayoutRoles.length;var i=0;while(i<R&&autoDimNames.length<F){this._getUnboundRoleDefaultDimNames(this._meaLayoutRoles[i],1,autoDimNames);i++}N=autoDimNames.length;if(N>0){freeMeaIndexes.length=N;this.defReader({names:autoDimNames,indexes:freeMeaIndexes})}}F=freeDisIndexes.length;if(F>0){autoDimNames.length=0;this._getUnboundRoleDefaultDimNames('series',F,autoDimNames);N=autoDimNames.length;if(N>0){freeDisIndexes.length=N;this.defReader({names:autoDimNames,indexes:freeDisIndexes})}}}});
def.type('pvc.MetricPointPanel',pvc.CartesianAbstractPanel).init(function(chart,parent,plot,options){this.base(chart,parent,plot,options);this.axes.size=chart._getAxis('size',(plot.option('SizeAxis')||0)-1);var sizeRoleName=plot.option('SizeRole');this.visualRoles.size=chart.visualRoles(sizeRoleName);this.linesVisible=plot.option('LinesVisible');this.dotsVisible=plot.option('DotsVisible');if(!this.linesVisible&&!this.dotsVisible){this.linesVisible=true;plot.option.specify({'LinesVisible':true})}this.dotShape=plot.option('Shape');if(!this.offsetPaddings){this.offsetPaddings=new pvc.Sides(0.01)}}).add({pvLine:null,pvDot:null,pvLabel:null,pvScatterPanel:null,dotShape:"circle",sizeAxisRatio:1/5,sizeAxisRatioTo:'minWidthHeight',autoPaddingByDotSize:true,_v1DimRoleName:{'category':'x','value':'y'},_creating:function(){var groupScene=this.defaultVisibleBulletGroupScene();if(groupScene&&!groupScene.hasRenderer()){var colorAxis=groupScene.colorAxis;var drawMarker=def.nullyTo(colorAxis.option('LegendDrawMarker',true),this.dotsVisible);var drawRule=def.nullyTo(colorAxis.option('LegendDrawLine',true),this.linesVisible);if(drawMarker||drawRule){var keyArgs={};if((keyArgs.drawMarker=drawMarker)){keyArgs.markerShape=colorAxis.option('LegendShape',true)||'circle';keyArgs.markerPvProto=new pv.Dot().lineWidth(1.5,pvc.extensionTag).shapeSize(12,pvc.extensionTag);this.extend(keyArgs.markerPvProto,'dot',{constOnly:true})}if((keyArgs.drawRule=drawRule)){keyArgs.rulePvProto=new pv.Line().lineWidth(1.5,pvc.extensionTag);this.extend(keyArgs.rulePvProto,'line',{constOnly:true})}groupScene.renderer(new pvc.visual.legend.BulletItemDefaultRenderer(keyArgs))}}},_getRootScene:function(){var me=this;var rootScene=me._rootScene;if(!rootScene){var roles=me.visualRoles;var hasColorRole=roles.color.isBound()&&!me.axes.color.scale.isNull;var hasSizeRole=roles.size.isBound()&&!me.axes.size.scale.isNull;me._rootScene=rootScene=me._buildScene(hasColorRole,hasSizeRole)}return rootScene},_calcLayout:function(layoutInfo){var rootScene=this._getRootScene();if(rootScene.hasSizeRole){var areaRange=this._calcDotAreaRange(layoutInfo);this.sizeScale=this.axes.size.setScaleRange(areaRange).scale}this._calcAxesPadding(layoutInfo,rootScene)},_getDotDiameterRefLength:function(layoutInfo){var clientSize=layoutInfo.clientSize;var paddings=layoutInfo.paddings;switch(this.sizeAxisRatioTo){case'minWidthHeight':return Math.min(clientSize.width+paddings.width,clientSize.height+paddings.height);case'width':return clientSize.width+paddings.width;case'height':return clientSize.height+paddings.height}if(pvc.debug>=2){this._log(def.format("Invalid option 'sizeAxisRatioTo' value. Assuming 'minWidthHeight'.",[this.sizeAxisRatioTo]))}this.sizeRatioTo='minWidthHeight';return this._getDotDiameterRefLength(layoutInfo)},_calcDotRadiusRange:function(layoutInfo){var refLength=this._getDotDiameterRefLength(layoutInfo);var max=(this.sizeAxisRatio/2)*refLength;var min=Math.sqrt(12);return{min:min,max:max}},_calcDotAreaRange:function(layoutInfo){var radiusRange=this._calcDotRadiusRange(layoutInfo);if(this.dotShape==='diamond'){radiusRange.max/=Math.SQRT2;radiusRange.min/=Math.SQRT2}var maxArea=radiusRange.max*radiusRange.max,minArea=radiusRange.min*radiusRange.min,areaSpan=maxArea-minArea;if(areaSpan<=1){maxArea=Math.max(maxArea,2);minArea=1;areaSpan=maxArea-minArea;radiusRange={min:Math.sqrt(minArea),max:Math.sqrt(maxArea)};if(pvc.debug>=3){this._log("Using rescue mode dot area calculation due to insufficient space.")}}return{min:minArea,max:maxArea,span:areaSpan}},_calcAxesPadding:function(layoutInfo,rootScene){var requestPaddings;if(!this.autoPaddingByDotSize){requestPaddings=this._calcRequestPaddings(layoutInfo)}else{var axes=this.axes;var clientSize=layoutInfo.clientSize;var paddings=layoutInfo.paddings;requestPaddings={};axes.x.setScaleRange(clientSize.width);axes.y.setScaleRange(clientSize.height);var sceneXScale=axes.base.sceneScale({sceneVarName:'x'});var sceneYScale=axes.ortho.sceneScale({sceneVarName:'y'});var xLength=axes.base.scale.max;var yLength=axes.ortho.scale.max;var hasSizeRole=rootScene.hasSizeRole;var sizeScale=this.sizeScale;if(!hasSizeRole){var defaultSize=def.number.as(this._getExtension('dot','shapeRadius'),0);if(defaultSize<=0){defaultSize=def.number.as(this._getExtension('dot','shapeSize'),0);if(defaultSize<=0){defaultSize=12}}else{defaultSize=defaultSize*defaultSize}sizeScale=def.fun.constant(defaultSize)}requestPaddings={};var op;if(this.offsetPaddings){op={};pvc.Sides.names.forEach(function(side){var len_a=pvc.BasePanel.orthogonalLength[side];op[side]=(this.offsetPaddings[side]||0)*(clientSize[len_a]+paddings[len_a])},this)}var setSide=function(side,padding){if(op){padding+=(op[side]||0)}if(padding<0){padding=0}var value=requestPaddings[side];if(value==null||padding>value){requestPaddings[side]=padding}};var processScene=function(scene){var x=sceneXScale(scene);var y=sceneYScale(scene);var r=Math.sqrt(sizeScale(hasSizeRole?scene.vars.size.value:0));setSide('left',r-x);setSide('bottom',r-y);setSide('right',x+r-xLength);setSide('top',y+r-yLength)};rootScene.children().selectMany(function(seriesScene){return seriesScene.childNodes}).each(processScene)}layoutInfo.requestPaddings=requestPaddings},_createCore:function(){this.base();var myself=this;var chart=this.chart;var rootScene=this._getRootScene();this._finalizeScene(rootScene);this.pvPanel.zOrder(1);this.pvScatterPanel=new pvc.visual.Panel(this,this.pvPanel,{extensionId:'panel'}).lock('data',rootScene.childNodes).pvMark;var wrapper;if(this.compatVersion()<=1){wrapper=function(v1f){return function(dotScene){var d={category:dotScene.vars.x.rawValue,value:dotScene.vars.y.rawValue};var pseudo=Object.create(this);pseudo.index=dotScene.dataIndex;return v1f.call(pseudo,d)}}}var isLineNoSelect=chart._canSelectWithFocusWindow();var line=new pvc.visual.Line(this,this.pvScatterPanel,{extensionId:'line',wrapper:wrapper,noTooltip:false,noHover:true,noSelect:isLineNoSelect,showsSelection:!isLineNoSelect}).lock('data',function(seriesScene){return seriesScene.childNodes}).lock('visible',this.linesVisible).override('x',function(){return this.scene.basePosition}).override('y',function(){return this.scene.orthoPosition});this.pvLine=line.pvMark;var dot=new pvc.visual.Dot(this,this.pvLine,{extensionId:'dot',wrapper:wrapper,activeSeriesAware:this.linesVisible}).intercept('visible',function(){return!this.scene.isIntermediate&&this.delegateExtension(true)}).lock('shape',this.dotShape).override('x',function(){return this.scene.basePosition}).override('y',function(){return this.scene.orthoPosition}).override('color',function(type){if(!myself.dotsVisible){var visible=this.scene.isActive||this.scene.isSingle;if(!visible){return pvc.invisibleFill}}return this.base(type)});this.pvDot=dot.pvMark;this.pvDot.rubberBandSelectionMode='center';dot.override('defaultColor',function(type){var color=this.base(type);if(color&&type==='stroke'){color=color.darker()}return color}).override('interactiveColor',function(color,type){if(type==='stroke'&&this.scene.isActive){return color}return this.base(color,type)});if(!rootScene.hasSizeRole){dot.override('baseSize',function(){if(!myself.dotsVisible){if(this.scene.isSingle){var lineWidth=Math.max(myself.pvLine.scene[this.pvMark.index].lineWidth,0.2)/2;return lineWidth*lineWidth}}return this.base()})}else{var sizeAxis=myself.axes.size;if(sizeAxis.scaleUsesAbs()){dot.override('strokeColor',function(){return this.scene.vars.size.value<0?"#000000":this.base()}).optional('lineCap','round').optionalMark('strokeDasharray',function(scene){return scene.vars.size.value<0?'dot':null}).optionalMark('lineWidth',function(scene){return scene.vars.size.value<0?1.8:1.5})}var sizeScale=this.sizeScale;dot.override('baseSize',function(){return sizeScale(this.scene.vars.size.value)}).override('interactiveSize',function(size){if(this.scene.isActive){var radius=Math.sqrt(size)*1.1;return radius*radius}return size});this.pvPanel.borderPanel.overflow("hidden")}if(this.valuesVisible){var extensionIds=['label'];if(this.compatVersion()<=1){extensionIds.push('lineLabel')}this.pvLabel=new pvc.visual.Label(this,this.pvDot.anchor(this.valuesAnchor),{extensionId:extensionIds,wrapper:wrapper}).pvMark.font(this.valuesFont).text(function(scene){return def.string.join(",",scene.vars.x.label,scene.vars.y.label)})}},renderInteractive:function(){this.pvScatterPanel.render()},_getSelectableMarks:function(){var marks=[];marks.push(this.pvDot);if(this.linesVisible){marks.push(this.pvLine)}return marks},_finalizeScene:function(rootScene){var axes=this.axes,sceneBaseScale=axes.base.sceneScale({sceneVarName:'x'}),sceneOrthoScale=axes.ortho.sceneScale({sceneVarName:'y'});rootScene.children().selectMany(function(seriesScene){return seriesScene.childNodes}).each(function(leafScene){leafScene.basePosition=sceneBaseScale(leafScene);leafScene.orthoPosition=sceneOrthoScale(leafScene)});return rootScene},_buildScene:function(hasColorRole,hasSizeRole){var data=this.visibleData();var rootScene=new pvc.visual.Scene(null,{panel:this,group:data});rootScene.hasColorRole=hasColorRole;rootScene.hasSizeRole=hasSizeRole;var roles=this.visualRoles;var colorVarHelper=new pvc.visual.RoleVarHelper(rootScene,roles.color,{forceUnbound:!hasColorRole});var sizeVarHelper=new pvc.visual.RoleVarHelper(rootScene,roles.size,{forceUnbound:!hasSizeRole});var xDim=data.owner.dimensions(roles.x.firstDimensionName());var yDim=data.owner.dimensions(roles.y.firstDimensionName());data.children().each(createSeriesScene,this);rootScene.children().each(completeSeriesScenes,this);return rootScene;function createSeriesScene(seriesGroup){var seriesScene=new pvc.visual.Scene(rootScene,{group:seriesGroup});seriesScene.vars.series=pvc.visual.ValueLabelVar.fromComplex(seriesGroup);colorVarHelper.onNewScene(seriesScene,false);seriesGroup.datums().each(function(datum,dataIndex){var xAtom=datum.atoms[xDim.name];if(xAtom.value==null){return}var yAtom=datum.atoms[yDim.name];if(yAtom.value==null){return}var scene=new pvc.visual.Scene(seriesScene,{datum:datum});scene.dataIndex=dataIndex;scene.vars.x=Object.create(xAtom);scene.vars.y=Object.create(yAtom);sizeVarHelper.onNewScene(scene,true);colorVarHelper.onNewScene(scene,true);scene.isIntermediate=false})}function completeSeriesScenes(seriesScene){var seriesScenes=seriesScene.childNodes,fromScene;for(var c=0,toChildIndex=0,pointCount=seriesScenes.length;c<pointCount;c++,toChildIndex++){var toScene=seriesScenes[toChildIndex];toScene.isSingle=!fromScene&&!toScene.nextSibling;if(fromScene){var interScene=createIntermediateScene(seriesScene,fromScene,toScene,toChildIndex);if(interScene){toChildIndex++}}fromScene=toScene}}function createIntermediateScene(seriesScene,fromScene,toScene,toChildIndex){var interYValue=yDim.type.cast.call(null,((+toScene.vars.y.value)+(+fromScene.vars.y.value))/2);var interXValue=xDim.type.cast.call(null,((+toScene.vars.x.value)+(+fromScene.vars.x.value))/2);var interScene=new pvc.visual.Scene(seriesScene,{index:toChildIndex,datum:toScene.datum});interScene.dataIndex=toScene.dataIndex;interScene.vars.x=new pvc.visual.ValueLabelVar(interXValue,xDim.format(interXValue),interXValue);interScene.vars.y=new pvc.visual.ValueLabelVar(interYValue,yDim.format(interYValue),interYValue);sizeVarHelper.onNewScene(interScene,true);colorVarHelper.onNewScene(interScene,true);interScene.ownerScene=toScene;interScene.isIntermediate=true;interScene.isSingle=false;return interScene}}});
def.type('pvc.MetricPointAbstract',pvc.MetricXYAbstract).init(function(options){this.base(options);var parent=this.parent;if(parent){this._colorRole=parent._colorRole;this._sizeRole=parent._sizeRole}}).add({_initPlotsCore:function(){var pointPlot=this._createPointPlot();var trend=pointPlot.option('Trend');if(trend){new pvc.visual.MetricPointPlot(this,{name:'trend',fixed:{DataPart:'trend',TrendType:'none',NullInterpolatioMode:'none',ColorRole:'series',SizeRole:null,SizeAxis:null,OrthoAxis:1},defaults:{ColorAxis:2,LinesVisible:true,DotsVisible:false}})}},_hasDataPartRole:function(){return true},_getColorRoleSpec:function(){return{defaultSourceRole:'series',defaultDimension:'color*',dimensionDefaults:{valueType:Number}}},_initVisualRoles:function(){this.base();this._sizeRole=this._addVisualRole('size',{isMeasure:true,requireSingleDimension:true,requireIsDiscrete:false,defaultDimension:'size',dimensionDefaults:{valueType:Number}})},_getTranslationClass:function(translOptions){return def.type(this.base(translOptions)).add(pvc.data.MetricPointChartTranslationOper)},_initData:function(keyArgs){this.base(keyArgs);var sizeGrouping=this._sizeRole.grouping;if(sizeGrouping){this._sizeDim=this.data.dimensions(sizeGrouping.firstDimensionName())}},_collectPlotAxesDataCells:function(plot,dataCellsByAxisTypeThenIndex){this.base(plot,dataCellsByAxisTypeThenIndex);if(plot.type==='scatter'&&plot.option('DotsVisible')){var sizeRoleName=plot.option('SizeRole');if(sizeRoleName){var sizeRole=this.visualRoles(sizeRoleName);if(sizeRole.isBound()){var sizeDataCellsByAxisIndex=def.array.lazy(dataCellsByAxisTypeThenIndex,'size');def.array.lazy(sizeDataCellsByAxisIndex,plot.option('SizeAxis')-1).push({plot:plot,role:this.visualRoles(plot.option('SizeRole')),dataPartValue:plot.option('DataPart')})}}}},_setAxesScales:function(hasMultiRole){this.base(hasMultiRole);if(!hasMultiRole||this.parent){var sizeAxis=this.axes.size;if(sizeAxis&&sizeAxis.isBound()){this._createAxisScale(sizeAxis)}}},_createPlotPanels:function(parentPanel,baseOptions){var options=this.options;var panelOptions=def.set(Object.create(baseOptions),'sizeAxisRatio',options.sizeAxisRatio,'sizeAxisRatioTo',options.sizeAxisRatioTo,'autoPaddingByDotSize',options.autoPaddingByDotSize);var scatterPlot=this.plots.scatter;this.scatterChartPanel=new pvc.MetricPointPanel(this,parentPanel,scatterPlot,panelOptions);var trendPlot=this.plots.trend;if(trendPlot){new pvc.MetricPointPanel(this,parentPanel,trendPlot,Object.create(panelOptions))}},defaults:{axisOriginIsZero:false,tooltipOffset:10}});def.type('pvc.MetricDotChart',pvc.MetricPointAbstract).add({_createPointPlot:function(){return new pvc.visual.MetricPointPlot(this,{fixed:{DotsVisible:true}})}});def.type('pvc.MetricLineChart',pvc.MetricPointAbstract).add({_createPointPlot:function(){return new pvc.visual.MetricPointPlot(this,{fixed:{LinesVisible:true}})}});
def.type('pvc.BulletChart',pvc.BaseChart).init(function(options){options=options||{};var dimGroups=options.dimensionGroups||(options.dimensionGroups={});var rangeDimGroup=dimGroups.range||(dimGroups.range={});if(rangeDimGroup.valueType===undefined){rangeDimGroup.valueType=Number}var markerDimGroup=dimGroups.marker||(dimGroups.marker={});if(markerDimGroup.valueType===undefined){markerDimGroup.valueType=Number}this.base(options)}).add({bulletChartPanel:null,allowNoData:true,_processOptionsCore:function(options){this.base(options);options.legend=false;options.selectable=false},_initVisualRoles:function(){this.base();this._addVisualRole('title',{defaultDimension:'title*'});this._addVisualRole('subTitle',{defaultDimension:'subTitle*'});this._addVisualRole('value',{isMeasure:true,requireIsDiscrete:false,valueType:Number,defaultDimension:'value*'});this._addVisualRole('marker',{isMeasure:true,requireIsDiscrete:false,valueType:Number,defaultDimension:'marker*'});this._addVisualRole('range',{isMeasure:true,requireIsDiscrete:false,valueType:Number,defaultDimension:'range*'})},_createTranslation:function(translOptions){var translation=this.base(translOptions),size=translation.virtualItemSize();if(size){switch(size){case 1:translation.defReader({names:'value'});break;case 2:translation.defReader({names:['title','value']});break;case 3:translation.defReader({names:['title','value','marker']});break;default:translation.defReader({names:['title','subTitle','value','marker']});if(size>4){translation.defReader({names:'range',indexes:pv.range(4,size)})}break}}return translation},_initPlotsCore:function(hasMultiRole){new pvc.visual.BulletPlot(this)},_preRenderContent:function(contentOptions){var bulletPlot=this.plots.bullet;this.bulletChartPanel=new pvc.BulletChartPanel(this,this.basePanel,bulletPlot,def.create(contentOptions,{tooltipEnabled:this._tooltipEnabled}))},defaults:{compatVersion:1,orientation:'horizontal',bulletSize:30,bulletSpacing:50,bulletMargin:100,bulletTitle:"Title",bulletSubtitle:"",bulletTitlePosition:"left",tooltipFormat:function(s,c,v){return this.chart.options.valueFormat(v)},crosstabMode:false,seriesInRows:false}});def.type('pvc.BulletChartPanel',pvc.PlotPanel).add({pvBullets:null,pvBullet:null,data:null,onSelectionChange:null,_createCore:function(layoutInfo){var chart=this.chart,options=chart.options,data=this.buildData();var anchor=options.orientation=="horizontal"?"left":"bottom";var size,angle,align,titleLeftOffset,titleTopOffset,ruleAnchor,leftPos,topPos,titleSpace;if(options.orientation=="horizontal"){size=layoutInfo.clientSize.width-this.chart.options.bulletMargin-20;angle=0;switch(options.bulletTitlePosition){case'top':leftPos=this.chart.options.bulletMargin;titleLeftOffset=0;align='left';titleTopOffset=-12;titleSpace=parseInt(options.titleSize/2,10);break;case'bottom':leftPos=this.chart.options.bulletMargin;titleLeftOffset=0;align='left';titleTopOffset=options.bulletSize+32;titleSpace=0;break;case'right':leftPos=5;titleLeftOffset=size+5;align='left';titleTopOffset=parseInt(options.bulletSize/2,10);titleSpace=0;break;case'left':default:leftPos=this.chart.options.bulletMargin;titleLeftOffset=0;titleTopOffset=parseInt(options.bulletSize/2,10);align='right';titleSpace=0}ruleAnchor="bottom";topPos=function(){return(this.index*(options.bulletSize+options.bulletSpacing))+titleSpace}}else{size=layoutInfo.clientSize.height-this.chart.options.bulletMargin-20;switch(options.bulletTitlePosition){case'top':leftPos=this.chart.options.bulletMargin;titleLeftOffset=0;align='left';titleTopOffset=-20;angle=0;topPos=undefined;break;case'bottom':leftPos=this.chart.options.bulletMargin;titleLeftOffset=0;align='left';titleTopOffset=size+20;angle=0;topPos=20;break;case'right':leftPos=5;titleLeftOffset=this.chart.options.bulletSize+40;align='left';titleTopOffset=size;angle=-Math.PI/2;topPos=undefined;break;case'left':default:leftPos=this.chart.options.bulletMargin;titleLeftOffset=-12;titleTopOffset=this.height-this.chart.options.bulletMargin-20;align='left';angle=-Math.PI/2;topPos=undefined}ruleAnchor="right";leftPos=function(){return options.bulletMargin+this.index*(options.bulletSize+options.bulletSpacing)}}this.pvBullets=this.pvPanel.add(pv.Panel).data(data)[pvc.BasePanel.orthogonalLength[anchor]](size)[pvc.BasePanel.parallelLength[anchor]](this.chart.options.bulletSize).margin(20).left(leftPos).top(topPos);this.pvBullet=this.pvBullets.add(pv.Layout.Bullet).orient(anchor).ranges(function(d){return d.ranges}).measures(function(d){return d.measures}).markers(function(d){return d.markers});if(options.clickable&&this.clickAction){var me=this;this.pvBullet.cursor("pointer").event("click",function(d){var s=d.title;var c=d.subtitle;var ev=pv.event;return me.clickAction(s,c,d.measures,ev)})}this.pvBulletRange=this.pvBullet.range.add(pv.Bar);this.pvBulletMeasure=this.pvBullet.measure.add(pv.Bar).text(function(v,d){return d.formattedMeasures[this.index]});this.pvBulletMarker=this.pvBullet.marker.add(pv.Dot).shape("square").fillStyle("white").text(function(v,d){return d.formattedMarkers[this.index]});if(this.tooltipEnabled){var myself=this;this.pvBulletMeasure.localProperty('tooltip').tooltip(function(v,d){var s=d.title;var c=d.subtitle;return chart.options.tooltipFormat.call(myself,s,c,v)});this.pvBulletMarker.localProperty('tooltip').tooltip(function(v,d){var s=d.title;var c=d.subtitle;return chart.options.tooltipFormat.call(myself,s,c,v)});this.pvBulletMeasure.event("mouseover",pv.Behavior.tipsy(this.chart._tooltipOptions));this.pvBulletMarker.event("mouseover",pv.Behavior.tipsy(this.chart._tooltipOptions))}this.pvBulletRule=this.pvBullet.tick.add(pv.Rule);this.pvBulletRuleLabel=this.pvBulletRule.anchor(ruleAnchor).add(pv.Label).text(this.pvBullet.x.tickFormat);this.pvBulletTitle=this.pvBullet.anchor(anchor).add(pv.Label).font("bold 12px sans-serif").textAngle(angle).left(-10).textAlign(align).textBaseline("bottom").left(titleLeftOffset).top(titleTopOffset).text(function(d){return d.formattedTitle});this.pvBulletSubtitle=this.pvBullet.anchor(anchor).add(pv.Label).textStyle("#666").textAngle(angle).textAlign(align).textBaseline("top").left(titleLeftOffset).top(titleTopOffset).text(function(d){return d.formattedSubtitle});var doubleClickAction=(typeof(options.axisDoubleClickAction)=='function')?function(d,e){options.axisDoubleClickAction(d,e)}:null;if(options.clickable&&doubleClickAction){this.pvBulletTitle.cursor("pointer").events('all').event("dblclick",function(d){doubleClickAction(d,arguments[arguments.length-1])});this.pvBulletSubtitle.cursor("pointer").events('all').event("dblclick",function(d){doubleClickAction(d,arguments[arguments.length-1])})}},applyExtensions:function(){this.base();this.extend(this.pvBullets,"bulletsPanel");this.extend(this.pvBullet,"bulletPanel");this.extend(this.pvBulletRange,"bulletRange");this.extend(this.pvBulletMeasure,"bulletMeasure");this.extend(this.pvBulletMarker,"bulletMarker");this.extend(this.pvBulletRule,"bulletRule");this.extend(this.pvBulletRuleLabel,"bulletRuleLabel");this.extend(this.pvBulletTitle,"bulletTitle");this.extend(this.pvBulletSubtitle,"bulletSubtitle")},_getExtensionId:function(){return[{abs:'content'}].concat(this.base())},buildData:function(){var data,chart=this.chart,options=chart.options,titleRole=chart.visualRoles('title'),titleGrouping=titleRole.grouping,subTitleRole=chart.visualRoles('subTitle'),subTitleGrouping=subTitleRole.grouping,valueRole=chart.visualRoles('value'),valueGrouping=valueRole.grouping,markerRole=chart.visualRoles('marker'),markerGrouping=markerRole.grouping,rangeRole=chart.visualRoles('range'),rangeGrouping=rangeRole.grouping;var defaultData={title:options.bulletTitle,formattedTitle:options.bulletTitle,subtitle:options.bulletSubtitle,formattedSubtitle:options.bulletSubtitle,ranges:def.array.to(options.bulletRanges)||[],measures:def.array.to(options.bulletMeasures)||[],markers:def.array.to(options.bulletMarkers)||[]};def.set(defaultData,'formattedRanges',defaultData.ranges.map(String),'formattedMeasures',defaultData.measures.map(String),'formattedMarkers',defaultData.markers.map(String));if(!valueGrouping&&!titleGrouping&&!markerGrouping&&!subTitleGrouping&&!rangeGrouping){data=[defaultData]}else{data=chart.data.datums().select(function(datum){var d=Object.create(defaultData),view;if(valueGrouping){view=valueGrouping.view(datum);d.measures=view.values();d.formattedMeasures=view.labels()}if(titleGrouping){view=titleGrouping.view(datum);d.title=view.value;d.formattedTitle=view.label}if(subTitleGrouping){view=subTitleGrouping.view(datum);d.subtitle=view.value;d.formattedSubtitle=view.label}if(markerGrouping){view=markerGrouping.view(datum);d.markers=view.values();d.formattedMarkers=view.labels()}if(rangeGrouping){view=rangeGrouping.view(datum);d.ranges=view.values();d.formattedRanges=view.labels()}return d},this).array()}return data}});
def.type('pvc.ParallelCoordinates',pvc.BaseChart).init(function(options){options=options||{};options.dimensions=options.dimensions||{};if(!options.dimensions.value){options.dimensions.value={valueType:null}}this.base(options)}).add({parCoordPanel:null,_preRenderContent:function(contentOptions){this.parCoordPanel=new pvc.ParCoordPanel(this,this.basePanel,def.create(contentOptions,{topRuleOffset:this.options.topRuleOffset,botRuleOffset:this.options.botRuleOffset,leftRuleOffset:this.options.leftRuleOffset,rightRuleOffset:this.options.rightRuleOffset,sortCategorical:this.options.sortCategorical,mapAllDimensions:this.options.mapAllDimensions,numDigits:this.options.numDigits}))},defaults:def.create(pvc.BaseChart.prototype.defaults,{compatVersion:1,topRuleOffset:30,botRuleOffset:30,leftRuleOffset:60,rightRuleOffset:60,sortCategorical:true,mapAllDimensions:true,numDigits:0})});def.type('pvc.ParCoordPanel',pvc.BasePanel).add({anchor:'fill',pvParCoord:null,dimensions:null,dimensionDescr:null,data:null,retrieveData:function(){var data=this.chart.data;var numDigit=this.chart.options.numDigits;this.dimensions=data.getVisibleCategories();var values=data.getValues();var dataRowIndex=data.getVisibleSeriesIndexes();var pCoordIndex=data.getVisibleCategoriesIndexes();var pCoordKeys=data.getCategories();var pCoordMapping=this.chart.options.mapAllDimensions?pCoordIndex.map(function(d){return isNaN(values[d][0])?{categorical:true,len:0,map:[]}:{categorical:false,len:0,map:[],displayValue:[]}}):pCoordIndex.map(function(d){return isNaN(values[d][0])?{categorical:true,len:0,map:[]}:null});var coordMapUpdate=function(i,val){var cMap=pCoordMapping[i];var k=null;if(!cMap.categorical){var keyVal=val.toFixed(numDigit);k=cMap.map[keyVal];if(k==null){k=cMap.len;cMap.len++;cMap.map[keyVal]=k;cMap.displayValue[keyVal]=val}}else{k=cMap.map[val];if(k==null){k=cMap.len;cMap.len++;cMap.map[val]=k}}return k};for(var d in pCoordMapping){if(pCoordMapping.hasOwnProperty(d)&&pCoordMapping[d]&&pCoordMapping[d].categorical){pCoordMapping[d].displayValue=pCoordMapping[d].map}}var i,item,k;if(this.chart.options.sortCategorical||this.chart.options.mapAllDimensions){for(i=0;i<pCoordMapping.length;i++){if(pCoordMapping[i]){for(var col=0;col<values[i].length;col++){coordMapUpdate(i,values[i][col])}var cMap=pCoordMapping[i].map;var sorted=[];for(item in cMap){if(cMap.hasOwnProperty(item)){sorted.push(item)}}sorted.sort();if(pCoordMapping[i].categorical){for(k=0;k<sorted.length;k++){cMap[sorted[k]]=k}}else{for(k=0;k<sorted.length;k++){cMap[sorted[k]].index=k}}}}}var generateHashMap=function(col){var record={};for(var j in pCoordIndex){if(pCoordIndex.hasOwnProperty(j)){record[pCoordKeys[j]]=(pCoordMapping[j])?coordMapUpdate(j,values[j][col]):values[j][col]}}return record};this.data=dataRowIndex.map(function(col){return generateHashMap(col)});var descrVals=this.dimensions.map(function(cat){var item2={};var elements=cat.split("__");item2.id=cat;item2.name=elements[0];item2.unit=(elements.length>1)?elements[1]:"";return item2});for(i=0;i<descrVals.length;i++){item=descrVals[i];var index=pCoordIndex[i];item.orgRowIndex=index;var len=values[index].length;var theMin,theMax,theMin2,theMax2;var v;if(pCoordMapping[index]){theMin=theMax=theMin2=theMax2=pCoordMapping[index].displayValue[values[index][0]];for(k=1;k<len;k++){v=pCoordMapping[index].displayValue[values[index][k]];if(v<theMin){theMin2=theMin;theMin=v}if(v>theMax){theMax2=theMax;theMax=v}}}else{theMin=theMax=theMin2=theMax2=values[index][0];for(k=1;k<len;k++){v=values[index][k];if(v<theMin){theMin2=theMin;theMin=v}if(v>theMax){theMax2=theMax;theMax=v}}}var theStep=((theMax-theMax2)+(theMin2-theMin))/2;item.min=theMin;item.max=theMax;item.step=theStep;item.categorical=false;if(pCoordMapping[index]){item.map=pCoordMapping[index].map;item.mapLength=pCoordMapping[index].len;item.categorical=pCoordMapping[index].categorical;if(!item.categorical){item.orgValue=[];var theMap=pCoordMapping[index].map;for(var key in theMap){if(theMap.hasOwnProperty(key)){item.orgValue[theMap[key]]=0.0+key}}}}}var genKeyVal=function(keys,vals){var record={};for(var i=0;i<keys.length;i++){record[keys[i]]=vals[i]}return record};this.dimensionDescr=genKeyVal(this.dimensions,descrVals)},_createCore:function(){var myself=this;this.retrieveData();var height=this.height,numDigits=this.chart.options.numDigits,topRuleOffs=this.chart.options.topRuleOffset,botRuleOffs=this.chart.options.botRuleOffset,leftRuleOffs=this.chart.options.leftRuleOffset,rightRulePos=this.width-this.chart.options.rightRuleOffset,topRulePos=this.height-topRuleOffs,ruleHeight=topRulePos-botRuleOffs,labelTopOffs=topRuleOffs-12,dims=this.dimensions,dimDescr=this.dimensionDescr;var getDimSc=function(t,addMargin){var theMin=dimDescr[t].min;var theMax=dimDescr[t].max;var theStep=dimDescr[t].step;if(addMargin){theMin-=theStep;theMax+=theStep}return pv.Scale.linear(theMin,theMax).range(botRuleOffs,topRulePos)};var getDimensionScale=function(t){var scale=getDimSc(t,true).range(botRuleOffs,topRulePos);var dd=dimDescr[t];if(dd.orgValue&&!dd.categorical){var func=function(x){var res=scale(dd.orgValue[x]);return res};func.domain=function(){return scale.domain()};func.invert=function(d){return scale.invert(d)};return func}return scale};var getDimColorScale=function(t){var scale=getDimSc(t,false).range("steelblue","brown");return scale};var x=pv.Scale.ordinal(dims).splitFlush(leftRuleOffs,rightRulePos);var y=pv.dict(dims,getDimensionScale);var colors=pv.dict(dims,getDimColorScale);var filter=pv.dict(dims,function(t){return{min:y[t].domain()[0],max:y[t].domain()[1]}});var active=dims[0];var selectVisible=this.chart.options.mapAllDimensions?function(d){return dims.every(function(t){var dd=dimDescr[t];var val=(dd.orgValue&&!dd.categorical)?dd.orgValue[d[t]]:d[t];return(val>=filter[t].min)&&(val<=filter[t].max)})}:function(d){return dims.every(function(t){return(d[t]>=filter[t].min)&&(d[t]<=filter[t].max)})};var auxData=null;this.pvParCoord=this.pvPanel.add(pv.Panel).data(myself.data).visible(selectVisible).add(pv.Line).data(dims).left(function(t,d){return x(t)}).bottom(function(t,d){var res=y[t](d[t]);return res}).strokeStyle("#ddd").lineWidth(1).antialias(false);var rule=this.pvPanel.add(pv.Rule).data(dims).left(x).top(topRuleOffs).bottom(botRuleOffs);rule.anchor("top").add(pv.Label).top(labelTopOffs).font("bold 10px sans-serif").text(function(d){return dimDescr[d].name});var labels=[];var labelXoffs=6,labelYoffs=3;for(var d in dimDescr){if(dimDescr.hasOwnProperty(d)){var dim=dimDescr[d];if(dim.categorical){var xVal=x(dim.id)+labelXoffs;for(var l in dim.map){if(dim.map.hasOwnProperty(l)){labels[labels.length]={x:xVal,y:y[dim.id](dim.map[l])+labelYoffs,label:l}}}}}}var dimLabels=this.pvPanel.add(pv.Panel).data(labels).add(pv.Label).left(function(d){return d.x}).bottom(function(d){return d.y}).text(function(d){return d.label}).textAlign("left");var change=this.pvPanel.add(pv.Panel);var line=change.add(pv.Panel).data(myself.data).visible(selectVisible).add(pv.Line).data(dims).left(function(t,d){return x(t)}).bottom(function(t,d){return y[t](d[t])}).strokeStyle(function(t,d){var dd=dimDescr[active];var val=(dd.orgValue&&!dd.categorical)?dd.orgValue[d[active]]:d[active];return colors[active](val)}).lineWidth(1);function update(d){var t=d.dim;filter[t].min=Math.max(y[t].domain()[0],y[t].invert(height-d.y-d.dy));filter[t].max=Math.min(y[t].domain()[1],y[t].invert(height-d.y));active=t;change.render();return false}function selectAll(d){if(d.dy<3){var t=d.dim;filter[t].min=Math.max(y[t].domain()[0],y[t].invert(0));filter[t].max=Math.min(y[t].domain()[1],y[t].invert(height));d.y=botRuleOffs;d.dy=ruleHeight;active=t;change.render()}return false}var handle=change.add(pv.Panel).data(dims.map(function(dim){return{y:botRuleOffs,dy:ruleHeight,dim:dim}})).left(function(t){return x(t.dim)-30}).width(60).fillStyle("rgba(0,0,0,.001)").cursor("crosshair").event("mousedown",pv.Behavior.select()).event("select",update).event("selectend",selectAll).add(pv.Bar).left(25).top(function(d){return d.y}).width(10).height(function(d){return d.dy}).fillStyle(function(t){return(t.dim==active)?colors[t.dim]((filter[t.dim].max+filter[t.dim].min)/2):"hsla(0,0,50%,.5)"}).strokeStyle("white").cursor("move").event("mousedown",pv.Behavior.drag()).event("dragstart",update).event("drag",update);handle.anchor("bottom").add(pv.Label).textBaseline("top").text(function(d){return(dimDescr[d.dim].categorical)?"":filter[d.dim].min.toFixed(numDigits)+dimDescr[d.dim].unit});handle.anchor("top").add(pv.Label).textBaseline("bottom").text(function(d){return(dimDescr[d.dim].categorical)?"":filter[d.dim].max.toFixed(numDigits)+dimDescr[d.dim].unit});this.extend(this.pvParCoord,"parCoord");this.extend(this.pvPanel,"chart")}});
def.type('pvc.DataTree',pvc.BaseChart).init(function(options){options=options||{};options.dimensionGroups=options.dimensionGroups||{};if(!options.dimensionGroups.value){options.dimensionGroups.value={valueType:null}}this.base(options)}).add({structEngine:null,structMetadata:null,structDataset:null,DataTreePanel:null,_getColorRoleSpec:function(){return{isRequired:true,defaultSourceRole:'category',requireIsDiscrete:true}},setStructData:function(data){this.structDataset=data.resultset;if(!this.structDataset.length){this._log("Warning: Structure-dataset is empty")}this.structMetadata=data.metadata;if(!this.structMetadata.length){this._log("Warning: Structure-Metadata is empty")}},_preRenderContent:function(contentOptions){var structEngine=this.structEngine;var structType=structEngine?structEngine.type:new pvc.data.ComplexType();structType.addDimension('value',{});var translOptions={seriesInRows:true,crosstabMode:true};var translation=new pvc.data.CrosstabTranslationOper(structType,this.structDataset,this.structMetadata,translOptions);translation.configureType();if(!structEngine){structEngine=this.structEngine=new pvc.data.Data({type:structType})}structEngine.load(translation.execute(structEngine));if(pvc.debug>=3){this._log(this.structEngine.getInfo())}this.dataTreePanel=new pvc.DataTreePanel(this,this.basePanel,def.create(contentOptions,{topRuleOffset:this.options.topRuleOffset,botRuleOffset:this.options.botRuleOffset,leftRuleOffset:this.options.leftRuleOffset,rightRuleOffset:this.options.rightRuleOffset,boxplotColor:this.options.boxplotColor,valueFontsize:this.options.valueFontsize,headerFontsize:this.options.headerFontsize,border:this.options.border,perpConnector:this.options.perpConnector,numDigits:this.options.numDigits,minVerticalSpace:this.options.minVerticalSpace,connectorSpace:this.options.connectorSpace,minAspectRatio:this.options.minAspectRatio}))},defaults:{compatVersion:1,topRuleOffset:30,botRuleOffset:30,leftRuleOffset:60,rightRuleOffset:60,boxplotColor:"grey",headerFontsize:16,valueFontsize:20,border:2,perpConnector:false,numDigits:0,connectorSpace:0.15,minVerticalSpace:0.05,minAspectRatio:2.0}});def.type('pvc.DataTreePanel',pvc.PlotPanel).add({pvDataTree:null,treeElements:null,structMap:null,structArr:null,hRules:null,vRules:null,rules:null,generatePerpConnectors:function(leftLength){this.hRules=[];this.vRules=[];this.rules=[];for(var e in this.structMap){var elem=this.structMap[e];if(elem.children!=null){var min=+10000,max=-10000;var theLeft=elem.left+elem.width;this.hRules.push({"left":theLeft,"width":leftLength,"bottom":elem.bottom+elem.height/2});theLeft+=leftLength;for(var i in elem.children){var child=this.structMap[elem.children[i]];var theBottom=child.bottom+child.height/2;if(theBottom>max){max=theBottom}if(theBottom<min){min=theBottom}this.hRules.push({"left":theLeft,"width":child.left-theLeft,"bottom":theBottom})}if(max>min){this.vRules.push({"left":theLeft,"bottom":min,"height":max-min})}}}},generateLineSegment:function(x1,y1,x2,y2){var line=[];line.push({"x":x1,"y":y1});line.push({"x":x2,"y":y2});this.rules.push(line)},generateConnectors:function(leftLength){this.hRules=[];this.vRules=[];if(this.chart.options.perpConnector){this.generatePerpConnectors(leftLength);return}this.rules=[];for(var e in this.structMap){var elem=this.structMap[e];if(elem.children!=null){var theCenter,child,i;var min=+10000,max=-10000;for(i in elem.children){child=this.structMap[elem.children[i]];theCenter=child.bottom+child.height/2;if(theCenter>max){max=theCenter}if(theCenter<min){min=theCenter}}var mid=(max+min)/2;var theLeft1=elem.left+elem.width;var theLeft2=theLeft1+leftLength;this.generateLineSegment(theLeft1,elem.bottom+elem.height/2,theLeft2,mid);for(i in elem.children){child=this.structMap[elem.children[i]];theCenter=child.bottom+child.height/2;this.generateLineSegment(theLeft2,mid,child.left,theCenter)}}}},retrieveStructure:function(){var data=this.chart.structEngine;var options=this.chart.options;var colLabels=data.getVisibleCategories();this.treeElements=data.getVisibleSeries();var values=data.getValues();var bottomHeightSpecified=(colLabels.length>4);var e;for(e in this.treeElements){this.treeElements[e]=$.trim(this.treeElements[e])}var bounds=[];bounds.getElement=function(label){if(bounds[label]==null){bounds[label]={"min":+10000,"max":-10000}}return bounds[label]};bounds.addValue=function(label,value){var bnd=bounds.getElement(label);if(value<bnd.min){bnd.min=value}if(value>bnd.max){bnd.max=value}return bnd};var col,colnr,elem,row;for(e in this.treeElements){elem=this.treeElements[e];col=elem[0];colnr=col.charCodeAt(0);row=parseInt(elem.slice(1),10);bounds.addValue("__cols",colnr);bounds.addValue(col,row)}var bnds=bounds.getElement("__cols");var gridWidth=this.innerWidth/(bnds.max-bnds.min+1);var connectorWidth=options.connectorSpace*gridWidth;var cellWidth=gridWidth-connectorWidth;var maxCellHeight=cellWidth/options.minAspectRatio;var colBase=bnds.min;delete bounds.__cols;for(e in bounds){bnds=bounds[e];if(typeof bnds=="function"){continue}var numRows=bnds.max-bnds.min+1;bnds.gridHeight=this.innerHeight/numRows;bnds.cellHeight=bnds.gridHeight*(1.0-options.minVerticalSpace);if(bnds.cellHeight>maxCellHeight){bnds.cellHeight=maxCellHeight}bnds.relBottom=(bnds.gridHeight-bnds.cellHeight)/2;bnds.numRows=numRows}var whitespaceQuote=new RegExp('[\\s\"\']+',"g");this.structMap={};for(e in this.treeElements){var box={};elem=this.treeElements[e];box.box_id=elem;this.structMap[elem]=box;col=elem[0];colnr=col.charCodeAt(0);row=parseInt(elem.slice(1),10);bnds=bounds.getElement(col);box.colIndex=colnr-colBase;box.rowIndex=bnds.numRows-(row-bnds.min)-1;box.left=this.leftOffs+box.colIndex*gridWidth;box.width=cellWidth;if(bottomHeightSpecified){box.bottom=values[4][e];box.height=values[5][e]}else{box.bottom=this.botOffs+box.rowIndex*bnds.gridHeight+bnds.relBottom;box.height=bnds.cellHeight}box.label=values[0][e];box.selector=values[1][e];box.aggregation=values[2][e];var children=(values[3][e]||'').replace(whitespaceQuote," ");box.children=(children===" "||children==="")?null:children.split(" ")}this.generateConnectors((gridWidth-cellWidth)/2);this.structArr=[];for(e in this.structMap){elem=this.structMap[e];this.structArr.push(elem)}},findDataValue:function(key,data){for(var i=0;i<data[0].length;i++){if(data[0][i]==key){return data[1][i]}}this._log("Error: value with key : "+key+" not found.")},generateBoxPlots:function(){var options=this.chart.options;for(var e in this.structArr){var elem=this.structArr[e];if(!elem.values.length){continue}elem.subplot={};var sp=elem.subplot;var dat=[];var margin=15;var rlMargin=elem.width/6;sp.hRules=[];sp.vRules=[];sp.marks=[];sp.labels=[];dat.push(this.findDataValue("_p5",elem.values));dat.push(this.findDataValue("_p25",elem.values));dat.push(this.findDataValue("_p50",elem.values));dat.push(this.findDataValue("_p75",elem.values));dat.push(this.findDataValue("_p95",elem.values));var noBox=false;if(typeof(dat[2])!="undefined"){if(dat[4]<dat[0]){dat=dat.reverse();this._log(" dataset "+elem.box_id+" repaired (_p95 was smaller than _p5)")}if(dat[4]>dat[0]){sp.hScale=pv.Scale.linear(dat[0],dat[4])}else{noBox=true;sp.hScale=pv.Scale.linear(dat[0]-1e-10,dat[0]+1e-10)}sp.hScale.range(elem.left+rlMargin,elem.left+elem.width-rlMargin);var avLabel=""+dat[2];var i;for(i=0;i<dat.length;i++){dat[i]=sp.hScale(dat[i])}sp.bot=elem.bottom+elem.height/3;sp.top=elem.bottom+2*elem.height/3;sp.mid=(sp.top+sp.bot)/2; sp.textBottom=elem.bottom+margin;sp.textBottom=sp.bot-options.valueFontsize-1;var lwa=3;if(noBox){sp.vRules.push({"left":dat[0],"bottom":sp.bot,"lWidth":lwa,"height":sp.top-sp.bot})}else{sp.hRules.push({"left":dat[0],"width":dat[1]-dat[0],"lWidth":1,"bottom":sp.mid});sp.hRules.push({"left":dat[1],"width":dat[3]-dat[1],"lWidth":1,"bottom":sp.bot});sp.hRules.push({"left":dat[1],"width":dat[3]-dat[1],"lWidth":1,"bottom":sp.top});sp.hRules.push({"left":dat[3],"width":dat[4]-dat[3],"lWidth":1,"bottom":sp.mid});for(i=0;i<dat.length;i++){sp.vRules.push({"left":dat[i],"bottom":sp.bot,"lWidth":(i==2)?lwa:1,"height":sp.top-sp.bot})}}sp.labels.push({left:dat[2],bottom:sp.textBottom,text:this.labelFixedDigits(avLabel),size:options.smValueFont,color:options.boxplotColor})}}},labelFixedDigits:function(value){if(typeof value=="string"){value=parseFloat(value)}if(typeof value=="number"){var nd=this.chart.options.numDigits;value=value.toFixed(nd)}return""+value},addDataPoint:function(key){var options=this.chart.options;for(var e in this.structArr){var elem=this.structArr[e];if(!elem.values.length){continue}var value=this.findDataValue(key,elem.values);if(typeof value=="undefined"){continue}var sp=elem.subplot;var theLeft=sp.hScale(value);var theColor="green";sp.marks.push({left:theLeft,bottom:sp.mid,color:theColor});sp.labels.push({left:theLeft,bottom:sp.textBottom,text:this.labelFixedDigits(value),size:options.valueFont,color:theColor})}},retrieveData:function(){var data=this.chart.data;var options=this.chart.options;var colLabels=data.getVisibleCategories();var selectors=data.getVisibleSeries();var values=data.getValues();var selMap={};var i;var numCols=values.length;for(var e in this.structArr){var elem=this.structArr[e];elem.values=[];for(i=0;i<numCols;i++){elem.values.push([])}selMap[elem.selector]=elem}var boxNotFound={};for(i in selectors){var box=selMap[selectors[i]];if(typeof(box)!="undefined"){for(var j in values){box.values[j].push(values[j][i])}}else{boxNotFound[selectors[i]]=true}}for(var sel in boxNotFound){this._log("Could'nt find box for selector: "+sel)}this.generateBoxPlots();var whitespaceQuote=new RegExp('[\\s\"\']+',"g");if(options.selectParam){var selPar=options.selectParam.replace(whitespaceQuote,'');if((selPar!="undefined")&&(selPar.length>0)&&(typeof window[selPar]!="undefined")){selPar=window[selPar];this.addDataPoint(selPar)}}},_createCore:function(){var myself=this;var options=this.chart.options;options.smValueFontsize=Math.round(0.6*options.valueFontsize);options.smValueFont=""+options.smValueFontsize+"px sans-serif";options.valueFont=""+options.valueFontsize+"px sans-serif";var topRuleOffs=options.topRuleOffset,botRuleOffs=options.botRuleOffset,leftRuleOffs=options.leftRuleOffset;this.innerWidth=this.width-leftRuleOffs-options.rightRuleOffset;this.innerHeight=this.height-topRuleOffs-botRuleOffs;this.botOffs=botRuleOffs;this.leftOffs=leftRuleOffs;this.retrieveStructure();this.retrieveData();var topMargin=options.headerFontsize+3;var rules=this.rules;var i;for(i=0;i<rules.length;i++){this.pvPanel.add(pv.Line).data(rules[i]).left(function(d){return d.x}).bottom(function(d){return d.y}).lineWidth(1).strokeStyle("black")}this.pvDataTree=this.pvPanel.add(pv.Bar).data(myself.structArr).left(function(d){return d.left}).bottom(function(d){return d.bottom}).height(function(d){return d.height}).width(function(d){return d.width}).fillStyle("green").add(pv.Bar).left(function(d){return d.left+options.border}).bottom(function(d){return d.bottom+options.border}).height(function(d){return d.height-options.border-topMargin}).width(function(d){return d.width-2*options.border}).fillStyle("white").add(pv.Label).text(function(d){return d.label}).textAlign("center").left(function(d){return d.left+d.width/2}).bottom(function(d){return d.bottom+d.height-options.headerFontsize-5+options.headerFontsize/5}).font(""+options.headerFontsize+"px sans-serif").textStyle("white").fillStyle("blue");for(i=0;i<this.structArr.length;i++){var box=this.structArr[i];this.pvPanel.add(pv.Rule).data(box.subplot.hRules).left(function(d){return d.left}).width(function(d){return d.width}).bottom(function(d){return d.bottom}).lineWidth(function(d){return d.lWidth}).strokeStyle(myself.chart.options.boxplotColor);this.pvPanel.add(pv.Rule).data(box.subplot.vRules).left(function(d){return d.left}).height(function(d){return d.height}).bottom(function(d){return d.bottom}).lineWidth(function(d){return d.lWidth}).strokeStyle(myself.chart.options.boxplotColor);this.pvPanel.add(pv.Dot).data(box.subplot.marks).left(function(d){return d.left}).bottom(function(d){return d.bottom}).fillStyle(function(d){return d.color});this.pvPanel.add(pv.Label).data(box.subplot.labels).left(function(d){return d.left}).bottom(function(d){return d.bottom}).font(function(d){return d.size}).text(function(d){return d.text}).textAlign("center").textStyle(function(d){return d.color})}if(options.perpConnector){this.pvPanel.add(pv.Rule).data(myself.vRules).left(function(d){return d.left}).bottom(function(d){return d.bottom}).height(function(d){return d.height}).strokeStyle("black");this.pvPanel.add(pv.Rule).data(myself.hRules).left(function(d){return d.left}).bottom(function(d){return d.bottom}).width(function(d){return d.width}).strokeStyle("black")}},applyExtensions:function(){this.extend(this.pvDataTree,"dataTree")}});
def.type('pvc.data.BoxplotChartTranslationOper').add({_configureTypeCore:function(){var autoDimNames=[];var V=this.virtualItemSize();var C=V-this.M;this._getUnboundRoleDefaultDimNames('category',C,autoDimNames);pvc.BoxplotChart.measureRolesNames.forEach(function(roleName){this._getUnboundRoleDefaultDimNames(roleName,1,autoDimNames)},this);autoDimNames.slice(0,this.freeVirtualItemSize());if(autoDimNames.length){this.defReader({names:autoDimNames})}}});
def.type('pvc.BoxplotPanel',pvc.CategoricalAbstractPanel).init(function(chart,parent,plot,options){this.base(chart,parent,plot,options);this.boxSizeRatio=plot.option('BoxSizeRatio');this.maxBoxSize=plot.option('BoxSizeMax')}).add({plotType:'box',anchor:'fill',_v1DimRoleName:{'value':'median'},_createCore:function(){this.base();var rootScene=this._buildScene();var a_bottom=this.isOrientationVertical()?"bottom":"left",a_left=this.anchorOrtho(a_bottom),a_width=this.anchorLength(a_bottom),a_height=this.anchorOrthoLength(a_bottom);function defaultColor(type){var color=this.base(type);return type==='stroke'?color.darker(1):color}var extensionIds=['panel'];if(this.compatVersion()<=1){extensionIds.push('')}this.pvBoxPanel=new pvc.visual.Panel(this,this.pvPanel,{extensionId:extensionIds}).lock('data',rootScene.childNodes).lockMark(a_left,function(scene){var catVar=scene.vars.category;return catVar.x-catVar.width/2}).pvMark[a_width](function(scene){return scene.vars.category.width});function setupRuleWhisker(rule){rule.lock(a_left,function(){return this.pvMark.parent[a_width]()/2}).override('defaultColor',defaultColor);return rule}this.pvRuleWhiskerUpper=setupRuleWhisker(new pvc.visual.Rule(this,this.pvBoxPanel,{extensionId:'boxRuleWhisker',freePosition:true,noHover:false,noSelect:false,noClick:false,noDoubleClick:false})).intercept('visible',function(scene){return scene.vars.category.showRuleWhiskerUpper&&this.delegateExtension(true)}).lock(a_bottom,function(scene){return scene.vars.category.ruleWhiskerUpperBottom}).lock(a_height,function(scene){return scene.vars.category.ruleWhiskerUpperHeight}).pvMark;this.pvRuleWhiskerLower=setupRuleWhisker(new pvc.visual.Rule(this,this.pvBoxPanel,{extensionId:'boxRuleWhisker',freePosition:true,noHover:false,noSelect:false,noClick:false,noDoubleClick:false})).intercept('visible',function(scene){return scene.vars.category.showRuleWhiskerBelow&&this.delegateExtension(true)}).lock(a_bottom,function(scene){return scene.vars.category.ruleWhiskerLowerBottom}).lock(a_height,function(scene){return scene.vars.category.ruleWhiskerLowerHeight}).pvMark;function setupHCateg(sign){sign.lock(a_left,function(scene){return scene.vars.category.boxLeft}).lock(a_width,function(scene){return scene.vars.category.boxWidth});return sign}this.pvBar=setupHCateg(new pvc.visual.Bar(this,this.pvBoxPanel,{extensionId:'boxBar',freePosition:true,normalStroke:true})).intercept('visible',function(scene){return scene.vars.category.showBox&&this.delegateExtension(true)}).lock(a_bottom,function(scene){return scene.vars.category.boxBottom}).lock(a_height,function(scene){return scene.vars.category.boxHeight}).override('defaultColor',defaultColor).override('defaultStrokeWidth',def.fun.constant(1)).pvMark;function setupHRule(rule){setupHCateg(rule);rule.override('defaultColor',defaultColor);return rule}this.pvRuleMin=setupHRule(new pvc.visual.Rule(this,this.pvBoxPanel,{extensionId:'boxRuleMin',freePosition:true,noHover:false,noSelect:false,noClick:false,noDoubleClick:false})).intercept('visible',function(){return this.scene.vars.minimum.value!=null&&this.delegateExtension(true)}).lock(a_bottom,function(){return this.scene.vars.minimum.position}).pvMark;this.pvRuleMax=setupHRule(new pvc.visual.Rule(this,this.pvBoxPanel,{extensionId:'boxRuleMax',freePosition:true,noHover:false,noSelect:false,noClick:false,noDoubleClick:false})).intercept('visible',function(){return this.scene.vars.maximum.value!=null&&this.delegateExtension(true)}).lock(a_bottom,function(){return this.scene.vars.maximum.position}).pvMark;this.pvRuleMedian=setupHRule(new pvc.visual.Rule(this,this.pvBoxPanel,{extensionId:'boxRuleMedian',freePosition:true,noHover:false,noSelect:false,noClick:false,noDoubleClick:false})).intercept('visible',function(){return this.scene.vars.median.value!=null&&this.delegateExtension(true)}).lock(a_bottom,function(){return this.scene.vars.median.position}).override('defaultStrokeWidth',def.fun.constant(2)).pvMark},renderInteractive:function(){this.pvBoxPanel.render()},_getSelectableMarks:function(){return[this.pvBar]},_buildScene:function(){var chart=this.chart,measureRolesDimNames=def.query(chart.measureVisualRoles()).object({name:function(role){return role.name},value:function(role){return role.firstDimensionName()}}),visibleKeyArgs={visible:true,zeroIfNone:false},data=this.visibleData(),rootScene=new pvc.visual.Scene(null,{panel:this,group:data}),baseScale=this.axes.base.scale,bandWidth=baseScale.range().band,boxWidth=Math.min(bandWidth*this.boxSizeRatio,this.maxBoxSize),orthoScale=this.axes.ortho.scale,colorVarHelper=new pvc.visual.RoleVarHelper(chart,chart._colorRole);data.children().each(createCategScene,this);return rootScene;function createCategScene(categData){var categScene=new pvc.visual.Scene(rootScene,{group:categData});var vars=categScene.vars;vars.series=new pvc.visual.ValueLabelVar(null,"");var catVar=vars.category=new pvc.visual.ValueLabelVar(categData.value,categData.label);def.set(catVar,'group',categData,'x',baseScale(categData.value),'width',bandWidth,'boxWidth',boxWidth,'boxLeft',bandWidth/2-boxWidth/2);chart.measureVisualRoles().forEach(function(role){var dimName=measureRolesDimNames[role.name],svar;if(dimName){var dim=categData.dimensions(dimName),value=dim.sum(visibleKeyArgs);svar=new pvc.visual.ValueLabelVar(value,dim.format(value));svar.position=orthoScale(value)}else{svar=new pvc.visual.ValueLabelVar(null,"");svar.position=null}vars[role.name]=svar});colorVarHelper.onNewScene(categScene,true);var hasMin=vars.minimum.value!=null,hasLower=vars.lowerQuartil.value!=null,hasMedian=vars.median.value!=null,hasUpper=vars.upperQuartil.value!=null,bottom,top;var show=hasLower||hasUpper;if(show){bottom=hasLower?vars.lowerQuartil.position:hasMedian?vars.median.position:vars.upperQuartil.position;top=hasUpper?vars.upperQuartil.position:hasMedian?vars.median.position:vars.lowerQuartil.position;show=(top!==bottom);if(show){catVar.boxBottom=bottom;catVar.boxHeight=top-bottom}}catVar.showBox=show;show=vars.maximum.value!=null;if(show){bottom=hasUpper?vars.upperQuartil.position:hasMedian?vars.median.position:hasLower?vars.lowerQuartil.position:hasMin?vars.minimum.position:null;show=bottom!=null;if(show){catVar.ruleWhiskerUpperBottom=bottom;catVar.ruleWhiskerUpperHeight=vars.maximum.position-bottom}}catVar.showRuleWhiskerUpper=show;show=hasMin;if(show){top=hasLower?vars.lowerQuartil.position:hasMedian?vars.median.position:hasUpper?vars.upperQuartil.position:null;show=top!=null;if(show){bottom=vars.minimum.position;catVar.ruleWhiskerLowerHeight=top-bottom;catVar.ruleWhiskerLowerBottom=bottom}}catVar.showRuleWhiskerBelow=show}}});
def.type('pvc.BoxplotChart',pvc.CategoricalAbstract).add({_processOptionsCore:function(options){this.base.apply(this,arguments);options.stacked=false},_initVisualRoles:function(){this.base();var roleSpecBase={isMeasure:true,requireSingleDimension:true,requireIsDiscrete:false,valueType:Number};[{name:'median',label:'Median',defaultDimension:'median',isRequired:true},{name:'lowerQuartil',label:'Lower Quartil',defaultDimension:'lowerQuartil'},{name:'upperQuartil',label:'Upper Quartil',defaultDimension:'upperQuartil'},{name:'minimum',label:'Minimum',defaultDimension:'minimum'},{name:'maximum',label:'Maximum',defaultDimension:'maximum'}].forEach(function(info){this._addVisualRole(info.name,def.create(roleSpecBase,info))},this)},_getTranslationClass:function(translOptions){return def.type(this.base(translOptions)).add(pvc.data.BoxplotChartTranslationOper)},_initPlotsCore:function(){new pvc.visual.BoxPlot(this);if(this.options.plot2){this._animatable=true;new pvc.visual.PointPlot(this,{name:'plot2',defaults:{LinesVisible:true,DotsVisible:true,OrthoRole:'median',ColorAxis:2},fixed:{OrthoAxis:1}})}},_bindAxes:function(hasMultiRole){this.base(hasMultiRole);var typeAxes=this.axesByType.ortho;if(typeAxes){typeAxes.forEach(function(axis){axis.option.defaults({Offset:0.02})})}},_createPlotPanels:function(parentPanel,baseOptions){var plots=this.plots;var boxPlot=plots.box;var boxPanel=new pvc.BoxplotPanel(this,parentPanel,boxPlot,Object.create(baseOptions));this.bpChartPanel=boxPanel;var plot2Plot=plots.plot2;if(plot2Plot){if(pvc.debug>=3){this._log("Creating Point panel.")}var pointPanel=new pvc.PointPanel(this,parentPanel,plot2Plot,Object.create(baseOptions));pointPanel._v1DimRoleName.value=plot2Plot.option('OrthoRole')}},defaults:{crosstabMode:false}}).addStatic({measureRolesNames:['median','lowerQuartil','upperQuartil','minimum','maximum']});