/*
 Copyright (c) 2010, Nicolas Garcia Belmonte
 All rights reserved
 
 > Redistribution and use in source and binary forms, with or without
 > modification, are permitted provided that the following conditions are met:
 >      * Redistributions of source code must retain the above copyright
 >        notice, this list of conditions and the following disclaimer.
 >      * Redistributions in binary form must reproduce the above copyright
 >        notice, this list of conditions and the following disclaimer in the
 >        documentation and/or other materials provided with the distribution.
 >      * Neither the name of the organization nor the
 >        names of its contributors may be used to endorse or promote products
 >        derived from this software without specific prior written permission.
 >
 >  THIS SOFTWARE IS PROVIDED BY NICOLAS GARCIA BELMONTE ``AS IS'' AND ANY
 >  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 >  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 >  DISCLAIMED. IN NO EVENT SHALL NICOLAS GARCIA BELMONTE BE LIABLE FOR ANY
 >  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 >  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 >  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 >  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 >  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 >  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
(function(){window.$jit=function(w){w=w||window;for(var k in $jit){if($jit[k].$extend){w[k]=$jit[k];}}};$jit.version='2.0.0b';var $=function(d){return document.getElementById(d);};$.empty=function(){};function pad(number,length){var str=''+number;while(str.length<length){str=str+'0';}
return str;};var Url={encode:function(string){return escape(this._utf8_encode(string));},decode:function(string){return this._utf8_decode(unescape(string));},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}};Array.prototype.sum=function(){return(!this.length)?0:this.slice(1).sum()+
((typeof this[0]=='number')?this[0]:0);};function array_match(needle,haystack){var length=haystack.length;var indexValue=new Array();for(var i=0,count=0;i<length;i++){if(haystack[i]==needle){indexValue[count]=i;count++;}}
return new Array(count,indexValue);};$.roundedRect=function(ctx,x,y,width,height,radius,fillType){ctx.beginPath();ctx.moveTo(x,y+radius);ctx.lineTo(x,y+height-radius);ctx.quadraticCurveTo(x,y+height,x+radius,y+height);ctx.lineTo(x+width-radius,y+height);ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);ctx.lineTo(x+width,y+radius);ctx.quadraticCurveTo(x+width,y,x+width-radius,y);ctx.lineTo(x+radius,y);ctx.quadraticCurveTo(x,y,x,y+radius);if(fillType=="fill"){ctx.fill();}else{ctx.stroke();}};$.saveImageFile=function(id,jsonfilename,imageExt){var parts=jsonfilename.split("/");var filename=parts[2].replace(".js","."+imageExt);var oCanvas=document.getElementById(id+"-canvas");if(oCanvas){if(imageExt=="jpg"){var strDataURI=oCanvas.toDataURL("image/jpeg");}else{var strDataURI=oCanvas.toDataURL("image/png");}
var handleFailure=function(o){}
var handleSuccess=function(o){}
var callback={success:handleSuccess,failure:handleFailure,argument:{foo:'foo',bar:''}};var path="index.php?action=DynamicAction&DynamicAction=saveImage&module=Charts&to_pdf=1";var postData="imageStr="+strDataURI+"&filename="+filename;var request=YAHOO.util.Connect.asyncRequest('POST',path,callback,postData);}};$.saveImageTest=function(id,jsonfilename,imageExt){if(typeof FlashCanvas!="undefined"){setTimeout(function(){$.saveImageFile(id,jsonfilename,imageExt)},10000);}else{$.saveImageFile(id,jsonfilename,imageExt);}};$.extend=function(original,extended){for(var key in(extended||{}))
original[key]=extended[key];return original;};$.lambda=function(value){return(typeof value=='function')?value:function(){return value;};};$.time=Date.now||function(){return+new Date;};$.splat=function(obj){var type=$.type(obj);return type?((type!='array')?[obj]:obj):[];};$.type=function(elem){var type=$.type.s.call(elem).match(/^\[object\s(.*)\]$/)[1].toLowerCase();if(type!='object')return type;if(elem&&elem.$$family)return elem.$$family;return(elem&&elem.nodeName&&elem.nodeType==1)?'element':type;};$.type.s=Object.prototype.toString;$.each=function(iterable,fn){var type=$.type(iterable);if(type=='object'){for(var key in iterable)
fn(iterable[key],key);}else{for(var i=0,l=iterable.length;i<l;i++)
fn(iterable[i],i);}};$.indexOf=function(array,item){if(Array.indexOf)return array.indexOf(item);for(var i=0,l=array.length;i<l;i++){if(array[i]===item)return i;}
return-1;};$.map=function(array,f){var ans=[];$.each(array,function(elem,i){ans.push(f(elem,i));});return ans;};$.reduce=function(array,f,opt){var l=array.length;if(l==0)return opt;var acum=arguments.length==3?opt:array[--l];while(l--){acum=f(acum,array[l]);}
return acum;};$.merge=function(){var mix={};for(var i=0,l=arguments.length;i<l;i++){var object=arguments[i];if($.type(object)!='object')
continue;for(var key in object){var op=object[key],mp=mix[key];mix[key]=(mp&&$.type(op)=='object'&&$.type(mp)=='object')?$.merge(mp,op):$.unlink(op);}}
return mix;};$.unlink=function(object){var unlinked;switch($.type(object)){case'object':unlinked={};for(var p in object)
unlinked[p]=$.unlink(object[p]);break;case'array':unlinked=[];for(var i=0,l=object.length;i<l;i++)
unlinked[i]=$.unlink(object[i]);break;default:return object;}
return unlinked;};$.zip=function(){if(arguments.length===0)return[];for(var j=0,ans=[],l=arguments.length,ml=arguments[0].length;j<ml;j++){for(var i=0,row=[];i<l;i++){row.push(arguments[i][j]);}
ans.push(row);}
return ans;};$.rgbToHex=function(srcArray,array){if(srcArray.length<3)
return null;if(srcArray.length==4&&srcArray[3]==0&&!array)
return'transparent';var hex=[];for(var i=0;i<3;i++){var bit=(srcArray[i]-0).toString(16);hex.push(bit.length==1?'0'+bit:bit);}
return array?hex:'#'+hex.join('');};$.hexToRgb=function(hex){if(hex.length!=7){hex=hex.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);hex.shift();if(hex.length!=3)
return null;var rgb=[];for(var i=0;i<3;i++){var value=hex[i];if(value.length==1)
value+=value;rgb.push(parseInt(value,16));}
return rgb;}else{hex=parseInt(hex.slice(1),16);return[hex>>16,hex>>8&0xff,hex&0xff];}};$.destroy=function(elem){$.clean(elem);if(elem.parentNode)
elem.parentNode.removeChild(elem);if(elem.clearAttributes)
elem.clearAttributes();};$.clean=function(elem){for(var ch=elem.childNodes,i=0,l=ch.length;i<l;i++){$.destroy(ch[i]);}};$.addEvent=function(obj,type,fn){if(obj.addEventListener)
obj.addEventListener(type,fn,false);else
obj.attachEvent('on'+type,fn);};$.addEvents=function(obj,typeObj){for(var type in typeObj){$.addEvent(obj,type,typeObj[type]);}};$.hasClass=function(obj,klass){return(' '+obj.className+' ').indexOf(' '+klass+' ')>-1;};$.addClass=function(obj,klass){if(!$.hasClass(obj,klass))
obj.className=(obj.className+" "+klass);};$.removeClass=function(obj,klass){obj.className=obj.className.replace(new RegExp('(^|\\s)'+klass+'(?:\\s|$)'),'$1');};$.getPos=function(elem){var offset=getOffsets(elem);var scroll=getScrolls(elem);return{x:offset.x-scroll.x,y:offset.y-scroll.y};function getOffsets(elem){var position={x:0,y:0};while(elem&&!isBody(elem)){position.x+=elem.offsetLeft;position.y+=elem.offsetTop;try{elem=elem.offsetParent;}catch(e){elem=document.body;}}
return position;}
function getScrolls(elem){var position={x:0,y:0};while(elem&&!isBody(elem)){position.x+=elem.scrollLeft;position.y+=elem.scrollTop;elem=elem.parentNode;}
return position;}
function isBody(element){return(/^(?:body|html)$/i).test(element.tagName);}};$.event={get:function(e,win){win=win||window;return e||win.event;},getWheel:function(e){return e.wheelDelta?e.wheelDelta / 120:-(e.detail||0)/ 3;},isRightClick:function(e){return(e.which==3||e.button==2);},getPos:function(e,win){win=win||window;e=e||win.event;var doc=win.document;doc=doc.documentElement||doc.body;if(e.touches&&e.touches.length){e=e.touches[0];}
var page={x:e.pageX||(e.clientX+doc.scrollLeft),y:e.pageY||(e.clientY+doc.scrollTop)};return page;},stop:function(e){if(e.stopPropagation)e.stopPropagation();e.cancelBubble=true;if(e.preventDefault)e.preventDefault();else e.returnValue=false;}};$jit.util=$jit.id=$;var Class=function(properties){properties=properties||{};var klass=function(){for(var key in this){if(typeof this[key]!='function')
this[key]=$.unlink(this[key]);}
this.constructor=klass;if(Class.prototyping)
return this;var instance=this.initialize?this.initialize.apply(this,arguments):this;this.$$family='class';return instance;};for(var mutator in Class.Mutators){if(!properties[mutator])
continue;properties=Class.Mutators[mutator](properties,properties[mutator]);delete properties[mutator];}
$.extend(klass,this);klass.constructor=Class;klass.prototype=properties;return klass;};Class.Mutators={Implements:function(self,klasses){$.each($.splat(klasses),function(klass){Class.prototyping=klass;var instance=(typeof klass=='function')?new klass:klass;for(var prop in instance){if(!(prop in self)){self[prop]=instance[prop];}}
delete Class.prototyping;});return self;}};$.extend(Class,{inherit:function(object,properties){for(var key in properties){var override=properties[key];var previous=object[key];var type=$.type(override);if(previous&&type=='function'){if(override!=previous){Class.override(object,key,override);}}else if(type=='object'){object[key]=$.merge(previous,override);}else{object[key]=override;}}
return object;},override:function(object,name,method){var parent=Class.prototyping;if(parent&&object[name]!=parent[name])
parent=null;var override=function(){var previous=this.parent;this.parent=parent?parent[name]:object[name];var value=method.apply(this,arguments);this.parent=previous;return value;};object[name]=override;}});Class.prototype.implement=function(){var proto=this.prototype;$.each(Array.prototype.slice.call(arguments||[]),function(properties){Class.inherit(proto,properties);});return this;};$jit.Class=Class;$jit.json={prune:function(tree,maxLevel){this.each(tree,function(elem,i){if(i==maxLevel&&elem.children){delete elem.children;elem.children=[];}});},getParent:function(tree,id){if(tree.id==id)
return false;var ch=tree.children;if(ch&&ch.length>0){for(var i=0;i<ch.length;i++){if(ch[i].id==id)
return tree;else{var ans=this.getParent(ch[i],id);if(ans)
return ans;}}}
return false;},getSubtree:function(tree,id){if(tree.id==id)
return tree;for(var i=0,ch=tree.children;i<ch.length;i++){var t=this.getSubtree(ch[i],id);if(t!=null)
return t;}
return null;},eachLevel:function(tree,initLevel,toLevel,action){if(initLevel<=toLevel){action(tree,initLevel);if(!tree.children)return;for(var i=0,ch=tree.children;i<ch.length;i++){this.eachLevel(ch[i],initLevel+1,toLevel,action);}}},each:function(tree,action){this.eachLevel(tree,0,Number.MAX_VALUE,action);}};$jit.Trans={$extend:true,linear:function(p){return p;}};var Trans=$jit.Trans;(function(){var makeTrans=function(transition,params){params=$.splat(params);return $.extend(transition,{easeIn:function(pos){return transition(pos,params);},easeOut:function(pos){return 1-transition(1-pos,params);},easeInOut:function(pos){return(pos<=0.5)?transition(2*pos,params)/ 2:(2-transition(2*(1-pos),params))/ 2;}});};var transitions={Pow:function(p,x){return Math.pow(p,x[0]||6);},Expo:function(p){return Math.pow(2,8*(p-1));},Circ:function(p){return 1-Math.sin(Math.acos(p));},Sine:function(p){return 1-Math.sin((1-p)*Math.PI / 2);},Back:function(p,x){x=x[0]||1.618;return Math.pow(p,2)*((x+1)*p-x);},Bounce:function(p){var value;for(var a=0,b=1;1;a+=b,b /=2){if(p>=(7-4*a)/ 11){value=b*b-Math.pow((11-6*a-11*p)/ 4,2);break;}}
return value;},Elastic:function(p,x){return Math.pow(2,10*--p)*Math.cos(20*p*Math.PI*(x[0]||1)/ 3);}};$.each(transitions,function(val,key){Trans[key]=makeTrans(val);});$.each(['Quad','Cubic','Quart','Quint'],function(elem,i){Trans[elem]=makeTrans(function(p){return Math.pow(p,[i+2]);});});})();var Animation=new Class({initialize:function(options){this.setOptions(options);},setOptions:function(options){var opt={duration:2500,fps:40,transition:Trans.Quart.easeInOut,compute:$.empty,complete:$.empty,link:'ignore'};this.opt=$.merge(opt,options||{});return this;},step:function(){var time=$.time(),opt=this.opt;if(time<this.time+opt.duration){var delta=opt.transition((time-this.time)/ opt.duration);opt.compute(delta);}else{this.timer=clearInterval(this.timer);opt.compute(1);opt.complete();}},start:function(){if(!this.check())
return this;this.time=0;this.startTimer();return this;},startTimer:function(){var that=this,fps=this.opt.fps;if(this.timer)
return false;this.time=$.time()-this.time;this.timer=setInterval((function(){that.step();}),Math.round(1000 / fps));return true;},pause:function(){this.stopTimer();return this;},resume:function(){this.startTimer();return this;},stopTimer:function(){if(!this.timer)
return false;this.time=$.time()-this.time;this.timer=clearInterval(this.timer);return true;},check:function(){if(!this.timer)
return true;if(this.opt.link=='cancel'){this.stopTimer();return true;}
return false;}});var Options=function(){var args=arguments;for(var i=0,l=args.length,ans={};i<l;i++){var opt=Options[args[i]];if(opt.$extend){$.extend(ans,opt);}else{ans[args[i]]=opt;}}
return ans;};Options.AreaChart={$extend:true,animate:true,labelOffset:3,type:'stacked',Tips:{enable:false,onShow:$.empty,onHide:$.empty},Events:{enable:false,onClick:$.empty},selectOnHover:true,showAggregates:true,showLabels:true,filterOnClick:false,restoreOnRightClick:false};Options.Margin={$extend:false,top:0,left:0,right:0,bottom:0};Options.Canvas={$extend:true,injectInto:'id',width:false,height:false,useCanvas:false,withLabels:true,background:false,colorStop1:'rgba(255,255,255,1)',colorStop2:'rgba(255,255,255,0)'};Options.Tree={$extend:true,orientation:"left",subtreeOffset:8,siblingOffset:5,indent:10,multitree:false,align:"center"};Options.Node={$extend:false,overridable:false,type:'circle',color:'#ccb',alpha:1,dim:3,height:20,width:90,autoHeight:false,autoWidth:false,lineWidth:1,transform:true,align:"center",angularWidth:1,span:1,CanvasStyles:{}};Options.Edge={$extend:false,overridable:false,type:'line',color:'#ccb',lineWidth:1,dim:15,alpha:1,epsilon:7,CanvasStyles:{}};Options.Fx={$extend:true,fps:40,duration:2500,transition:$jit.Trans.Quart.easeInOut,clearCanvas:true};Options.Label={$extend:false,overridable:false,type:'HTML',style:' ',size:10,family:'sans-serif',textAlign:'center',textBaseline:'alphabetic',color:'#fff'};Options.Tips={$extend:false,enable:false,type:'auto',offsetX:20,offsetY:20,force:false,onShow:$.empty,onHide:$.empty};Options.NodeStyles={$extend:false,enable:false,type:'auto',stylesHover:false,stylesClick:false};Options.Events={$extend:false,enable:false,enableForEdges:false,type:'auto',onClick:$.empty,onRightClick:$.empty,onMouseMove:$.empty,onMouseEnter:$.empty,onMouseLeave:$.empty,onDragStart:$.empty,onDragMove:$.empty,onDragCancel:$.empty,onDragEnd:$.empty,onTouchStart:$.empty,onTouchMove:$.empty,onTouchEnd:$.empty,onMouseWheel:$.empty};Options.Navigation={$extend:false,enable:false,type:'auto',panning:false,zooming:false};Options.Controller={$extend:true,onBeforeCompute:$.empty,onAfterCompute:$.empty,onCreateLabel:$.empty,onPlaceLabel:$.empty,onComplete:$.empty,onBeforePlotLine:$.empty,onAfterPlotLine:$.empty,onBeforePlotNode:$.empty,onAfterPlotNode:$.empty,request:false};var ExtrasInitializer={initialize:function(className,viz){this.viz=viz;this.canvas=viz.canvas;this.config=viz.config[className];this.nodeTypes=viz.fx.nodeTypes;var type=this.config.type;this.dom=type=='auto'?(viz.config.Label.type!='Native'):(type!='Native');this.labelContainer=this.dom&&viz.labels.getLabelContainer();this.isEnabled()&&this.initializePost();},initializePost:$.empty,setAsProperty:$.lambda(false),isEnabled:function(){return this.config.enable;},isLabel:function(e,win){e=$.event.get(e,win);var labelContainer=this.labelContainer,target=e.target||e.srcElement;if(target&&target.parentNode==labelContainer)
return target;return false;}};var EventsInterface={onMouseUp:$.empty,onMouseDown:$.empty,onMouseMove:$.empty,onMouseOver:$.empty,onMouseOut:$.empty,onMouseWheel:$.empty,onTouchStart:$.empty,onTouchMove:$.empty,onTouchEnd:$.empty,onTouchCancel:$.empty};var MouseEventsManager=new Class({initialize:function(viz){this.viz=viz;this.canvas=viz.canvas;this.node=false;this.edge=false;this.registeredObjects=[];this.attachEvents();},attachEvents:function(){var htmlCanvas=this.canvas.getElement(),that=this;htmlCanvas.oncontextmenu=$.lambda(false);$.addEvents(htmlCanvas,{'mouseup':function(e,win){var event=$.event.get(e,win);that.handleEvent('MouseUp',e,win,that.makeEventObject(e,win),$.event.isRightClick(event));},'mousedown':function(e,win){var event=$.event.get(e,win);that.handleEvent('MouseDown',e,win,that.makeEventObject(e,win),$.event.isRightClick(event));},'mousemove':function(e,win){that.handleEvent('MouseMove',e,win,that.makeEventObject(e,win));},'mouseover':function(e,win){that.handleEvent('MouseOver',e,win,that.makeEventObject(e,win));},'mouseout':function(e,win){that.handleEvent('MouseOut',e,win,that.makeEventObject(e,win));},'touchstart':function(e,win){that.handleEvent('TouchStart',e,win,that.makeEventObject(e,win));},'touchmove':function(e,win){that.handleEvent('TouchMove',e,win,that.makeEventObject(e,win));},'touchend':function(e,win){that.handleEvent('TouchEnd',e,win,that.makeEventObject(e,win));}});var handleMouseWheel=function(e,win){var event=$.event.get(e,win);var wheel=$.event.getWheel(event);that.handleEvent('MouseWheel',e,win,wheel);};if(!document.getBoxObjectFor&&window.mozInnerScreenX==null){$.addEvent(htmlCanvas,'mousewheel',handleMouseWheel);}else{htmlCanvas.addEventListener('DOMMouseScroll',handleMouseWheel,false);}},register:function(obj){this.registeredObjects.push(obj);},handleEvent:function(){var args=Array.prototype.slice.call(arguments),type=args.shift();for(var i=0,regs=this.registeredObjects,l=regs.length;i<l;i++){regs[i]['on'+type].apply(regs[i],args);}},makeEventObject:function(e,win){var that=this,graph=this.viz.graph,fx=this.viz.fx,ntypes=fx.nodeTypes,etypes=fx.edgeTypes;return{pos:false,node:false,edge:false,contains:false,getNodeCalled:false,getEdgeCalled:false,getPos:function(){var canvas=that.viz.canvas,s=canvas.getSize(),p=canvas.getPos(),ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,pos=$.event.getPos(e,win);this.pos={x:(pos.x-p.x-s.width/2-ox)*1/sx,y:(pos.y-p.y-s.height/2-oy)*1/sy};return this.pos;},getNode:function(){if(this.getNodeCalled)return this.node;this.getNodeCalled=true;for(var id in graph.nodes){var n=graph.nodes[id],geom=n&&ntypes[n.getData('type')],contains=geom&&geom.contains&&geom.contains.call(fx,n,this.getPos());if(contains){this.contains=contains;return that.node=this.node=n;}}
return that.node=this.node=false;},getEdge:function(){if(this.getEdgeCalled)return this.edge;this.getEdgeCalled=true;var hashset={};for(var id in graph.edges){var edgeFrom=graph.edges[id];hashset[id]=true;for(var edgeId in edgeFrom){if(edgeId in hashset)continue;var e=edgeFrom[edgeId],geom=e&&etypes[e.getData('type')],contains=geom&&geom.contains&&geom.contains.call(fx,e,this.getPos());if(contains){this.contains=contains;return that.edge=this.edge=e;}}}
return that.edge=this.edge=false;},getContains:function(){if(this.getNodeCalled)return this.contains;this.getNode();return this.contains;}};}});var Extras={initializeExtras:function(){var mem=new MouseEventsManager(this),that=this;$.each(['NodeStyles','Tips','Navigation','Events'],function(k){var obj=new Extras.Classes[k](k,that);if(obj.isEnabled()){mem.register(obj);}
if(obj.setAsProperty()){that[k.toLowerCase()]=obj;}});}};Extras.Classes={};Extras.Classes.Events=new Class({Implements:[ExtrasInitializer,EventsInterface],initializePost:function(){this.fx=this.viz.fx;this.ntypes=this.viz.fx.nodeTypes;this.etypes=this.viz.fx.edgeTypes;this.hovered=false;this.pressed=false;this.touched=false;this.touchMoved=false;this.moved=false;},setAsProperty:$.lambda(true),onMouseUp:function(e,win,event,isRightClick){var evt=$.event.get(e,win);if(!this.moved){if(isRightClick){this.config.onRightClick(this.hovered,event,evt);}else{this.config.onClick(this.pressed,event,evt);}}
if(this.pressed){if(this.moved){this.config.onDragEnd(this.pressed,event,evt);}else{this.config.onDragCancel(this.pressed,event,evt);}
this.pressed=this.moved=false;}},onMouseOut:function(e,win,event){var evt=$.event.get(e,win),label;if(this.dom&&(label=this.isLabel(e,win))){this.config.onMouseLeave(this.viz.graph.getNode(label.id),event,evt);this.hovered=false;return;}
var rt=evt.relatedTarget,canvasWidget=this.canvas.getElement();while(rt&&rt.parentNode){if(canvasWidget==rt.parentNode)return;rt=rt.parentNode;}
if(this.hovered){this.config.onMouseLeave(this.hovered,event,evt);this.hovered=false;}},onMouseOver:function(e,win,event){var evt=$.event.get(e,win),label;if(this.dom&&(label=this.isLabel(e,win))){this.hovered=this.viz.graph.getNode(label.id);this.config.onMouseEnter(this.hovered,event,evt);}},onMouseMove:function(e,win,event){var label,evt=$.event.get(e,win);if(this.pressed){this.moved=true;this.config.onDragMove(this.pressed,event,evt);return;}
if(this.dom){this.config.onMouseMove(this.hovered,event,evt);}else{if(this.hovered){var hn=this.hovered;var geom=hn.nodeFrom?this.etypes[hn.getData('type')]:this.ntypes[hn.getData('type')];var contains=geom&&geom.contains&&geom.contains.call(this.fx,hn,event.getPos());if(contains){this.config.onMouseMove(hn,event,evt);return;}else{this.config.onMouseLeave(hn,event,evt);this.hovered=false;}}
if(this.hovered=(event.getNode()||(this.config.enableForEdges&&event.getEdge()))){this.config.onMouseEnter(this.hovered,event,evt);}else{this.config.onMouseMove(false,event,evt);}}},onMouseWheel:function(e,win,delta){this.config.onMouseWheel(delta,$.event.get(e,win));},onMouseDown:function(e,win,event){var evt=$.event.get(e,win);this.pressed=event.getNode()||(this.config.enableForEdges&&event.getEdge());this.config.onDragStart(this.pressed,event,evt);},onTouchStart:function(e,win,event){var evt=$.event.get(e,win);this.touched=event.getNode()||(this.config.enableForEdges&&event.getEdge());this.config.onTouchStart(this.touched,event,evt);},onTouchMove:function(e,win,event){var evt=$.event.get(e,win);if(this.touched){this.touchMoved=true;this.config.onTouchMove(this.touched,event,evt);}},onTouchEnd:function(e,win,event){var evt=$.event.get(e,win);if(this.touched){if(this.touchMoved){this.config.onTouchEnd(this.touched,event,evt);}else{this.config.onTouchCancel(this.touched,event,evt);}
this.touched=this.touchMoved=false;}}});Extras.Classes.Tips=new Class({Implements:[ExtrasInitializer,EventsInterface],initializePost:function(){if(document.body){var tip=$('_tooltip')||document.createElement('div');tip.id='_tooltip';tip.className='tip';$.extend(tip.style,{position:'absolute',display:'none',zIndex:13000});document.body.appendChild(tip);this.tip=tip;this.node=false;}},setAsProperty:$.lambda(true),onMouseOut:function(e,win){if(this.dom&&this.isLabel(e,win)){this.hide(true);return;}
var rt=e.relatedTarget,canvasWidget=this.canvas.getElement();while(rt&&rt.parentNode){if(canvasWidget==rt.parentNode)return;rt=rt.parentNode;}
this.hide(false);},onMouseOver:function(e,win){var label;if(this.dom&&(label=this.isLabel(e,win))){this.node=this.viz.graph.getNode(label.id);this.config.onShow(this.tip,this.node,label);}},onMouseMove:function(e,win,opt){if(this.dom&&this.isLabel(e,win)){this.setTooltipPosition($.event.getPos(e,win));}
if(!this.dom){var node=opt.getNode();if(!node){this.hide(true);return;}
if(this.config.force||!this.node||this.node.id!=node.id){this.node=node;this.config.onShow(this.tip,node,opt.getContains());}
this.setTooltipPosition($.event.getPos(e,win));}},setTooltipPosition:function(pos){var tip=this.tip,style=tip.style,cont=this.config;style.display='';var win={'height':document.body.clientHeight,'width':document.body.clientWidth};var obj={'width':tip.offsetWidth,'height':tip.offsetHeight};var x=cont.offsetX,y=cont.offsetY;style.top=((pos.y+y+obj.height>win.height)?(pos.y-obj.height-y):pos.y+y)+'px';style.left=((pos.x+obj.width+x>win.width)?(pos.x-obj.width-x):pos.x+x)+'px';},hide:function(triggerCallback){if(!SUGAR.util.isTouchScreen()){this.tip.style.display='none';}
triggerCallback&&this.config.onHide();}});Extras.Classes.NodeStyles=new Class({Implements:[ExtrasInitializer,EventsInterface],initializePost:function(){this.fx=this.viz.fx;this.types=this.viz.fx.nodeTypes;this.nStyles=this.config;this.nodeStylesOnHover=this.nStyles.stylesHover;this.nodeStylesOnClick=this.nStyles.stylesClick;this.hoveredNode=false;this.fx.nodeFxAnimation=new Animation();this.down=false;this.move=false;},onMouseOut:function(e,win){this.down=this.move=false;if(!this.hoveredNode)return;if(this.dom&&this.isLabel(e,win)){this.toggleStylesOnHover(this.hoveredNode,false);}
var rt=e.relatedTarget,canvasWidget=this.canvas.getElement();while(rt&&rt.parentNode){if(canvasWidget==rt.parentNode)return;rt=rt.parentNode;}
this.toggleStylesOnHover(this.hoveredNode,false);this.hoveredNode=false;},onMouseOver:function(e,win){var label;if(this.dom&&(label=this.isLabel(e,win))){var node=this.viz.graph.getNode(label.id);if(node.selected)return;this.hoveredNode=node;this.toggleStylesOnHover(this.hoveredNode,true);}},onMouseDown:function(e,win,event,isRightClick){if(isRightClick)return;var label;if(this.dom&&(label=this.isLabel(e,win))){this.down=this.viz.graph.getNode(label.id);}else if(!this.dom){this.down=event.getNode();}
this.move=false;},onMouseUp:function(e,win,event,isRightClick){if(isRightClick)return;if(!this.move){this.onClick(event.getNode());}
this.down=this.move=false;},getRestoredStyles:function(node,type){var restoredStyles={},nStyles=this['nodeStylesOn'+type];for(var prop in nStyles){restoredStyles[prop]=node.styles['$'+prop];}
return restoredStyles;},toggleStylesOnHover:function(node,set){if(this.nodeStylesOnHover){this.toggleStylesOn('Hover',node,set);}},toggleStylesOnClick:function(node,set){if(this.nodeStylesOnClick){this.toggleStylesOn('Click',node,set);}},toggleStylesOn:function(type,node,set){var viz=this.viz;var nStyles=this.nStyles;if(set){var that=this;if(!node.styles){node.styles=$.merge(node.data,{});}
for(var s in this['nodeStylesOn'+type]){var $s='$'+s;if(!($s in node.styles)){node.styles[$s]=node.getData(s);}}
viz.fx.nodeFx($.extend({'elements':{'id':node.id,'properties':that['nodeStylesOn'+type]},transition:Trans.Quart.easeOut,duration:300,fps:40},this.config));}else{var restoredStyles=this.getRestoredStyles(node,type);viz.fx.nodeFx($.extend({'elements':{'id':node.id,'properties':restoredStyles},transition:Trans.Quart.easeOut,duration:300,fps:40},this.config));}},onClick:function(node){if(!node)return;var nStyles=this.nodeStylesOnClick;if(!nStyles)return;if(node.selected){this.toggleStylesOnClick(node,false);delete node.selected;}else{this.viz.graph.eachNode(function(n){if(n.selected){for(var s in nStyles){n.setData(s,n.styles['$'+s],'end');}
delete n.selected;}});this.toggleStylesOnClick(node,true);node.selected=true;delete node.hovered;this.hoveredNode=false;}},onMouseMove:function(e,win,event){if(this.down)this.move=true;if(this.dom&&this.isLabel(e,win))return;var nStyles=this.nodeStylesOnHover;if(!nStyles)return;if(!this.dom){if(this.hoveredNode){var geom=this.types[this.hoveredNode.getData('type')];var contains=geom&&geom.contains&&geom.contains.call(this.fx,this.hoveredNode,event.getPos());if(contains)return;}
var node=event.getNode();if(!this.hoveredNode&&!node)return;if(node.hovered)return;if(node&&!node.selected){this.fx.nodeFxAnimation.stopTimer();this.viz.graph.eachNode(function(n){if(n.hovered&&!n.selected){for(var s in nStyles){n.setData(s,n.styles['$'+s],'end');}
delete n.hovered;}});node.hovered=true;this.hoveredNode=node;this.toggleStylesOnHover(node,true);}else if(this.hoveredNode&&!this.hoveredNode.selected){this.fx.nodeFxAnimation.stopTimer();this.toggleStylesOnHover(this.hoveredNode,false);delete this.hoveredNode.hovered;this.hoveredNode=false;}}}});Extras.Classes.Navigation=new Class({Implements:[ExtrasInitializer,EventsInterface],initializePost:function(){this.pos=false;this.pressed=false;},onMouseWheel:function(e,win,scroll){if(!this.config.zooming)return;$.event.stop($.event.get(e,win));var val=this.config.zooming / 1000,ans=1+scroll*val;this.canvas.scale(ans,ans);},onMouseDown:function(e,win,eventInfo){if(!this.config.panning)return;if(this.config.panning=='avoid nodes'&&eventInfo.getNode())return;this.pressed=true;this.pos=eventInfo.getPos();var canvas=this.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY;this.pos.x*=sx;this.pos.x+=ox;this.pos.y*=sy;this.pos.y+=oy;},onMouseMove:function(e,win,eventInfo){if(!this.config.panning)return;if(!this.pressed)return;if(this.config.panning=='avoid nodes'&&eventInfo.getNode())return;var thispos=this.pos,currentPos=eventInfo.getPos(),canvas=this.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY;currentPos.x*=sx;currentPos.y*=sy;currentPos.x+=ox;currentPos.y+=oy;var x=currentPos.x-thispos.x,y=currentPos.y-thispos.y;this.pos=currentPos;this.canvas.translate(x*1/sx,y*1/sy);},onMouseUp:function(e,win,eventInfo,isRightClick){if(!this.config.panning)return;this.pressed=false;}});var Canvas;(function(){var canvasType=typeof HTMLCanvasElement,supportsCanvas=(canvasType=='object'||canvasType=='function');function $E(tag,props){var elem=document.createElement(tag);for(var p in props){if(typeof props[p]=="object"){$.extend(elem[p],props[p]);}else{elem[p]=props[p];}}
if(tag=="canvas"&&!supportsCanvas&&G_vmlCanvasManager){elem=G_vmlCanvasManager.initElement(elem);}
return elem;}
$jit.Canvas=Canvas=new Class({canvases:[],pos:false,element:false,labelContainer:false,translateOffsetX:0,translateOffsetY:0,scaleOffsetX:1,scaleOffsetY:1,initialize:function(viz,opt){this.viz=viz;this.opt=opt;var id=$.type(opt.injectInto)=='string'?opt.injectInto:opt.injectInto.id,idLabel=id+"-label",wrapper=$(id),width=opt.width||wrapper.offsetWidth,height=opt.height||wrapper.offsetHeight;this.id=id;var canvasOptions={injectInto:id,width:width,height:height};this.element=$E('div',{'id':id+'-canvaswidget','style':{'position':'relative','width':width+'px','height':height+'px'}});this.labelContainer=this.createLabelContainer(opt.Label.type,idLabel,canvasOptions);this.canvases.push(new Canvas.Base({config:$.extend({idSuffix:'-canvas'},canvasOptions),plot:function(base){viz.fx.plot();},resize:function(){viz.refresh();}}));var back=opt.background;if(back){var backCanvas=new Canvas.Background[back.type](viz,$.extend(back,canvasOptions));this.canvases.push(new Canvas.Base(backCanvas));}
var len=this.canvases.length;while(len--){this.element.appendChild(this.canvases[len].canvas);if(len>0){this.canvases[len].plot();}}
this.element.appendChild(this.labelContainer);wrapper.appendChild(this.element);var timer=null,that=this;$.addEvent(window,'scroll',function(){clearTimeout(timer);timer=setTimeout(function(){that.getPos(true);},500);});$.addEvent(window,'click',function(){clearTimeout(timer);timer=setTimeout(function(){that.getPos(true);},500);});sb=document.getElementById('sb'+id);$.addEvent(sb,'scroll',function(){clearTimeout(timer);timer=setTimeout(function(){that.getPos(true);},500);});},getCtx:function(i){return this.canvases[i||0].getCtx();},getConfig:function(){return this.opt;},getElement:function(){return this.element;},getSize:function(i){return this.canvases[i||0].getSize();},resize:function(width,height){this.getPos(true);this.translateOffsetX=this.translateOffsetY=0;this.scaleOffsetX=this.scaleOffsetY=1;for(var i=0,l=this.canvases.length;i<l;i++){this.canvases[i].resize(width,height);}
var style=this.element.style;style.width=width+'px';style.height=height+'px';if(this.labelContainer)
this.labelContainer.style.width=width+'px';},translate:function(x,y,disablePlot){this.translateOffsetX+=x*this.scaleOffsetX;this.translateOffsetY+=y*this.scaleOffsetY;for(var i=0,l=this.canvases.length;i<l;i++){this.canvases[i].translate(x,y,disablePlot);}},scale:function(x,y,disablePlot){if(!disablePlot){disablePlot=false;}
var px=this.scaleOffsetX*x,py=this.scaleOffsetY*y;var dx=this.translateOffsetX*(x-1)/ px,dy=this.translateOffsetY*(y-1)/ py;this.scaleOffsetX=px;this.scaleOffsetY=py;for(var i=0,l=this.canvases.length;i<l;i++){this.canvases[i].scale(x,y,true);}
this.translate(dx,dy,disablePlot);},getPos:function(force){if(force||!this.pos){return this.pos=$.getPos(this.getElement());}
return this.pos;},clear:function(i){this.canvases[i||0].clear();},path:function(type,action){var ctx=this.canvases[0].getCtx();ctx.beginPath();action(ctx);ctx[type]();ctx.closePath();},createLabelContainer:function(type,idLabel,dim){var NS='http://www.w3.org/2000/svg';if(type=='HTML'||type=='Native'){return $E('div',{'id':idLabel,'style':{'overflow':'visible','position':'absolute','top':0,'left':0,'width':dim.width+'px','height':0}});}else if(type=='SVG'){var svgContainer=document.createElementNS(NS,'svg:svg');svgContainer.setAttribute("width",dim.width);svgContainer.setAttribute('height',dim.height);var style=svgContainer.style;style.position='absolute';style.left=style.top='0px';var labelContainer=document.createElementNS(NS,'svg:g');labelContainer.setAttribute('width',dim.width);labelContainer.setAttribute('height',dim.height);labelContainer.setAttribute('x',0);labelContainer.setAttribute('y',0);labelContainer.setAttribute('id',idLabel);svgContainer.appendChild(labelContainer);return svgContainer;}}});Canvas.Base=new Class({translateOffsetX:0,translateOffsetY:0,scaleOffsetX:1,scaleOffsetY:1,initialize:function(viz){this.viz=viz;this.opt=viz.config;this.size=false;this.createCanvas();this.translateToCenter();},createCanvas:function(){var opt=this.opt,width=opt.width,height=opt.height;this.canvas=$E('canvas',{'id':opt.injectInto+opt.idSuffix,'width':width,'height':height,'style':{'position':'absolute','top':0,'left':0,'width':width+'px','height':height+'px'}});},getCtx:function(){if(!this.ctx)
return this.ctx=this.canvas.getContext('2d');return this.ctx;},getSize:function(){if(this.size)return this.size;var canvas=this.canvas;return this.size={width:canvas.width,height:canvas.height};},translateToCenter:function(ps){var size=this.getSize(),width=ps?(size.width-ps.width-this.translateOffsetX*2):size.width;height=ps?(size.height-ps.height-this.translateOffsetY*2):size.height;var ctx=this.getCtx();ps&&ctx.scale(1/this.scaleOffsetX,1/this.scaleOffsetY);ctx.translate(width/2,height/2);},resize:function(width,height){var size=this.getSize(),canvas=this.canvas,styles=canvas.style;this.size=false;canvas.width=width;canvas.height=height;styles.width=width+"px";styles.height=height+"px";if(!supportsCanvas){this.getCtx().I(width,height);}
this.translateToCenter();this.translateOffsetX=this.translateOffsetY=0;this.scaleOffsetX=this.scaleOffsetY=1;this.clear();this.viz.resize(width,height,this);},translate:function(x,y,disablePlot){var sx=this.scaleOffsetX,sy=this.scaleOffsetY;this.translateOffsetX+=x*sx;this.translateOffsetY+=y*sy;this.getCtx().translate(x,y);!disablePlot&&this.plot();},scale:function(x,y,disablePlot){this.scaleOffsetX*=x;this.scaleOffsetY*=y;this.getCtx().scale(x,y);!disablePlot&&this.plot();},clear:function(){var size=this.getSize(),ox=this.translateOffsetX,oy=this.translateOffsetY,sx=this.scaleOffsetX,sy=this.scaleOffsetY;this.getCtx().clearRect((-size.width / 2-ox)*1/sx,(-size.height / 2-oy)*1/sy,size.width*1/sx,size.height*1/sy);},plot:function(){this.clear();this.viz.plot(this);}});Canvas.Background={};Canvas.Background.Circles=new Class({initialize:function(viz,options){this.viz=viz;this.config=$.merge({idSuffix:'-bkcanvas',levelDistance:100,numberOfCircles:6,CanvasStyles:{},offset:0},options);},resize:function(width,height,base){this.plot(base);},plot:function(base){var canvas=base.canvas,ctx=base.getCtx(),conf=this.config,styles=conf.CanvasStyles;for(var s in styles)ctx[s]=styles[s];var n=conf.numberOfCircles,rho=conf.levelDistance;for(var i=1;i<=n;i++){ctx.beginPath();ctx.arc(0,0,rho*i,0,2*Math.PI,false);ctx.stroke();ctx.closePath();}}});Canvas.Background.Fade=new Class({initialize:function(viz,options){this.viz=viz;this.config=$.merge({idSuffix:'-bkcanvas',CanvasStyles:{},offset:0},options);},resize:function(width,height,base){this.plot(base);},plot:function(base){var canvas=base.canvas,ctx=base.getCtx(),conf=this.config,styles=conf.CanvasStyles,size=base.getSize();ctx.fillStyle='rgb(255,255,255)';ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);}});})();var Polar=function(theta,rho){this.theta=theta;this.rho=rho;};$jit.Polar=Polar;Polar.prototype={getc:function(simple){return this.toComplex(simple);},getp:function(){return this;},set:function(v){v=v.getp();this.theta=v.theta;this.rho=v.rho;},setc:function(x,y){this.rho=Math.sqrt(x*x+y*y);this.theta=Math.atan2(y,x);if(this.theta<0)this.theta+=Math.PI*2;},setp:function(theta,rho){this.theta=theta;this.rho=rho;},clone:function(){return new Polar(this.theta,this.rho);},toComplex:function(simple){var x=Math.cos(this.theta)*this.rho;var y=Math.sin(this.theta)*this.rho;if(simple)return{'x':x,'y':y};return new Complex(x,y);},add:function(polar){return new Polar(this.theta+polar.theta,this.rho+polar.rho);},scale:function(number){return new Polar(this.theta,this.rho*number);},equals:function(c){return this.theta==c.theta&&this.rho==c.rho;},$add:function(polar){this.theta=this.theta+polar.theta;this.rho+=polar.rho;return this;},$madd:function(polar){this.theta=(this.theta+polar.theta)%(Math.PI*2);this.rho+=polar.rho;return this;},$scale:function(number){this.rho*=number;return this;},interpolate:function(elem,delta){var pi=Math.PI,pi2=pi*2;var ch=function(t){var a=(t<0)?(t%pi2)+pi2:t%pi2;return a;};var tt=this.theta,et=elem.theta;var sum,diff=Math.abs(tt-et);if(diff==pi){if(tt>et){sum=ch((et+((tt-pi2)-et)*delta));}else{sum=ch((et-pi2+(tt-(et))*delta));}}else if(diff>=pi){if(tt>et){sum=ch((et+((tt-pi2)-et)*delta));}else{sum=ch((et-pi2+(tt-(et-pi2))*delta));}}else{sum=ch((et+(tt-et)*delta));}
var r=(this.rho-elem.rho)*delta+elem.rho;return{'theta':sum,'rho':r};}};var $P=function(a,b){return new Polar(a,b);};Polar.KER=$P(0,0);var Complex=function(x,y){this.x=x;this.y=y;};$jit.Complex=Complex;Complex.prototype={getc:function(){return this;},getp:function(simple){return this.toPolar(simple);},set:function(c){c=c.getc(true);this.x=c.x;this.y=c.y;},setc:function(x,y){this.x=x;this.y=y;},setp:function(theta,rho){this.x=Math.cos(theta)*rho;this.y=Math.sin(theta)*rho;},clone:function(){return new Complex(this.x,this.y);},toPolar:function(simple){var rho=this.norm();var atan=Math.atan2(this.y,this.x);if(atan<0)atan+=Math.PI*2;if(simple)return{'theta':atan,'rho':rho};return new Polar(atan,rho);},norm:function(){return Math.sqrt(this.squaredNorm());},squaredNorm:function(){return this.x*this.x+this.y*this.y;},add:function(pos){return new Complex(this.x+pos.x,this.y+pos.y);},prod:function(pos){return new Complex(this.x*pos.x-this.y*pos.y,this.y*pos.x+this.x*pos.y);},conjugate:function(){return new Complex(this.x,-this.y);},scale:function(factor){return new Complex(this.x*factor,this.y*factor);},equals:function(c){return this.x==c.x&&this.y==c.y;},$add:function(pos){this.x+=pos.x;this.y+=pos.y;return this;},$prod:function(pos){var x=this.x,y=this.y;this.x=x*pos.x-y*pos.y;this.y=y*pos.x+x*pos.y;return this;},$conjugate:function(){this.y=-this.y;return this;},$scale:function(factor){this.x*=factor;this.y*=factor;return this;},$div:function(pos){var x=this.x,y=this.y;var sq=pos.squaredNorm();this.x=x*pos.x+y*pos.y;this.y=y*pos.x-x*pos.y;return this.$scale(1 / sq);}};var $C=function(a,b){return new Complex(a,b);};Complex.KER=$C(0,0);$jit.Graph=new Class({initialize:function(opt,Node,Edge,Label){var innerOptions={'complex':false,'Node':{}};this.Node=Node;this.Edge=Edge;this.Label=Label;this.opt=$.merge(innerOptions,opt||{});this.nodes={};this.edges={};var that=this;this.nodeList={};for(var p in Accessors){that.nodeList[p]=(function(p){return function(){var args=Array.prototype.slice.call(arguments);that.eachNode(function(n){n[p].apply(n,args);});};})(p);}},getNode:function(id){if(this.hasNode(id))return this.nodes[id];return false;},getByName:function(name){for(var id in this.nodes){var n=this.nodes[id];if(n.name==name)return n;}
return false;},getAdjacence:function(id,id2){if(id in this.edges){return this.edges[id][id2];}
return false;},addNode:function(obj){if(!this.nodes[obj.id]){var edges=this.edges[obj.id]={};this.nodes[obj.id]=new Graph.Node($.extend({'id':obj.id,'name':obj.name,'data':$.merge(obj.data||{},{}),'adjacencies':edges},this.opt.Node),this.opt.complex,this.Node,this.Edge,this.Label);}
return this.nodes[obj.id];},addAdjacence:function(obj,obj2,data){if(!this.hasNode(obj.id)){this.addNode(obj);}
if(!this.hasNode(obj2.id)){this.addNode(obj2);}
obj=this.nodes[obj.id];obj2=this.nodes[obj2.id];if(!obj.adjacentTo(obj2)){var adjsObj=this.edges[obj.id]=this.edges[obj.id]||{};var adjsObj2=this.edges[obj2.id]=this.edges[obj2.id]||{};adjsObj[obj2.id]=adjsObj2[obj.id]=new Graph.Adjacence(obj,obj2,data,this.Edge,this.Label);return adjsObj[obj2.id];}
return this.edges[obj.id][obj2.id];},removeNode:function(id){if(this.hasNode(id)){delete this.nodes[id];var adjs=this.edges[id];for(var to in adjs){delete this.edges[to][id];}
delete this.edges[id];}},removeAdjacence:function(id1,id2){delete this.edges[id1][id2];delete this.edges[id2][id1];},hasNode:function(id){return id in this.nodes;},empty:function(){this.nodes={};this.edges={};}});var Graph=$jit.Graph;var Accessors;(function(){var getDataInternal=function(prefix,prop,type,force,prefixConfig){var data;type=type||'current';prefix="$"+(prefix?prefix+"-":"");if(type=='current'){data=this.data;}else if(type=='start'){data=this.startData;}else if(type=='end'){data=this.endData;}
var dollar=prefix+prop;if(force){return data[dollar];}
if(!this.Config.overridable)
return prefixConfig[prop]||0;return(dollar in data)?data[dollar]:((dollar in this.data)?this.data[dollar]:(prefixConfig[prop]||0));}
var setDataInternal=function(prefix,prop,value,type){type=type||'current';prefix='$'+(prefix?prefix+'-':'');var data;if(type=='current'){data=this.data;}else if(type=='start'){data=this.startData;}else if(type=='end'){data=this.endData;}
data[prefix+prop]=value;}
var removeDataInternal=function(prefix,properties){prefix='$'+(prefix?prefix+'-':'');var that=this;$.each(properties,function(prop){var pref=prefix+prop;delete that.data[pref];delete that.endData[pref];delete that.startData[pref];});}
Accessors={getData:function(prop,type,force){return getDataInternal.call(this,"",prop,type,force,this.Config);},setData:function(prop,value,type){setDataInternal.call(this,"",prop,value,type);},setDataset:function(types,obj){types=$.splat(types);for(var attr in obj){for(var i=0,val=$.splat(obj[attr]),l=types.length;i<l;i++){this.setData(attr,val[i],types[i]);}}},removeData:function(){removeDataInternal.call(this,"",Array.prototype.slice.call(arguments));},getCanvasStyle:function(prop,type,force){return getDataInternal.call(this,'canvas',prop,type,force,this.Config.CanvasStyles);},setCanvasStyle:function(prop,value,type){setDataInternal.call(this,'canvas',prop,value,type);},setCanvasStyles:function(types,obj){types=$.splat(types);for(var attr in obj){for(var i=0,val=$.splat(obj[attr]),l=types.length;i<l;i++){this.setCanvasStyle(attr,val[i],types[i]);}}},removeCanvasStyle:function(){removeDataInternal.call(this,'canvas',Array.prototype.slice.call(arguments));},getLabelData:function(prop,type,force){return getDataInternal.call(this,'label',prop,type,force,this.Label);},setLabelData:function(prop,value,type){setDataInternal.call(this,'label',prop,value,type);},setLabelDataset:function(types,obj){types=$.splat(types);for(var attr in obj){for(var i=0,val=$.splat(obj[attr]),l=types.length;i<l;i++){this.setLabelData(attr,val[i],types[i]);}}},removeLabelData:function(){removeDataInternal.call(this,'label',Array.prototype.slice.call(arguments));}};})();Graph.Node=new Class({initialize:function(opt,complex,Node,Edge,Label){var innerOptions={'id':'','name':'','data':{},'startData':{},'endData':{},'adjacencies':{},'selected':false,'drawn':false,'exist':false,'angleSpan':{'begin':0,'end':0},'pos':(complex&&$C(0,0))||$P(0,0),'startPos':(complex&&$C(0,0))||$P(0,0),'endPos':(complex&&$C(0,0))||$P(0,0)};$.extend(this,$.extend(innerOptions,opt));this.Config=this.Node=Node;this.Edge=Edge;this.Label=Label;},adjacentTo:function(node){return node.id in this.adjacencies;},getAdjacency:function(id){return this.adjacencies[id];},getPos:function(type){type=type||"current";if(type=="current"){return this.pos;}else if(type=="end"){return this.endPos;}else if(type=="start"){return this.startPos;}},setPos:function(value,type){type=type||"current";var pos;if(type=="current"){pos=this.pos;}else if(type=="end"){pos=this.endPos;}else if(type=="start"){pos=this.startPos;}
pos.set(value);}});Graph.Node.implement(Accessors);Graph.Adjacence=new Class({initialize:function(nodeFrom,nodeTo,data,Edge,Label){this.nodeFrom=nodeFrom;this.nodeTo=nodeTo;this.data=data||{};this.startData={};this.endData={};this.Config=this.Edge=Edge;this.Label=Label;}});Graph.Adjacence.implement(Accessors);Graph.Util={filter:function(param){if(!param||!($.type(param)=='string'))return function(){return true;};var props=param.split(" ");return function(elem){for(var i=0;i<props.length;i++){if(elem[props[i]]){return false;}}
return true;};},getNode:function(graph,id){return graph.nodes[id];},eachNode:function(graph,action,flags){var filter=this.filter(flags);for(var i in graph.nodes){if(filter(graph.nodes[i]))action(graph.nodes[i]);}},eachAdjacency:function(node,action,flags){var adj=node.adjacencies,filter=this.filter(flags);for(var id in adj){var a=adj[id];if(filter(a)){if(a.nodeFrom!=node){var tmp=a.nodeFrom;a.nodeFrom=a.nodeTo;a.nodeTo=tmp;}
action(a,id);}}},computeLevels:function(graph,id,startDepth,flags){startDepth=startDepth||0;var filter=this.filter(flags);this.eachNode(graph,function(elem){elem._flag=false;elem._depth=-1;},flags);var root=graph.getNode(id);root._depth=startDepth;var queue=[root];while(queue.length!=0){var node=queue.pop();node._flag=true;this.eachAdjacency(node,function(adj){var n=adj.nodeTo;if(n._flag==false&&filter(n)){if(n._depth<0)n._depth=node._depth+1+startDepth;queue.unshift(n);}},flags);}},eachBFS:function(graph,id,action,flags){var filter=this.filter(flags);this.clean(graph);var queue=[graph.getNode(id)];while(queue.length!=0){var node=queue.pop();node._flag=true;action(node,node._depth);this.eachAdjacency(node,function(adj){var n=adj.nodeTo;if(n._flag==false&&filter(n)){n._flag=true;queue.unshift(n);}},flags);}},eachLevel:function(node,levelBegin,levelEnd,action,flags){var d=node._depth,filter=this.filter(flags),that=this;levelEnd=levelEnd===false?Number.MAX_VALUE-d:levelEnd;(function loopLevel(node,levelBegin,levelEnd){var d=node._depth;if(d>=levelBegin&&d<=levelEnd&&filter(node))action(node,d);if(d<levelEnd){that.eachAdjacency(node,function(adj){var n=adj.nodeTo;if(n._depth>d)loopLevel(n,levelBegin,levelEnd);});}})(node,levelBegin+d,levelEnd+d);},eachSubgraph:function(node,action,flags){this.eachLevel(node,0,false,action,flags);},eachSubnode:function(node,action,flags){this.eachLevel(node,1,1,action,flags);},anySubnode:function(node,cond,flags){var flag=false;cond=cond||$.lambda(true);var c=$.type(cond)=='string'?function(n){return n[cond];}:cond;this.eachSubnode(node,function(elem){if(c(elem))flag=true;},flags);return flag;},getSubnodes:function(node,level,flags){var ans=[],that=this;level=level||0;var levelStart,levelEnd;if($.type(level)=='array'){levelStart=level[0];levelEnd=level[1];}else{levelStart=level;levelEnd=Number.MAX_VALUE-node._depth;}
this.eachLevel(node,levelStart,levelEnd,function(n){ans.push(n);},flags);return ans;},getParents:function(node){var ans=[];this.eachAdjacency(node,function(adj){var n=adj.nodeTo;if(n._depth<node._depth)ans.push(n);});return ans;},isDescendantOf:function(node,id){if(node.id==id)return true;var pars=this.getParents(node),ans=false;for(var i=0;!ans&&i<pars.length;i++){ans=ans||this.isDescendantOf(pars[i],id);}
return ans;},clean:function(graph){this.eachNode(graph,function(elem){elem._flag=false;});},getClosestNodeToOrigin:function(graph,prop,flags){return this.getClosestNodeToPos(graph,Polar.KER,prop,flags);},getClosestNodeToPos:function(graph,pos,prop,flags){var node=null;prop=prop||'current';pos=pos&&pos.getc(true)||Complex.KER;var distance=function(a,b){var d1=a.x-b.x,d2=a.y-b.y;return d1*d1+d2*d2;};this.eachNode(graph,function(elem){node=(node==null||distance(elem.getPos(prop).getc(true),pos)<distance(node.getPos(prop).getc(true),pos))?elem:node;},flags);return node;}};$.each(['getNode','eachNode','computeLevels','eachBFS','clean','getClosestNodeToPos','getClosestNodeToOrigin'],function(m){Graph.prototype[m]=function(){return Graph.Util[m].apply(Graph.Util,[this].concat(Array.prototype.slice.call(arguments)));};});$.each(['eachAdjacency','eachLevel','eachSubgraph','eachSubnode','anySubnode','getSubnodes','getParents','isDescendantOf'],function(m){Graph.Node.prototype[m]=function(){return Graph.Util[m].apply(Graph.Util,[this].concat(Array.prototype.slice.call(arguments)));};});Graph.Op={options:{type:'nothing',duration:2000,hideLabels:true,fps:30},initialize:function(viz){this.viz=viz;},removeNode:function(node,opt){var viz=this.viz;var options=$.merge(this.options,viz.controller,opt);var n=$.splat(node);var i,that,nodeObj;switch(options.type){case'nothing':for(i=0;i<n.length;i++)viz.graph.removeNode(n[i]);break;case'replot':this.removeNode(n,{type:'nothing'});viz.labels.clearLabels();viz.refresh(true);break;case'fade:seq':case'fade':that=this;for(i=0;i<n.length;i++){nodeObj=viz.graph.getNode(n[i]);nodeObj.setData('alpha',0,'end');}
viz.fx.animate($.merge(options,{modes:['node-property:alpha'],onComplete:function(){that.removeNode(n,{type:'nothing'});viz.labels.clearLabels();viz.reposition();viz.fx.animate($.merge(options,{modes:['linear']}));}}));break;case'fade:con':that=this;for(i=0;i<n.length;i++){nodeObj=viz.graph.getNode(n[i]);nodeObj.setData('alpha',0,'end');nodeObj.ignore=true;}
viz.reposition();viz.fx.animate($.merge(options,{modes:['node-property:alpha','linear'],onComplete:function(){that.removeNode(n,{type:'nothing'});}}));break;case'iter':that=this;viz.fx.sequence({condition:function(){return n.length!=0;},step:function(){that.removeNode(n.shift(),{type:'nothing'});viz.labels.clearLabels();},onComplete:function(){options.onComplete();},duration:Math.ceil(options.duration / n.length)});break;default:this.doError();}},removeEdge:function(vertex,opt){var viz=this.viz;var options=$.merge(this.options,viz.controller,opt);var v=($.type(vertex[0])=='string')?[vertex]:vertex;var i,that,adj;switch(options.type){case'nothing':for(i=0;i<v.length;i++)viz.graph.removeAdjacence(v[i][0],v[i][1]);break;case'replot':this.removeEdge(v,{type:'nothing'});viz.refresh(true);break;case'fade:seq':case'fade':that=this;for(i=0;i<v.length;i++){adj=viz.graph.getAdjacence(v[i][0],v[i][1]);if(adj){adj.setData('alpha',0,'end');}}
viz.fx.animate($.merge(options,{modes:['edge-property:alpha'],onComplete:function(){that.removeEdge(v,{type:'nothing'});viz.reposition();viz.fx.animate($.merge(options,{modes:['linear']}));}}));break;case'fade:con':that=this;for(i=0;i<v.length;i++){adj=viz.graph.getAdjacence(v[i][0],v[i][1]);if(adj){adj.setData('alpha',0,'end');adj.ignore=true;}}
viz.reposition();viz.fx.animate($.merge(options,{modes:['edge-property:alpha','linear'],onComplete:function(){that.removeEdge(v,{type:'nothing'});}}));break;case'iter':that=this;viz.fx.sequence({condition:function(){return v.length!=0;},step:function(){that.removeEdge(v.shift(),{type:'nothing'});viz.labels.clearLabels();},onComplete:function(){options.onComplete();},duration:Math.ceil(options.duration / v.length)});break;default:this.doError();}},sum:function(json,opt){var viz=this.viz;var options=$.merge(this.options,viz.controller,opt),root=viz.root;var graph;viz.root=opt.id||viz.root;switch(options.type){case'nothing':graph=viz.construct(json);graph.eachNode(function(elem){elem.eachAdjacency(function(adj){viz.graph.addAdjacence(adj.nodeFrom,adj.nodeTo,adj.data);});});break;case'replot':viz.refresh(true);this.sum(json,{type:'nothing'});viz.refresh(true);break;case'fade:seq':case'fade':case'fade:con':that=this;graph=viz.construct(json);var fadeEdges=this.preprocessSum(graph);var modes=!fadeEdges?['node-property:alpha']:['node-property:alpha','edge-property:alpha'];viz.reposition();if(options.type!='fade:con'){viz.fx.animate($.merge(options,{modes:['linear'],onComplete:function(){viz.fx.animate($.merge(options,{modes:modes,onComplete:function(){options.onComplete();}}));}}));}else{viz.graph.eachNode(function(elem){if(elem.id!=root&&elem.pos.getp().equals(Polar.KER)){elem.pos.set(elem.endPos);elem.startPos.set(elem.endPos);}});viz.fx.animate($.merge(options,{modes:['linear'].concat(modes)}));}
break;default:this.doError();}},morph:function(json,opt,extraModes){var viz=this.viz;var options=$.merge(this.options,viz.controller,opt),root=viz.root;var graph;viz.root=opt.id||viz.root;switch(options.type){case'nothing':graph=viz.construct(json);graph.eachNode(function(elem){var nodeExists=viz.graph.hasNode(elem.id);elem.eachAdjacency(function(adj){var adjExists=!!viz.graph.getAdjacence(adj.nodeFrom.id,adj.nodeTo.id);viz.graph.addAdjacence(adj.nodeFrom,adj.nodeTo,adj.data);if(adjExists){var addedAdj=viz.graph.getAdjacence(adj.nodeFrom.id,adj.nodeTo.id);for(var prop in(adj.data||{})){addedAdj.data[prop]=adj.data[prop];}}});if(nodeExists){var addedNode=viz.graph.getNode(elem.id);for(var prop in(elem.data||{})){addedNode.data[prop]=elem.data[prop];}}});viz.graph.eachNode(function(elem){elem.eachAdjacency(function(adj){if(!graph.getAdjacence(adj.nodeFrom.id,adj.nodeTo.id)){viz.graph.removeAdjacence(adj.nodeFrom.id,adj.nodeTo.id);}});if(!graph.hasNode(elem.id))viz.graph.removeNode(elem.id);});break;case'replot':viz.labels.clearLabels(true);this.morph(json,{type:'nothing'});viz.refresh(true);viz.refresh(true);break;case'fade:seq':case'fade':case'fade:con':that=this;graph=viz.construct(json);var nodeModes=extraModes&&('node-property'in extraModes)&&$.map($.splat(extraModes['node-property']),function(n){return'$'+n;});viz.graph.eachNode(function(elem){var graphNode=graph.getNode(elem.id);if(!graphNode){elem.setData('alpha',1);elem.setData('alpha',1,'start');elem.setData('alpha',0,'end');elem.ignore=true;}else{var graphNodeData=graphNode.data;for(var prop in graphNodeData){if(nodeModes&&($.indexOf(nodeModes,prop)>-1)){elem.endData[prop]=graphNodeData[prop];}else{elem.data[prop]=graphNodeData[prop];}}}});viz.graph.eachNode(function(elem){if(elem.ignore)return;elem.eachAdjacency(function(adj){if(adj.nodeFrom.ignore||adj.nodeTo.ignore)return;var nodeFrom=graph.getNode(adj.nodeFrom.id);var nodeTo=graph.getNode(adj.nodeTo.id);if(!nodeFrom.adjacentTo(nodeTo)){var adj=viz.graph.getAdjacence(nodeFrom.id,nodeTo.id);fadeEdges=true;adj.setData('alpha',1);adj.setData('alpha',1,'start');adj.setData('alpha',0,'end');}});});var fadeEdges=this.preprocessSum(graph);var modes=!fadeEdges?['node-property:alpha']:['node-property:alpha','edge-property:alpha'];modes[0]=modes[0]+((extraModes&&('node-property'in extraModes))?(':'+$.splat(extraModes['node-property']).join(':')):'');modes[1]=(modes[1]||'edge-property:alpha')+((extraModes&&('edge-property'in extraModes))?(':'+$.splat(extraModes['edge-property']).join(':')):'');if(extraModes&&('label-property'in extraModes)){modes.push('label-property:'+$.splat(extraModes['label-property']).join(':'))}
viz.reposition();viz.graph.eachNode(function(elem){if(elem.id!=root&&elem.pos.getp().equals(Polar.KER)){elem.pos.set(elem.endPos);elem.startPos.set(elem.endPos);}});viz.fx.animate($.merge(options,{modes:['polar'].concat(modes),onComplete:function(){viz.graph.eachNode(function(elem){if(elem.ignore)viz.graph.removeNode(elem.id);});viz.graph.eachNode(function(elem){elem.eachAdjacency(function(adj){if(adj.ignore)viz.graph.removeAdjacence(adj.nodeFrom.id,adj.nodeTo.id);});});options.onComplete();}}));break;default:;}},contract:function(node,opt){var viz=this.viz;if(node.collapsed||!node.anySubnode($.lambda(true)))return;opt=$.merge(this.options,viz.config,opt||{},{'modes':['node-property:alpha:span','linear']});node.collapsed=true;(function subn(n){n.eachSubnode(function(ch){ch.ignore=true;ch.setData('alpha',0,opt.type=='animate'?'end':'current');subn(ch);});})(node);if(opt.type=='animate'){viz.compute('end');if(viz.rotated){viz.rotate(viz.rotated,'none',{'property':'end'});}
(function subn(n){n.eachSubnode(function(ch){ch.setPos(node.getPos('end'),'end');subn(ch);});})(node);viz.fx.animate(opt);}else if(opt.type=='replot'){viz.refresh();}},expand:function(node,opt){if(!('collapsed'in node))return;var viz=this.viz;opt=$.merge(this.options,viz.config,opt||{},{'modes':['node-property:alpha:span','linear']});delete node.collapsed;(function subn(n){n.eachSubnode(function(ch){delete ch.ignore;ch.setData('alpha',1,opt.type=='animate'?'end':'current');subn(ch);});})(node);if(opt.type=='animate'){viz.compute('end');if(viz.rotated){viz.rotate(viz.rotated,'none',{'property':'end'});}
viz.fx.animate(opt);}else if(opt.type=='replot'){viz.refresh();}},preprocessSum:function(graph){var viz=this.viz;graph.eachNode(function(elem){if(!viz.graph.hasNode(elem.id)){viz.graph.addNode(elem);var n=viz.graph.getNode(elem.id);n.setData('alpha',0);n.setData('alpha',0,'start');n.setData('alpha',1,'end');}});var fadeEdges=false;graph.eachNode(function(elem){elem.eachAdjacency(function(adj){var nodeFrom=viz.graph.getNode(adj.nodeFrom.id);var nodeTo=viz.graph.getNode(adj.nodeTo.id);if(!nodeFrom.adjacentTo(nodeTo)){var adj=viz.graph.addAdjacence(nodeFrom,nodeTo,adj.data);if(nodeFrom.startAlpha==nodeFrom.endAlpha&&nodeTo.startAlpha==nodeTo.endAlpha){fadeEdges=true;adj.setData('alpha',0);adj.setData('alpha',0,'start');adj.setData('alpha',1,'end');}}});});return fadeEdges;}};var NodeHelper={'none':{'render':$.empty,'contains':$.lambda(false)},'circle':{'render':function(type,pos,radius,canvas){var ctx=canvas.getCtx();ctx.beginPath();ctx.arc(pos.x,pos.y,radius,0,Math.PI*2,true);ctx.closePath();ctx[type]();},'contains':function(npos,pos,radius){var diffx=npos.x-pos.x,diffy=npos.y-pos.y,diff=diffx*diffx+diffy*diffy;return diff<=radius*radius;}},'ellipse':{'render':function(type,pos,width,height,canvas){var ctx=canvas.getCtx();height /=2;width /=2;ctx.save();ctx.scale(width / height,height / width);ctx.beginPath();ctx.arc(pos.x*(height / width),pos.y*(width / height),height,0,Math.PI*2,true);ctx.closePath();ctx[type]();ctx.restore();},'contains':function(npos,pos,width,height){width /=2;height /=2;var dist=(width+height)/ 2,diffx=npos.x-pos.x,diffy=npos.y-pos.y,diff=diffx*diffx+diffy*diffy;return diff<=dist*dist;}},'square':{'render':function(type,pos,dim,canvas){canvas.getCtx()[type+"Rect"](pos.x-dim,pos.y-dim,2*dim,2*dim);},'contains':function(npos,pos,dim){return Math.abs(pos.x-npos.x)<=dim&&Math.abs(pos.y-npos.y)<=dim;}},'rectangle':{'render':function(type,pos,width,height,canvas){canvas.getCtx()[type+"Rect"](pos.x-width / 2,pos.y-height / 2,width,height);},'contains':function(npos,pos,width,height){return Math.abs(pos.x-npos.x)<=width / 2&&Math.abs(pos.y-npos.y)<=height / 2;}},'triangle':{'render':function(type,pos,dim,canvas){var ctx=canvas.getCtx(),c1x=pos.x,c1y=pos.y-dim,c2x=c1x-dim,c2y=pos.y+dim,c3x=c1x+dim,c3y=c2y;ctx.beginPath();ctx.moveTo(c1x,c1y);ctx.lineTo(c2x,c2y);ctx.lineTo(c3x,c3y);ctx.closePath();ctx[type]();},'contains':function(npos,pos,dim){return NodeHelper.circle.contains(npos,pos,dim);}},'star':{'render':function(type,pos,dim,canvas){var ctx=canvas.getCtx(),pi5=Math.PI / 5;ctx.save();ctx.translate(pos.x,pos.y);ctx.beginPath();ctx.moveTo(dim,0);for(var i=0;i<9;i++){ctx.rotate(pi5);if(i%2==0){ctx.lineTo((dim / 0.525731)*0.200811,0);}else{ctx.lineTo(dim,0);}}
ctx.closePath();ctx[type]();ctx.restore();},'contains':function(npos,pos,dim){return NodeHelper.circle.contains(npos,pos,dim);}}};var EdgeHelper={'line':{'render':function(from,to,canvas){var ctx=canvas.getCtx();ctx.beginPath();ctx.moveTo(from.x,from.y);ctx.lineTo(to.x,to.y);ctx.stroke();},'contains':function(posFrom,posTo,pos,epsilon){var min=Math.min,max=Math.max,minPosX=min(posFrom.x,posTo.x),maxPosX=max(posFrom.x,posTo.x),minPosY=min(posFrom.y,posTo.y),maxPosY=max(posFrom.y,posTo.y);if(pos.x>=minPosX&&pos.x<=maxPosX&&pos.y>=minPosY&&pos.y<=maxPosY){if(Math.abs(posTo.x-posFrom.x)<=epsilon){return true;}
var dist=(posTo.y-posFrom.y)/(posTo.x-posFrom.x)*(pos.x-posFrom.x)+posFrom.y;return Math.abs(dist-pos.y)<=epsilon;}
return false;}},'arrow':{'render':function(from,to,dim,swap,canvas){var ctx=canvas.getCtx();if(swap){var tmp=from;from=to;to=tmp;}
var vect=new Complex(to.x-from.x,to.y-from.y);vect.$scale(dim / vect.norm());var intermediatePoint=new Complex(to.x-vect.x,to.y-vect.y),normal=new Complex(-vect.y / 2,vect.x / 2),v1=intermediatePoint.add(normal),v2=intermediatePoint.$add(normal.$scale(-1));ctx.beginPath();ctx.moveTo(from.x,from.y);ctx.lineTo(to.x,to.y);ctx.stroke();ctx.beginPath();ctx.moveTo(v1.x,v1.y);ctx.lineTo(v2.x,v2.y);ctx.lineTo(to.x,to.y);ctx.closePath();ctx.fill();},'contains':function(posFrom,posTo,pos,epsilon){return EdgeHelper.line.contains(posFrom,posTo,pos,epsilon);}},'hyperline':{'render':function(from,to,r,canvas){var ctx=canvas.getCtx();var centerOfCircle=computeArcThroughTwoPoints(from,to);if(centerOfCircle.a>1000||centerOfCircle.b>1000||centerOfCircle.ratio<0){ctx.beginPath();ctx.moveTo(from.x*r,from.y*r);ctx.lineTo(to.x*r,to.y*r);ctx.stroke();}else{var angleBegin=Math.atan2(to.y-centerOfCircle.y,to.x
-centerOfCircle.x);var angleEnd=Math.atan2(from.y-centerOfCircle.y,from.x
-centerOfCircle.x);var sense=sense(angleBegin,angleEnd);ctx.beginPath();ctx.arc(centerOfCircle.x*r,centerOfCircle.y*r,centerOfCircle.ratio*r,angleBegin,angleEnd,sense);ctx.stroke();}
function computeArcThroughTwoPoints(p1,p2){var aDen=(p1.x*p2.y-p1.y*p2.x),bDen=aDen;var sq1=p1.squaredNorm(),sq2=p2.squaredNorm();if(aDen==0)
return{x:0,y:0,ratio:-1};var a=(p1.y*sq2-p2.y*sq1+p1.y-p2.y)/ aDen;var b=(p2.x*sq1-p1.x*sq2+p2.x-p1.x)/ bDen;var x=-a / 2;var y=-b / 2;var squaredRatio=(a*a+b*b)/ 4-1;if(squaredRatio<0)
return{x:0,y:0,ratio:-1};var ratio=Math.sqrt(squaredRatio);var out={x:x,y:y,ratio:ratio>1000?-1:ratio,a:a,b:b};return out;}
function sense(angleBegin,angleEnd){return(angleBegin<angleEnd)?((angleBegin+Math.PI>angleEnd)?false:true):((angleEnd+Math.PI>angleBegin)?true:false);}},'contains':$.lambda(false)}};Graph.Plot={initialize:function(viz,klass){this.viz=viz;this.config=viz.config;this.node=viz.config.Node;this.edge=viz.config.Edge;this.animation=new Animation;this.nodeTypes=new klass.Plot.NodeTypes;this.edgeTypes=new klass.Plot.EdgeTypes;this.labels=viz.labels;},nodeHelper:NodeHelper,edgeHelper:EdgeHelper,Interpolator:{'map':{'border':'color','color':'color','width':'number','height':'number','dim':'number','alpha':'number','lineWidth':'number','angularWidth':'number','span':'number','valueArray':'array-number','dimArray':'array-number'},'canvas':{'globalAlpha':'number','fillStyle':'color','strokeStyle':'color','lineWidth':'number','shadowBlur':'number','shadowColor':'color','shadowOffsetX':'number','shadowOffsetY':'number','miterLimit':'number'},'label':{'size':'number','color':'color'},'compute':function(from,to,delta){return from+(to-from)*delta;},'moebius':function(elem,props,delta,vector){var v=vector.scale(-delta);if(v.norm()<1){var x=v.x,y=v.y;var ans=elem.startPos.getc().moebiusTransformation(v);elem.pos.setc(ans.x,ans.y);v.x=x;v.y=y;}},'linear':function(elem,props,delta){var from=elem.startPos.getc(true);var to=elem.endPos.getc(true);elem.pos.setc(this.compute(from.x,to.x,delta),this.compute(from.y,to.y,delta));},'polar':function(elem,props,delta){var from=elem.startPos.getp(true);var to=elem.endPos.getp();var ans=to.interpolate(from,delta);elem.pos.setp(ans.theta,ans.rho);},'number':function(elem,prop,delta,getter,setter){var from=elem[getter](prop,'start');var to=elem[getter](prop,'end');elem[setter](prop,this.compute(from,to,delta));},'color':function(elem,prop,delta,getter,setter){var from=$.hexToRgb(elem[getter](prop,'start'));var to=$.hexToRgb(elem[getter](prop,'end'));var comp=this.compute;var val=$.rgbToHex([parseInt(comp(from[0],to[0],delta)),parseInt(comp(from[1],to[1],delta)),parseInt(comp(from[2],to[2],delta))]);elem[setter](prop,val);},'array-number':function(elem,prop,delta,getter,setter){var from=elem[getter](prop,'start'),to=elem[getter](prop,'end'),cur=[];for(var i=0,l=from.length;i<l;i++){var fromi=from[i],toi=to[i];if(fromi.length){for(var j=0,len=fromi.length,curi=[];j<len;j++){curi.push(this.compute(fromi[j],toi[j],delta));}
cur.push(curi);}else{cur.push(this.compute(fromi,toi,delta));}}
elem[setter](prop,cur);},'node':function(elem,props,delta,map,getter,setter){map=this[map];if(props){var len=props.length;for(var i=0;i<len;i++){var pi=props[i];this[map[pi]](elem,pi,delta,getter,setter);}}else{for(var pi in map){this[map[pi]](elem,pi,delta,getter,setter);}}},'edge':function(elem,props,delta,mapKey,getter,setter){var adjs=elem.adjacencies;for(var id in adjs)this['node'](adjs[id],props,delta,mapKey,getter,setter);},'node-property':function(elem,props,delta){this['node'](elem,props,delta,'map','getData','setData');},'edge-property':function(elem,props,delta){this['edge'](elem,props,delta,'map','getData','setData');},'label-property':function(elem,props,delta){this['node'](elem,props,delta,'label','getLabelData','setLabelData');},'node-style':function(elem,props,delta){this['node'](elem,props,delta,'canvas','getCanvasStyle','setCanvasStyle');},'edge-style':function(elem,props,delta){this['edge'](elem,props,delta,'canvas','getCanvasStyle','setCanvasStyle');}},sequence:function(options){var that=this;options=$.merge({condition:$.lambda(false),step:$.empty,onComplete:$.empty,duration:200},options||{});var interval=setInterval(function(){if(options.condition()){options.step();}else{clearInterval(interval);options.onComplete();}
that.viz.refresh(true);},options.duration);},prepare:function(modes){var graph=this.viz.graph,accessors={'node-property':{'getter':'getData','setter':'setData'},'edge-property':{'getter':'getData','setter':'setData'},'node-style':{'getter':'getCanvasStyle','setter':'setCanvasStyle'},'edge-style':{'getter':'getCanvasStyle','setter':'setCanvasStyle'}};var m={};if($.type(modes)=='array'){for(var i=0,len=modes.length;i<len;i++){var elems=modes[i].split(':');m[elems.shift()]=elems;}}else{for(var p in modes){if(p=='position'){m[modes.position]=[];}else{m[p]=$.splat(modes[p]);}}}
graph.eachNode(function(node){node.startPos.set(node.pos);$.each(['node-property','node-style'],function(p){if(p in m){var prop=m[p];for(var i=0,l=prop.length;i<l;i++){node[accessors[p].setter](prop[i],node[accessors[p].getter](prop[i]),'start');}}});$.each(['edge-property','edge-style'],function(p){if(p in m){var prop=m[p];node.eachAdjacency(function(adj){for(var i=0,l=prop.length;i<l;i++){adj[accessors[p].setter](prop[i],adj[accessors[p].getter](prop[i]),'start');}});}});});return m;},animate:function(opt,versor){opt=$.merge(this.viz.config,opt||{});var that=this,viz=this.viz,graph=viz.graph,interp=this.Interpolator,animation=opt.type==='nodefx'?this.nodeFxAnimation:this.animation;var m=this.prepare(opt.modes);if(opt.hideLabels)this.labels.hideLabels(true);animation.setOptions($.merge(opt,{$animating:false,compute:function(delta){graph.eachNode(function(node){for(var p in m){interp[p](node,m[p],delta,versor);}});that.plot(opt,this.$animating,delta);this.$animating=true;},complete:function(){if(opt.hideLabels)that.labels.hideLabels(false);that.plot(opt);opt.onComplete();opt.onAfterCompute();}})).start();},nodeFx:function(opt){var viz=this.viz,graph=viz.graph,animation=this.nodeFxAnimation,options=$.merge(this.viz.config,{'elements':{'id':false,'properties':{}},'reposition':false});opt=$.merge(options,opt||{},{onBeforeCompute:$.empty,onAfterCompute:$.empty});animation.stopTimer();var props=opt.elements.properties;if(!opt.elements.id){graph.eachNode(function(n){for(var prop in props){n.setData(prop,props[prop],'end');}});}else{var ids=$.splat(opt.elements.id);$.each(ids,function(id){var n=graph.getNode(id);if(n){for(var prop in props){n.setData(prop,props[prop],'end');}}});}
var propnames=[];for(var prop in props)propnames.push(prop);var modes=['node-property:'+propnames.join(':')];if(opt.reposition){modes.push('linear');viz.compute('end');}
this.animate($.merge(opt,{modes:modes,type:'nodefx'}));},plot:function(opt,animating){var viz=this.viz,aGraph=viz.graph,canvas=viz.canvas,id=viz.root,that=this,ctx=canvas.getCtx(),min=Math.min,opt=opt||this.viz.controller;opt.clearCanvas&&canvas.clear();var root=aGraph.getNode(id);if(!root)return;var T=!!root.visited;aGraph.eachNode(function(node){var nodeAlpha=node.getData('alpha');node.eachAdjacency(function(adj){var nodeTo=adj.nodeTo;if(!!nodeTo.visited===T&&node.drawn&&nodeTo.drawn){!animating&&opt.onBeforePlotLine(adj);ctx.save();ctx.globalAlpha=min(nodeAlpha,nodeTo.getData('alpha'),adj.getData('alpha'));that.plotLine(adj,canvas,animating);ctx.restore();!animating&&opt.onAfterPlotLine(adj);}});ctx.save();if(node.drawn){!animating&&opt.onBeforePlotNode(node);that.plotNode(node,canvas,animating);!animating&&opt.onAfterPlotNode(node);}
if(!that.labelsHidden&&opt.withLabels){if(node.drawn&&nodeAlpha>=0.95){that.labels.plotLabel(canvas,node,opt);}else{that.labels.hideLabel(node,false);}}
ctx.restore();node.visited=!T;});},plotTree:function(node,opt,animating){var that=this,viz=this.viz,canvas=viz.canvas,config=this.config,ctx=canvas.getCtx();var nodeAlpha=node.getData('alpha');node.eachSubnode(function(elem){if(opt.plotSubtree(node,elem)&&elem.exist&&elem.drawn){var adj=node.getAdjacency(elem.id);!animating&&opt.onBeforePlotLine(adj);ctx.globalAlpha=Math.min(nodeAlpha,elem.getData('alpha'));that.plotLine(adj,canvas,animating);!animating&&opt.onAfterPlotLine(adj);that.plotTree(elem,opt,animating);}});if(node.drawn){!animating&&opt.onBeforePlotNode(node);this.plotNode(node,canvas,animating);!animating&&opt.onAfterPlotNode(node);if(!opt.hideLabels&&opt.withLabels&&nodeAlpha>=0.95)
this.labels.plotLabel(canvas,node,opt);else
this.labels.hideLabel(node,false);}else{this.labels.hideLabel(node,true);}},plotNode:function(node,canvas,animating){var f=node.getData('type'),ctxObj=this.node.CanvasStyles;if(f!='none'){var width=node.getData('lineWidth'),color=node.getData('color'),alpha=node.getData('alpha'),ctx=canvas.getCtx();ctx.lineWidth=width;ctx.fillStyle=ctx.strokeStyle=color;ctx.globalAlpha=alpha;for(var s in ctxObj){ctx[s]=node.getCanvasStyle(s);}
this.nodeTypes[f].render.call(this,node,canvas,animating);}},plotLine:function(adj,canvas,animating){var f=adj.getData('type'),ctxObj=this.edge.CanvasStyles;if(f!='none'){var width=adj.getData('lineWidth'),color=adj.getData('color'),ctx=canvas.getCtx();ctx.lineWidth=width;ctx.fillStyle=ctx.strokeStyle=color;for(var s in ctxObj){ctx[s]=adj.getCanvasStyle(s);}
this.edgeTypes[f].render.call(this,adj,canvas,animating);}}};Graph.Label={};Graph.Label.Native=new Class({plotLabel:function(canvas,node,controller){var ctx=canvas.getCtx();var pos=node.pos.getc(true);ctx.font=node.getLabelData('style')+' '+node.getLabelData('size')+'px '+node.getLabelData('family');ctx.textAlign=node.getLabelData('textAlign');ctx.fillStyle=ctx.strokeStyle=node.getLabelData('color');ctx.textBaseline=node.getLabelData('textBaseline');this.renderLabel(canvas,node,controller);},renderLabel:function(canvas,node,controller){var ctx=canvas.getCtx();var pos=node.pos.getc(true);ctx.fillText(node.name,pos.x,pos.y+node.getData("height")/ 2);},hideLabel:$.empty,hideLabels:$.empty});Graph.Label.DOM=new Class({labelsHidden:false,labelContainer:false,labels:{},getLabelContainer:function(){return this.labelContainer?this.labelContainer:this.labelContainer=document.getElementById(this.viz.config.labelContainer);},getLabel:function(id){return(id in this.labels&&this.labels[id]!=null)?this.labels[id]:this.labels[id]=document.getElementById(id);},hideLabels:function(hide){var container=this.getLabelContainer();if(hide)
container.style.display='none';else
container.style.display='';this.labelsHidden=hide;},clearLabels:function(force){for(var id in this.labels){if(force||!this.viz.graph.hasNode(id)){this.disposeLabel(id);delete this.labels[id];}}},disposeLabel:function(id){var elem=this.getLabel(id);if(elem&&elem.parentNode){elem.parentNode.removeChild(elem);}},hideLabel:function(node,show){node=$.splat(node);var st=show?"":"none",lab,that=this;$.each(node,function(n){var lab=that.getLabel(n.id);if(lab){lab.style.display=st;}});},fitsInCanvas:function(pos,canvas){var size=canvas.getSize();if(pos.x>=size.width||pos.x<0||pos.y>=size.height||pos.y<0)return false;return true;}});Graph.Label.HTML=new Class({Implements:Graph.Label.DOM,plotLabel:function(canvas,node,controller){var id=node.id,tag=this.getLabel(id);if(!tag&&!(tag=document.getElementById(id))){tag=document.createElement('div');var container=this.getLabelContainer();tag.id=id;tag.className='node';tag.style.position='absolute';controller.onCreateLabel(tag,node);container.appendChild(tag);this.labels[node.id]=tag;}
this.placeLabel(tag,node,controller);}});Graph.Label.SVG=new Class({Implements:Graph.Label.DOM,plotLabel:function(canvas,node,controller){var id=node.id,tag=this.getLabel(id);if(!tag&&!(tag=document.getElementById(id))){var ns='http://www.w3.org/2000/svg';tag=document.createElementNS(ns,'svg:text');var tspan=document.createElementNS(ns,'svg:tspan');tag.appendChild(tspan);var container=this.getLabelContainer();tag.setAttribute('id',id);tag.setAttribute('class','node');container.appendChild(tag);controller.onCreateLabel(tag,node);this.labels[node.id]=tag;}
this.placeLabel(tag,node,controller);}});Graph.Geom=new Class({initialize:function(viz){this.viz=viz;this.config=viz.config;this.node=viz.config.Node;this.edge=viz.config.Edge;},translate:function(pos,prop){prop=$.splat(prop);this.viz.graph.eachNode(function(elem){$.each(prop,function(p){elem.getPos(p).$add(pos);});});},setRightLevelToShow:function(node,canvas,callback){var level=this.getRightLevelToShow(node,canvas),fx=this.viz.labels,opt=$.merge({execShow:true,execHide:true,onHide:$.empty,onShow:$.empty},callback||{});node.eachLevel(0,this.config.levelsToShow,function(n){var d=n._depth-node._depth;if(d>level){opt.onHide(n);if(opt.execHide){n.drawn=false;n.exist=false;fx.hideLabel(n,false);}}else{opt.onShow(n);if(opt.execShow){n.exist=true;}}});node.drawn=true;},getRightLevelToShow:function(node,canvas){var config=this.config;var level=config.levelsToShow;var constrained=config.constrained;if(!constrained)return level;while(!this.treeFitsInCanvas(node,canvas,level)&&level>1){level--;}
return level;}});var Loader={construct:function(json){var isGraph=($.type(json)=='array');var ans=new Graph(this.graphOptions,this.config.Node,this.config.Edge,this.config.Label);if(!isGraph)
(function(ans,json){ans.addNode(json);if(json.children){for(var i=0,ch=json.children;i<ch.length;i++){ans.addAdjacence(json,ch[i]);arguments.callee(ans,ch[i]);}}})(ans,json);else
(function(ans,json){var getNode=function(id){for(var i=0,l=json.length;i<l;i++){if(json[i].id==id){return json[i];}}
var newNode={"id":id,"name":id};return ans.addNode(newNode);};for(var i=0,l=json.length;i<l;i++){ans.addNode(json[i]);var adj=json[i].adjacencies;if(adj){for(var j=0,lj=adj.length;j<lj;j++){var node=adj[j],data={};if(typeof adj[j]!='string'){data=$.merge(node.data,{});node=node.nodeTo;}
ans.addAdjacence(json[i],getNode(node),data);}}}})(ans,json);return ans;},loadJSON:function(json,i){this.json=json;if(this.labels&&this.labels.clearLabels){this.labels.clearLabels(true);}
this.graph=this.construct(json);if($.type(json)!='array'){this.root=json.id;}else{this.root=json[i?i:0].id;}},toJSON:function(type){type=type||"tree";if(type=='tree'){var ans={};var rootNode=this.graph.getNode(this.root);var ans=(function recTree(node){var ans={};ans.id=node.id;ans.name=node.name;ans.data=node.data;var ch=[];node.eachSubnode(function(n){ch.push(recTree(n));});ans.children=ch;return ans;})(rootNode);return ans;}else{var ans=[];var T=!!this.graph.getNode(this.root).visited;this.graph.eachNode(function(node){var ansNode={};ansNode.id=node.id;ansNode.name=node.name;ansNode.data=node.data;var adjs=[];node.eachAdjacency(function(adj){var nodeTo=adj.nodeTo;if(!!nodeTo.visited===T){var ansAdj={};ansAdj.nodeTo=nodeTo.id;ansAdj.data=adj.data;adjs.push(ansAdj);}});ansNode.adjacencies=adjs;ans.push(ansNode);node.visited=!T;});return ans;}}};var Layouts=$jit.Layouts={};var NodeDim={label:null,compute:function(graph,prop,opt){this.initializeLabel(opt);var label=this.label,style=label.style;graph.eachNode(function(n){var autoWidth=n.getData('autoWidth'),autoHeight=n.getData('autoHeight');if(autoWidth||autoHeight){delete n.data.$width;delete n.data.$height;delete n.data.$dim;var width=n.getData('width'),height=n.getData('height');style.width=autoWidth?'auto':width+'px';style.height=autoHeight?'auto':height+'px';label.innerHTML=n.name;var offsetWidth=label.offsetWidth,offsetHeight=label.offsetHeight;var type=n.getData('type');if($.indexOf(['circle','square','triangle','star'],type)===-1){n.setData('width',offsetWidth);n.setData('height',offsetHeight);}else{var dim=offsetWidth>offsetHeight?offsetWidth:offsetHeight;n.setData('width',dim);n.setData('height',dim);n.setData('dim',dim);}}});},initializeLabel:function(opt){if(!this.label){this.label=document.createElement('div');document.body.appendChild(this.label);}
this.setLabelStyles(opt);},setLabelStyles:function(opt){$.extend(this.label.style,{'visibility':'hidden','position':'absolute','width':'auto','height':'auto'});this.label.className='jit-autoadjust-label';}};Layouts.Tree=(function(){var slice=Array.prototype.slice;function getBoundaries(graph,config,level,orn,prop){var dim=config.Node;var multitree=config.multitree;if(dim.overridable){var w=-1,h=-1;graph.eachNode(function(n){if(n._depth==level&&(!multitree||('$orn'in n.data)&&n.data.$orn==orn)){var dw=n.getData('width',prop);var dh=n.getData('height',prop);w=(w<dw)?dw:w;h=(h<dh)?dh:h;}});return{'width':w<0?dim.width:w,'height':h<0?dim.height:h};}else{return dim;}}
function movetree(node,prop,val,orn){var p=(orn=="left"||orn=="right")?"y":"x";node.getPos(prop)[p]+=val;}
function moveextent(extent,val){var ans=[];$.each(extent,function(elem){elem=slice.call(elem);elem[0]+=val;elem[1]+=val;ans.push(elem);});return ans;}
function merge(ps,qs){if(ps.length==0)
return qs;if(qs.length==0)
return ps;var p=ps.shift(),q=qs.shift();return[[p[0],q[1]]].concat(merge(ps,qs));}
function mergelist(ls,def){def=def||[];if(ls.length==0)
return def;var ps=ls.pop();return mergelist(ls,merge(ps,def));}
function fit(ext1,ext2,subtreeOffset,siblingOffset,i){if(ext1.length<=i||ext2.length<=i)
return 0;var p=ext1[i][1],q=ext2[i][0];return Math.max(fit(ext1,ext2,subtreeOffset,siblingOffset,++i)
+subtreeOffset,p-q+siblingOffset);}
function fitlistl(es,subtreeOffset,siblingOffset){function $fitlistl(acc,es,i){if(es.length<=i)
return[];var e=es[i],ans=fit(acc,e,subtreeOffset,siblingOffset,0);return[ans].concat($fitlistl(merge(acc,moveextent(e,ans)),es,++i));};return $fitlistl([],es,0);}
function fitlistr(es,subtreeOffset,siblingOffset){function $fitlistr(acc,es,i){if(es.length<=i)
return[];var e=es[i],ans=-fit(e,acc,subtreeOffset,siblingOffset,0);return[ans].concat($fitlistr(merge(moveextent(e,ans),acc),es,++i));};es=slice.call(es);var ans=$fitlistr([],es.reverse(),0);return ans.reverse();}
function fitlist(es,subtreeOffset,siblingOffset,align){var esl=fitlistl(es,subtreeOffset,siblingOffset),esr=fitlistr(es,subtreeOffset,siblingOffset);if(align=="left")
esr=esl;else if(align=="right")
esl=esr;for(var i=0,ans=[];i<esl.length;i++){ans[i]=(esl[i]+esr[i])/ 2;}
return ans;}
function design(graph,node,prop,config,orn){var multitree=config.multitree;var auxp=['x','y'],auxs=['width','height'];var ind=+(orn=="left"||orn=="right");var p=auxp[ind],notp=auxp[1-ind];var cnode=config.Node;var s=auxs[ind],nots=auxs[1-ind];var siblingOffset=config.siblingOffset;var subtreeOffset=config.subtreeOffset;var align=config.align;function $design(node,maxsize,acum){var sval=node.getData(s,prop);var notsval=maxsize||(node.getData(nots,prop));var trees=[],extents=[],chmaxsize=false;var chacum=notsval+config.levelDistance;node.eachSubnode(function(n){if(n.exist&&(!multitree||('$orn'in n.data)&&n.data.$orn==orn)){if(!chmaxsize)
chmaxsize=getBoundaries(graph,config,n._depth,orn,prop);var s=$design(n,chmaxsize[nots],acum+chacum);trees.push(s.tree);extents.push(s.extent);}});var positions=fitlist(extents,subtreeOffset,siblingOffset,align);for(var i=0,ptrees=[],pextents=[];i<trees.length;i++){movetree(trees[i],prop,positions[i],orn);pextents.push(moveextent(extents[i],positions[i]));}
var resultextent=[[-sval / 2,sval / 2]].concat(mergelist(pextents));node.getPos(prop)[p]=0;if(orn=="top"||orn=="left"){node.getPos(prop)[notp]=acum;}else{node.getPos(prop)[notp]=-acum;}
return{tree:node,extent:resultextent};}
$design(node,false,0);}
return new Class({compute:function(property,computeLevels){var prop=property||'start';var node=this.graph.getNode(this.root);$.extend(node,{'drawn':true,'exist':true,'selected':true});NodeDim.compute(this.graph,prop,this.config);if(!!computeLevels||!("_depth"in node)){this.graph.computeLevels(this.root,0,"ignore");}
this.computePositions(node,prop);},computePositions:function(node,prop){var config=this.config;var multitree=config.multitree;var align=config.align;var indent=align!=='center'&&config.indent;var orn=config.orientation;var orns=multitree?['top','right','bottom','left']:[orn];var that=this;$.each(orns,function(orn){design(that.graph,node,prop,that.config,orn,prop);var i=['x','y'][+(orn=="left"||orn=="right")];(function red(node){node.eachSubnode(function(n){if(n.exist&&(!multitree||('$orn'in n.data)&&n.data.$orn==orn)){n.getPos(prop)[i]+=node.getPos(prop)[i];if(indent){n.getPos(prop)[i]+=align=='left'?indent:-indent;}
red(n);}});})(node);});}});})();$jit.ST=(function(){var nodesInPath=[];function getNodesToHide(node){node=node||this.clickedNode;if(!this.config.constrained){return[];}
var Geom=this.geom;var graph=this.graph;var canvas=this.canvas;var level=node._depth,nodeArray=[];graph.eachNode(function(n){if(n.exist&&!n.selected){if(n.isDescendantOf(node.id)){if(n._depth<=level)nodeArray.push(n);}else{nodeArray.push(n);}}});var leafLevel=Geom.getRightLevelToShow(node,canvas);node.eachLevel(leafLevel,leafLevel,function(n){if(n.exist&&!n.selected)nodeArray.push(n);});for(var i=0;i<nodesInPath.length;i++){var n=this.graph.getNode(nodesInPath[i]);if(!n.isDescendantOf(node.id)){nodeArray.push(n);}}
return nodeArray;};function getNodesToShow(node){var nodeArray=[],config=this.config;node=node||this.clickedNode;this.clickedNode.eachLevel(0,config.levelsToShow,function(n){if(config.multitree&&!('$orn'in n.data)&&n.anySubnode(function(ch){return ch.exist&&!ch.drawn;})){nodeArray.push(n);}else if(n.drawn&&!n.anySubnode("drawn")){nodeArray.push(n);}});return nodeArray;};return new Class({Implements:[Loader,Extras,Layouts.Tree],initialize:function(controller){var $ST=$jit.ST;var config={levelsToShow:2,levelDistance:30,constrained:true,Node:{type:'rectangle'},duration:700,offsetX:0,offsetY:0};this.controller=this.config=$.merge(Options("Canvas","Fx","Tree","Node","Edge","Controller","Tips","NodeStyles","Events","Navigation","Label"),config,controller);var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{if(canvasConfig.background){canvasConfig.background=$.merge({type:'Fade',colorStop1:this.config.colorStop1,colorStop2:this.config.colorStop2},canvasConfig.background);}
this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':true};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new $ST.Label[canvasConfig.Label.type](this);this.fx=new $ST.Plot(this,$ST);this.op=new $ST.Op(this);this.group=new $ST.Group(this);this.geom=new $ST.Geom(this);this.clickedNode=null;this.initializeExtras();},plot:function(){this.fx.plot(this.controller);},switchPosition:function(pos,method,onComplete){var Geom=this.geom,Plot=this.fx,that=this;if(!Plot.busy){Plot.busy=true;this.contract({onComplete:function(){Geom.switchOrientation(pos);that.compute('end',false);Plot.busy=false;if(method=='animate'){that.onClick(that.clickedNode.id,onComplete);}else if(method=='replot'){that.select(that.clickedNode.id,onComplete);}}},pos);}},switchAlignment:function(align,method,onComplete){this.config.align=align;if(method=='animate'){this.select(this.clickedNode.id,onComplete);}else if(method=='replot'){this.onClick(this.clickedNode.id,onComplete);}},addNodeInPath:function(id){nodesInPath.push(id);this.select((this.clickedNode&&this.clickedNode.id)||this.root);},clearNodesInPath:function(id){nodesInPath.length=0;this.select((this.clickedNode&&this.clickedNode.id)||this.root);},refresh:function(){this.reposition();this.select((this.clickedNode&&this.clickedNode.id)||this.root);},reposition:function(){this.graph.computeLevels(this.root,0,"ignore");this.geom.setRightLevelToShow(this.clickedNode,this.canvas);this.graph.eachNode(function(n){if(n.exist)n.drawn=true;});this.compute('end');},requestNodes:function(node,onComplete){var handler=$.merge(this.controller,onComplete),lev=this.config.levelsToShow;if(handler.request){var leaves=[],d=node._depth;node.eachLevel(0,lev,function(n){if(n.drawn&&!n.anySubnode()){leaves.push(n);n._level=lev-(n._depth-d);}});this.group.requestNodes(leaves,handler);}
else
handler.onComplete();},contract:function(onComplete,switched){var orn=this.config.orientation;var Geom=this.geom,Group=this.group;if(switched)Geom.switchOrientation(switched);var nodes=getNodesToHide.call(this);if(switched)Geom.switchOrientation(orn);Group.contract(nodes,$.merge(this.controller,onComplete));},move:function(node,onComplete){this.compute('end',false);var move=onComplete.Move,offset={'x':move.offsetX,'y':move.offsetY};if(move.enable){this.geom.translate(node.endPos.add(offset).$scale(-1),"end");}
this.fx.animate($.merge(this.controller,{modes:['linear']},onComplete));},expand:function(node,onComplete){var nodeArray=getNodesToShow.call(this,node);this.group.expand(nodeArray,$.merge(this.controller,onComplete));},selectPath:function(node){var that=this;this.graph.eachNode(function(n){n.selected=false;});function path(node){if(node==null||node.selected)return;node.selected=true;$.each(that.group.getSiblings([node])[node.id],function(n){n.exist=true;n.drawn=true;});var parents=node.getParents();parents=(parents.length>0)?parents[0]:null;path(parents);};for(var i=0,ns=[node.id].concat(nodesInPath);i<ns.length;i++){path(this.graph.getNode(ns[i]));}},setRoot:function(id,method,onComplete){if(this.busy)return;this.busy=true;var that=this,canvas=this.canvas;var rootNode=this.graph.getNode(this.root);var clickedNode=this.graph.getNode(id);function $setRoot(){if(this.config.multitree&&clickedNode.data.$orn){var orn=clickedNode.data.$orn;var opp={'left':'right','right':'left','top':'bottom','bottom':'top'}[orn];rootNode.data.$orn=opp;(function tag(rootNode){rootNode.eachSubnode(function(n){if(n.id!=id){n.data.$orn=opp;tag(n);}});})(rootNode);delete clickedNode.data.$orn;}
this.root=id;this.clickedNode=clickedNode;this.graph.computeLevels(this.root,0,"ignore");this.geom.setRightLevelToShow(clickedNode,canvas,{execHide:false,onShow:function(node){if(!node.drawn){node.drawn=true;node.setData('alpha',1,'end');node.setData('alpha',0);node.pos.setc(clickedNode.pos.x,clickedNode.pos.y);}}});this.compute('end');this.busy=true;this.fx.animate({modes:['linear','node-property:alpha'],onComplete:function(){that.busy=false;that.onClick(id,{onComplete:function(){onComplete&&onComplete.onComplete();}});}});}
delete rootNode.data.$orns;if(method=='animate'){$setRoot.call(this);that.selectPath(clickedNode);}else if(method=='replot'){$setRoot.call(this);this.select(this.root);}},addSubtree:function(subtree,method,onComplete){if(method=='replot'){this.op.sum(subtree,$.extend({type:'replot'},onComplete||{}));}else if(method=='animate'){this.op.sum(subtree,$.extend({type:'fade:seq'},onComplete||{}));}},removeSubtree:function(id,removeRoot,method,onComplete){var node=this.graph.getNode(id),subids=[];node.eachLevel(+!removeRoot,false,function(n){subids.push(n.id);});if(method=='replot'){this.op.removeNode(subids,$.extend({type:'replot'},onComplete||{}));}else if(method=='animate'){this.op.removeNode(subids,$.extend({type:'fade:seq'},onComplete||{}));}},select:function(id,onComplete){var group=this.group,geom=this.geom;var node=this.graph.getNode(id),canvas=this.canvas;var root=this.graph.getNode(this.root);var complete=$.merge(this.controller,onComplete);var that=this;complete.onBeforeCompute(node);this.selectPath(node);this.clickedNode=node;this.requestNodes(node,{onComplete:function(){group.hide(group.prepare(getNodesToHide.call(that)),complete);geom.setRightLevelToShow(node,canvas);that.compute("current");that.graph.eachNode(function(n){var pos=n.pos.getc(true);n.startPos.setc(pos.x,pos.y);n.endPos.setc(pos.x,pos.y);n.visited=false;});var offset={x:complete.offsetX,y:complete.offsetY};that.geom.translate(node.endPos.add(offset).$scale(-1),["start","current","end"]);group.show(getNodesToShow.call(that));that.plot();complete.onAfterCompute(that.clickedNode);complete.onComplete();}});},onClick:function(id,options){var canvas=this.canvas,that=this,Geom=this.geom,config=this.config;var innerController={Move:{enable:true,offsetX:config.offsetX||0,offsetY:config.offsetY||0},setRightLevelToShowConfig:false,onBeforeRequest:$.empty,onBeforeContract:$.empty,onBeforeMove:$.empty,onBeforeExpand:$.empty};var complete=$.merge(this.controller,innerController,options);if(!this.busy){this.busy=true;var node=this.graph.getNode(id);this.selectPath(node,this.clickedNode);this.clickedNode=node;complete.onBeforeCompute(node);complete.onBeforeRequest(node);this.requestNodes(node,{onComplete:function(){complete.onBeforeContract(node);that.contract({onComplete:function(){Geom.setRightLevelToShow(node,canvas,complete.setRightLevelToShowConfig);complete.onBeforeMove(node);that.move(node,{Move:complete.Move,onComplete:function(){complete.onBeforeExpand(node);that.expand(node,{onComplete:function(){that.busy=false;complete.onAfterCompute(id);complete.onComplete();}});}});}});}});}}});})();$jit.ST.$extend=true;$jit.ST.Op=new Class({Implements:Graph.Op});$jit.ST.Group=new Class({initialize:function(viz){this.viz=viz;this.canvas=viz.canvas;this.config=viz.config;this.animation=new Animation;this.nodes=null;},requestNodes:function(nodes,controller){var counter=0,len=nodes.length,nodeSelected={};var complete=function(){controller.onComplete();};var viz=this.viz;if(len==0)complete();for(var i=0;i<len;i++){nodeSelected[nodes[i].id]=nodes[i];controller.request(nodes[i].id,nodes[i]._level,{onComplete:function(nodeId,data){if(data&&data.children){data.id=nodeId;viz.op.sum(data,{type:'nothing'});}
if(++counter==len){viz.graph.computeLevels(viz.root,0);complete();}}});}},contract:function(nodes,controller){var viz=this.viz;var that=this;nodes=this.prepare(nodes);this.animation.setOptions($.merge(controller,{$animating:false,compute:function(delta){if(delta==1)delta=0.99;that.plotStep(1-delta,controller,this.$animating);this.$animating='contract';},complete:function(){that.hide(nodes,controller);}})).start();},hide:function(nodes,controller){var viz=this.viz;for(var i=0;i<nodes.length;i++){if(true||!controller||!controller.request){nodes[i].eachLevel(1,false,function(elem){if(elem.exist){$.extend(elem,{'drawn':false,'exist':false});}});}else{var ids=[];nodes[i].eachLevel(1,false,function(n){ids.push(n.id);});viz.op.removeNode(ids,{'type':'nothing'});viz.labels.clearLabels();}}
controller.onComplete();},expand:function(nodes,controller){var that=this;this.show(nodes);this.animation.setOptions($.merge(controller,{$animating:false,compute:function(delta){that.plotStep(delta,controller,this.$animating);this.$animating='expand';},complete:function(){that.plotStep(undefined,controller,false);controller.onComplete();}})).start();},show:function(nodes){var config=this.config;this.prepare(nodes);$.each(nodes,function(n){if(config.multitree&&!('$orn'in n.data)){delete n.data.$orns;var orns=' ';n.eachSubnode(function(ch){if(('$orn'in ch.data)&&orns.indexOf(ch.data.$orn)<0&&ch.exist&&!ch.drawn){orns+=ch.data.$orn+' ';}});n.data.$orns=orns;}
n.eachLevel(0,config.levelsToShow,function(n){if(n.exist)n.drawn=true;});});},prepare:function(nodes){this.nodes=this.getNodesWithChildren(nodes);return this.nodes;},getNodesWithChildren:function(nodes){var ans=[],config=this.config,root=this.viz.root;nodes.sort(function(a,b){return(a._depth<=b._depth)-(a._depth>=b._depth);});for(var i=0;i<nodes.length;i++){if(nodes[i].anySubnode("exist")){for(var j=i+1,desc=false;!desc&&j<nodes.length;j++){if(!config.multitree||'$orn'in nodes[j].data){desc=desc||nodes[i].isDescendantOf(nodes[j].id);}}
if(!desc)ans.push(nodes[i]);}}
return ans;},plotStep:function(delta,controller,animating){var viz=this.viz,config=this.config,canvas=viz.canvas,ctx=canvas.getCtx(),nodes=this.nodes;var i,node;var nds={};for(i=0;i<nodes.length;i++){node=nodes[i];nds[node.id]=[];var root=config.multitree&&!('$orn'in node.data);var orns=root&&node.data.$orns;node.eachSubgraph(function(n){if(root&&orns&&orns.indexOf(n.data.$orn)>0&&n.drawn){n.drawn=false;nds[node.id].push(n);}else if((!root||!orns)&&n.drawn){n.drawn=false;nds[node.id].push(n);}});node.drawn=true;}
if(nodes.length>0)viz.fx.plot();for(i in nds){$.each(nds[i],function(n){n.drawn=true;});}
for(i=0;i<nodes.length;i++){node=nodes[i];ctx.save();viz.fx.plotSubtree(node,controller,delta,animating);ctx.restore();}},getSiblings:function(nodes){var siblings={};$.each(nodes,function(n){var par=n.getParents();if(par.length==0){siblings[n.id]=[n];}else{var ans=[];par[0].eachSubnode(function(sn){ans.push(sn);});siblings[n.id]=ans;}});return siblings;}});$jit.ST.Geom=new Class({Implements:Graph.Geom,switchOrientation:function(orn){this.config.orientation=orn;},dispatch:function(){var args=Array.prototype.slice.call(arguments);var s=args.shift(),len=args.length;var val=function(a){return typeof a=='function'?a():a;};if(len==2){return(s=="top"||s=="bottom")?val(args[0]):val(args[1]);}else if(len==4){switch(s){case"top":return val(args[0]);case"right":return val(args[1]);case"bottom":return val(args[2]);case"left":return val(args[3]);}}
return undefined;},getSize:function(n,invert){var data=n.data,config=this.config;var siblingOffset=config.siblingOffset;var s=(config.multitree&&('$orn'in data)&&data.$orn)||config.orientation;var w=n.getData('width')+siblingOffset;var h=n.getData('height')+siblingOffset;if(!invert)
return this.dispatch(s,h,w);else
return this.dispatch(s,w,h);},getTreeBaseSize:function(node,level,leaf){var size=this.getSize(node,true),baseHeight=0,that=this;if(leaf(level,node))return size;if(level===0)return 0;node.eachSubnode(function(elem){baseHeight+=that.getTreeBaseSize(elem,level-1,leaf);});return(size>baseHeight?size:baseHeight)+this.config.subtreeOffset;},getEdge:function(node,type,s){var $C=function(a,b){return function(){return node.pos.add(new Complex(a,b));};};var dim=this.node;var w=node.getData('width');var h=node.getData('height');if(type=='begin'){if(dim.align=="center"){return this.dispatch(s,$C(0,h/2),$C(-w/2,0),$C(0,-h/2),$C(w/2,0));}else if(dim.align=="left"){return this.dispatch(s,$C(0,h),$C(0,0),$C(0,0),$C(w,0));}else if(dim.align=="right"){return this.dispatch(s,$C(0,0),$C(-w,0),$C(0,-h),$C(0,0));}else throw"align: not implemented";}else if(type=='end'){if(dim.align=="center"){return this.dispatch(s,$C(0,-h/2),$C(w/2,0),$C(0,h/2),$C(-w/2,0));}else if(dim.align=="left"){return this.dispatch(s,$C(0,0),$C(w,0),$C(0,h),$C(0,0));}else if(dim.align=="right"){return this.dispatch(s,$C(0,-h),$C(0,0),$C(0,0),$C(-w,0));}else throw"align: not implemented";}},getScaledTreePosition:function(node,scale){var dim=this.node;var w=node.getData('width');var h=node.getData('height');var s=(this.config.multitree&&('$orn'in node.data)&&node.data.$orn)||this.config.orientation;var $C=function(a,b){return function(){return node.pos.add(new Complex(a,b)).$scale(1-scale);};};if(dim.align=="left"){return this.dispatch(s,$C(0,h),$C(0,0),$C(0,0),$C(w,0));}else if(dim.align=="center"){return this.dispatch(s,$C(0,h / 2),$C(-w / 2,0),$C(0,-h / 2),$C(w / 2,0));}else if(dim.align=="right"){return this.dispatch(s,$C(0,0),$C(-w,0),$C(0,-h),$C(0,0));}else throw"align: not implemented";},treeFitsInCanvas:function(node,canvas,level){var csize=canvas.getSize();var s=(this.config.multitree&&('$orn'in node.data)&&node.data.$orn)||this.config.orientation;var size=this.dispatch(s,csize.width,csize.height);var baseSize=this.getTreeBaseSize(node,level,function(level,node){return level===0||!node.anySubnode();});return(baseSize<size);}});$jit.ST.Plot=new Class({Implements:Graph.Plot,plotSubtree:function(node,opt,scale,animating){var viz=this.viz,canvas=viz.canvas,config=viz.config;scale=Math.min(Math.max(0.001,scale),1);if(scale>=0){node.drawn=false;var ctx=canvas.getCtx();var diff=viz.geom.getScaledTreePosition(node,scale);ctx.translate(diff.x,diff.y);ctx.scale(scale,scale);}
this.plotTree(node,$.merge(opt,{'withLabels':true,'hideLabels':!!scale,'plotSubtree':function(n,ch){var root=config.multitree&&!('$orn'in node.data);var orns=root&&node.getData('orns');return!root||orns.indexOf(elem.getData('orn'))>-1;}}),animating);if(scale>=0)node.drawn=true;},positions:function(dimArray,fontHeight)
{var group=[];var isLastElem=false;var i;var newArray=[];var position=0;var currentState;for(i=0;i<dimArray.length;i++)
{currentState={type:'element',position:position,height:dimArray[i],font:fontHeight,filament:true};if(dimArray[i]<=fontHeight)
{if(isLastElem)
{group=[];}
group.push(currentState);isLastElem=false;}
else
{group.push(currentState);newArray.push({type:'group',val:group,groupHeight:0,groupPosition:group[0].position});group=[];isLastElem=true;}
position+=dimArray[i];}
if(group.length>0)
{newArray.push({type:'group',val:group,groupHeight:0,groupPosition:group[0].position});group=[];}
var figureHeight=position;for(i=0;i<newArray.length;i++)
{newArray[i]=this.pipelineGetHeight(newArray[i]);}
newArray=this.pipelineMoveBlocks(newArray,figureHeight,fontHeight);var ret=[];for(i=0;i<newArray.length;i++)
{group=newArray[i].val;for(var k=0;k<group.length;k++)
{ret.push(group[k]);}}
return ret;},pipelineGetHeight:function(group)
{var position=0;var between=3;var count=group.val.length;var fontHeight=group.val[0].font;var positionStart=group.val[0].position;if(count==1)
{group.groupHeight=group.val[0].font;group.val[0].filament=false;return group;}
if(count==2)
{group.groupHeight=fontHeight*2+between;group.val[1].position=positionStart+fontHeight+between;group.val[0].filament=false;group.val[1].filament=false;return group;}
var even=true;for(var i=0;i<group.val.length;i++)
{group.val[i].position=positionStart+position;even=i%2;position+=between;if(even)
{group.val[i].filament=false;position+=fontHeight;}
else
{group.val[i].filament=true;}}
group.groupHeight=(group.val[group.val.length-1].position-group.val[0].position)+fontHeight+between;return group;},pipelineMoveBlocks:function(block,figureheight,fontHeight)
{var offset;var rebuild;if(block.length<2)
{return block;}
var lastValue=block[block.length-1];var prelastValue;if((lastValue.groupPosition+lastValue.groupHeight)>figureheight)
{offset=(figureheight-lastValue.groupHeight)-lastValue.groupPosition;lastValue.groupPosition+=offset;for(var li=0;li<lastValue.val.length;li++)
{lastValue.val[li].position+=offset;}
prelastValue=block[block.length-2];if(prelastValue.groupPosition+fontHeight>lastValue.groupPosition)
{block[block.length-2]=this.pipelineMergeGroup(lastValue,prelastValue);block.pop();rebuild=true;}
if(block.length<3)
{return block;}}
for(var i=1;i<block.length;i++)
{if((block[i-1].groupPosition+block[i-1].groupHeight)>block[i].groupPosition)
{block[i-1]=this.pipelineMergeGroup(block[i],block[i-1]);block.splice(i,1);rebuild=true;}}
if(rebuild)
{block=this.pipelineMoveBlocks(block,figureheight,fontHeight);}
return block;},pipelineMergeGroup:function(lastValue,prelastValue)
{var newGroup;newGroup=prelastValue;newGroup.val=newGroup.val.concat(lastValue.val);newGroup=this.pipelineGetHeight(newGroup);newGroup.groupPosition=prelastValue.groupPosition;return newGroup;},getAlignedPos:function(pos,width,height){var nconfig=this.node;var square,orn;if(nconfig.align=="center"){square={x:pos.x-width / 2,y:pos.y-height / 2};}else if(nconfig.align=="left"){orn=this.config.orientation;if(orn=="bottom"||orn=="top"){square={x:pos.x-width / 2,y:pos.y};}else{square={x:pos.x,y:pos.y-height / 2};}}else if(nconfig.align=="right"){orn=this.config.orientation;if(orn=="bottom"||orn=="top"){square={x:pos.x-width / 2,y:pos.y-height};}else{square={x:pos.x-width,y:pos.y-height / 2};}}else throw"align: not implemented";return square;},getOrientation:function(adj){var config=this.config;var orn=config.orientation;if(config.multitree){var nodeFrom=adj.nodeFrom;var nodeTo=adj.nodeTo;orn=(('$orn'in nodeFrom.data)&&nodeFrom.data.$orn)||(('$orn'in nodeTo.data)&&nodeTo.data.$orn);}
return orn;}});$jit.ST.Label={};$jit.ST.Label.Native=new Class({Implements:Graph.Label.Native,renderLabel:function(canvas,node,controller){var ctx=canvas.getCtx();var coord=node.pos.getc(true);ctx.fillText(node.name,coord.x,coord.y);}});$jit.ST.Label.DOM=new Class({Implements:Graph.Label.DOM,placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),config=this.viz.config,dim=config.Node,canvas=this.viz.canvas,w=node.getData('width'),h=node.getData('height'),radius=canvas.getSize(),labelPos,orn;var ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,posx=pos.x*sx+ox,posy=pos.y*sy+oy;if(dim.align=="center"){labelPos={x:Math.round(posx-w / 2+radius.width/2),y:Math.round(posy-h / 2+radius.height/2)};}else if(dim.align=="left"){orn=config.orientation;if(orn=="bottom"||orn=="top"){labelPos={x:Math.round(posx-w / 2+radius.width/2),y:Math.round(posy+radius.height/2)};}else{labelPos={x:Math.round(posx+radius.width/2),y:Math.round(posy-h / 2+radius.height/2)};}}else if(dim.align=="right"){orn=config.orientation;if(orn=="bottom"||orn=="top"){labelPos={x:Math.round(posx-w / 2+radius.width/2),y:Math.round(posy-h+radius.height/2)};}else{labelPos={x:Math.round(posx-w+radius.width/2),y:Math.round(posy-h / 2+radius.height/2)};}}else throw"align: not implemented";var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.display=this.fitsInCanvas(labelPos,canvas)?'':'none';controller.onPlaceLabel(tag,node);}});$jit.ST.Label.SVG=new Class({Implements:[$jit.ST.Label.DOM,Graph.Label.SVG],initialize:function(viz){this.viz=viz;}});$jit.ST.Label.HTML=new Class({Implements:[$jit.ST.Label.DOM,Graph.Label.HTML],initialize:function(viz){this.viz=viz;}});$jit.ST.Plot.NodeTypes=new Class({'none':{'render':$.empty,'contains':$.lambda(false)},'circle':{'render':function(node,canvas){var dim=node.getData('dim'),pos=this.getAlignedPos(node.pos.getc(true),dim,dim),dim2=dim/2;this.nodeHelper.circle.render('fill',{x:pos.x+dim2,y:pos.y+dim2},dim2,canvas);},'contains':function(node,pos){var dim=node.getData('dim'),npos=this.getAlignedPos(node.pos.getc(true),dim,dim),dim2=dim/2;this.nodeHelper.circle.contains({x:npos.x+dim2,y:npos.y+dim2},dim2);}},'square':{'render':function(node,canvas){var dim=node.getData('dim'),dim2=dim/2,pos=this.getAlignedPos(node.pos.getc(true),dim,dim);this.nodeHelper.square.render('fill',{x:pos.x+dim2,y:pos.y+dim2},dim2,canvas);},'contains':function(node,pos){var dim=node.getData('dim'),npos=this.getAlignedPos(node.pos.getc(true),dim,dim),dim2=dim/2;this.nodeHelper.square.contains({x:npos.x+dim2,y:npos.y+dim2},dim2);}},'ellipse':{'render':function(node,canvas){var width=node.getData('width'),height=node.getData('height'),pos=this.getAlignedPos(node.pos.getc(true),width,height);this.nodeHelper.ellipse.render('fill',{x:pos.x+width/2,y:pos.y+height/2},width,height,canvas);},'contains':function(node,pos){var width=node.getData('width'),height=node.getData('height'),npos=this.getAlignedPos(node.pos.getc(true),width,height);this.nodeHelper.ellipse.contains({x:npos.x+width/2,y:npos.y+height/2},width,height,canvas);}},'rectangle':{'render':function(node,canvas){var width=node.getData('width'),height=node.getData('height'),pos=this.getAlignedPos(node.pos.getc(true),width,height);this.nodeHelper.rectangle.render('fill',{x:pos.x+width/2,y:pos.y+height/2},width,height,canvas);},'contains':function(node,pos){var width=node.getData('width'),height=node.getData('height'),npos=this.getAlignedPos(node.pos.getc(true),width,height);this.nodeHelper.rectangle.contains({x:npos.x+width/2,y:npos.y+height/2},width,height,canvas);}}});$jit.ST.Plot.EdgeTypes=new Class({'none':$.empty,'line':{'render':function(adj,canvas){var orn=this.getOrientation(adj),nodeFrom=adj.nodeFrom,nodeTo=adj.nodeTo,rel=nodeFrom._depth<nodeTo._depth,from=this.viz.geom.getEdge(rel?nodeFrom:nodeTo,'begin',orn),to=this.viz.geom.getEdge(rel?nodeTo:nodeFrom,'end',orn);this.edgeHelper.line.render(from,to,canvas);},'contains':function(adj,pos){var orn=this.getOrientation(adj),nodeFrom=adj.nodeFrom,nodeTo=adj.nodeTo,rel=nodeFrom._depth<nodeTo._depth,from=this.viz.geom.getEdge(rel?nodeFrom:nodeTo,'begin',orn),to=this.viz.geom.getEdge(rel?nodeTo:nodeFrom,'end',orn);return this.edgeHelper.line.contains(from,to,pos,this.edge.epsilon);}},'arrow':{'render':function(adj,canvas){var orn=this.getOrientation(adj),node=adj.nodeFrom,child=adj.nodeTo,dim=adj.getData('dim'),from=this.viz.geom.getEdge(node,'begin',orn),to=this.viz.geom.getEdge(child,'end',orn),direction=adj.data.$direction,inv=(direction&&direction.length>1&&direction[0]!=node.id);this.edgeHelper.arrow.render(from,to,dim,inv,canvas);},'contains':function(adj,pos){var orn=this.getOrientation(adj),nodeFrom=adj.nodeFrom,nodeTo=adj.nodeTo,rel=nodeFrom._depth<nodeTo._depth,from=this.viz.geom.getEdge(rel?nodeFrom:nodeTo,'begin',orn),to=this.viz.geom.getEdge(rel?nodeTo:nodeFrom,'end',orn);return this.edgeHelper.arrow.contains(from,to,pos,this.edge.epsilon);}},'quadratic:begin':{'render':function(adj,canvas){var orn=this.getOrientation(adj);var nodeFrom=adj.nodeFrom,nodeTo=adj.nodeTo,rel=nodeFrom._depth<nodeTo._depth,begin=this.viz.geom.getEdge(rel?nodeFrom:nodeTo,'begin',orn),end=this.viz.geom.getEdge(rel?nodeTo:nodeFrom,'end',orn),dim=adj.getData('dim'),ctx=canvas.getCtx();ctx.beginPath();ctx.moveTo(begin.x,begin.y);switch(orn){case"left":ctx.quadraticCurveTo(begin.x+dim,begin.y,end.x,end.y);break;case"right":ctx.quadraticCurveTo(begin.x-dim,begin.y,end.x,end.y);break;case"top":ctx.quadraticCurveTo(begin.x,begin.y+dim,end.x,end.y);break;case"bottom":ctx.quadraticCurveTo(begin.x,begin.y-dim,end.x,end.y);break;}
ctx.stroke();}},'quadratic:end':{'render':function(adj,canvas){var orn=this.getOrientation(adj);var nodeFrom=adj.nodeFrom,nodeTo=adj.nodeTo,rel=nodeFrom._depth<nodeTo._depth,begin=this.viz.geom.getEdge(rel?nodeFrom:nodeTo,'begin',orn),end=this.viz.geom.getEdge(rel?nodeTo:nodeFrom,'end',orn),dim=adj.getData('dim'),ctx=canvas.getCtx();ctx.beginPath();ctx.moveTo(begin.x,begin.y);switch(orn){case"left":ctx.quadraticCurveTo(end.x-dim,end.y,end.x,end.y);break;case"right":ctx.quadraticCurveTo(end.x+dim,end.y,end.x,end.y);break;case"top":ctx.quadraticCurveTo(end.x,end.y-dim,end.x,end.y);break;case"bottom":ctx.quadraticCurveTo(end.x,end.y+dim,end.x,end.y);break;}
ctx.stroke();}},'bezier':{'render':function(adj,canvas){var orn=this.getOrientation(adj),nodeFrom=adj.nodeFrom,nodeTo=adj.nodeTo,rel=nodeFrom._depth<nodeTo._depth,begin=this.viz.geom.getEdge(rel?nodeFrom:nodeTo,'begin',orn),end=this.viz.geom.getEdge(rel?nodeTo:nodeFrom,'end',orn),dim=adj.getData('dim'),ctx=canvas.getCtx();ctx.beginPath();ctx.moveTo(begin.x,begin.y);switch(orn){case"left":ctx.bezierCurveTo(begin.x+dim,begin.y,end.x-dim,end.y,end.x,end.y);break;case"right":ctx.bezierCurveTo(begin.x-dim,begin.y,end.x+dim,end.y,end.x,end.y);break;case"top":ctx.bezierCurveTo(begin.x,begin.y+dim,end.x,end.y-dim,end.x,end.y);break;case"bottom":ctx.bezierCurveTo(begin.x,begin.y-dim,end.x,end.y+dim,end.x,end.y);break;}
ctx.stroke();}}});Options.LineChart={$extend:true,animate:false,labelOffset:3,type:'basic',dataPointSize:10,Tips:{enable:false,onShow:$.empty,onHide:$.empty},Ticks:{enable:false,segments:4,color:'#000000'},Events:{enable:false,onClick:$.empty},selectOnHover:true,showAggregates:true,showLabels:true,filterOnClick:false,restoreOnRightClick:false};$jit.ST.Plot.NodeTypes.implement({'linechart-basic':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x+width/2,y=algnPos.y,stringArray=node.getData('stringArray'),lastNode=node.getData('lastNode'),dimArray=node.getData('dimArray'),valArray=node.getData('valueArray'),colorArray=node.getData('colorArray'),colorLength=colorArray.length,config=node.getData('config'),gradient=node.getData('gradient'),showLabels=config.showLabels,aggregates=config.showAggregates,label=config.Label,prev=node.getData('prev'),dataPointSize=config.dataPointSize;var ctx=canvas.getCtx(),border=node.getData('border');if(colorArray&&dimArray&&stringArray){for(var i=0,l=dimArray.length,acumLeft=0,acumRight=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];ctx.lineWidth=4;ctx.lineCap="round";if(!lastNode){ctx.save();ctx.beginPath();ctx.moveTo(x,y-dimArray[i][0]);ctx.lineTo(x+width,y-dimArray[i][1]);ctx.stroke();ctx.restore();}
ctx.fillRect(x-(dataPointSize/2),y-dimArray[i][0]-(dataPointSize/2),dataPointSize,dataPointSize);}
if(label.type=='Native'&&showLabels){ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(node.name,x,y+label.size+config.labelOffset);}}},'contains':function(node,mpos){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),config=node.getData('config'),dataPointSize=config.dataPointSize,dataPointMidPoint=dataPointSize/2,algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x+width/2,y=algnPos.y,dimArray=node.getData('dimArray');if(mpos.x<x-dataPointMidPoint||mpos.x>x+dataPointMidPoint){return false;}
for(var i=0,l=dimArray.length;i<l;i++){var dimi=dimArray[i];var url=Url.decode(node.getData('linkArray')[i]);if(mpos.x>=x-dataPointMidPoint&&mpos.x<=x+dataPointMidPoint&&mpos.y>=y-dimi[0]-dataPointMidPoint&&mpos.y<=y-dimi[0]+dataPointMidPoint){var valArrayCur=node.getData('valArrayCur');var results=array_match(valArrayCur[i],valArrayCur);var matches=results[0];var indexValues=results[1];if(matches>1){var names=new Array(),values=new Array(),percentages=new Array(),linksArr=new Array();for(var j=0,il=indexValues.length;j<il;j++){names[j]=node.getData('stringArray')[indexValues[j]];values[j]=valArrayCur[indexValues[j]];percentages[j]=((valArrayCur[indexValues[j]]/node.getData('groupTotalValue'))*100).toFixed(1);linksArr[j]=Url.decode(node.getData('linkArray')[j]);}
return{'name':names,'color':node.getData('colorArray')[i],'value':values,'percentage':percentages,'link':false,'collision':true};}
else{return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i][0],'percentage':((node.getData('valueArray')[i][0]/node.getData('groupTotalValue'))*100).toFixed(1),'link':url,'collision':false};}}}
return false;}}});$jit.LineChart=new Class({st:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(opt){this.controller=this.config=$.merge(Options("Canvas","Margin","Label","LineChart"),{Label:{type:'Native'}},opt);var showLabels=this.config.showLabels,typeLabels=$.type(showLabels),showAggregates=this.config.showAggregates,typeAggregates=$.type(showAggregates);this.config.showLabels=typeLabels=='function'?showLabels:$.lambda(showLabels);this.config.showAggregates=typeAggregates=='function'?showAggregates:$.lambda(showAggregates);Options.Fx.clearCanvas=false;this.initializeViz();},initializeViz:function(){var config=this.config,that=this,nodeType=config.type.split(":")[0],nodeLabels={};var st=new $jit.ST({injectInto:config.injectInto,orientation:"bottom",backgroundColor:config.backgroundColor,renderBackground:config.renderBackground,levelDistance:0,siblingOffset:0,subtreeOffset:0,withLabels:config.Label.type!='Native',useCanvas:config.useCanvas,Label:{type:config.Label.type},Node:{overridable:true,type:'linechart-'+nodeType,align:'left',width:1,height:1},Edge:{type:'none'},Tips:{enable:config.Tips.enable,type:'Native',force:true,onShow:function(tip,node,contains){var elem=contains;config.Tips.onShow(tip,elem,node);}},Events:{enable:true,type:'Native',onClick:function(node,eventInfo,evt){if(!config.filterOnClick&&!config.Events.enable)return;var elem=eventInfo.getContains();if(elem)config.filterOnClick&&that.filter(elem.name);config.Events.enable&&config.Events.onClick(elem,eventInfo,evt);},onRightClick:function(node,eventInfo,evt){if(!config.restoreOnRightClick)return;that.restore();},onMouseMove:function(node,eventInfo,evt){if(!config.selectOnHover)return;if(node){var elem=eventInfo.getContains();that.select(node.id,elem.name,elem.index);}else{that.select(false,false,false);}}},onCreateLabel:function(domElement,node){var labelConf=config.Label,valueArray=node.getData('valueArray'),acumLeft=$.reduce(valueArray,function(x,y){return x+y[0];},0),acumRight=$.reduce(valueArray,function(x,y){return x+y[1];},0);if(node.getData('prev')){var nlbs={wrapper:document.createElement('div'),aggregate:document.createElement('div'),label:document.createElement('div')};var wrapper=nlbs.wrapper,label=nlbs.label,aggregate=nlbs.aggregate,wrapperStyle=wrapper.style,labelStyle=label.style,aggregateStyle=aggregate.style;nodeLabels[node.id]=nlbs;wrapper.appendChild(label);wrapper.appendChild(aggregate);if(!config.showLabels(node.name,acumLeft,acumRight,node)){label.style.display='none';}
if(!config.showAggregates(node.name,acumLeft,acumRight,node)){aggregate.style.display='none';}
wrapperStyle.position='relative';wrapperStyle.overflow='visible';wrapperStyle.fontSize=labelConf.size+'px';wrapperStyle.fontFamily=labelConf.family;wrapperStyle.color=labelConf.color;wrapperStyle.textAlign='center';aggregateStyle.position=labelStyle.position='absolute';domElement.style.width=node.getData('width')+'px';domElement.style.height=node.getData('height')+'px';label.innerHTML=node.name;domElement.appendChild(wrapper);}},onPlaceLabel:function(domElement,node){if(!node.getData('prev'))return;var labels=nodeLabels[node.id],wrapperStyle=labels.wrapper.style,labelStyle=labels.label.style,aggregateStyle=labels.aggregate.style,width=node.getData('width'),height=node.getData('height'),dimArray=node.getData('dimArray'),valArray=node.getData('valueArray'),acumLeft=$.reduce(valArray,function(x,y){return x+y[0];},0),acumRight=$.reduce(valArray,function(x,y){return x+y[1];},0),font=parseInt(wrapperStyle.fontSize,10),domStyle=domElement.style;if(dimArray&&valArray){if(config.showLabels(node.name,acumLeft,acumRight,node)){labelStyle.display='';}else{labelStyle.display='none';}
if(config.showAggregates(node.name,acumLeft,acumRight,node)){aggregateStyle.display='';}else{aggregateStyle.display='none';}
wrapperStyle.width=aggregateStyle.width=labelStyle.width=domElement.style.width=width+'px';aggregateStyle.left=labelStyle.left=-width/2+'px';for(var i=0,l=valArray.length,acum=0,leftAcum=0;i<l;i++){if(dimArray[i][0]>0){acum+=valArray[i][0];leftAcum+=dimArray[i][0];}}
aggregateStyle.top=(-font-config.labelOffset)+'px';labelStyle.top=(config.labelOffset+leftAcum)+'px';domElement.style.top=parseInt(domElement.style.top,10)-leftAcum+'px';domElement.style.height=wrapperStyle.height=leftAcum+'px';labels.aggregate.innerHTML=acum;}}});var size=st.canvas.getSize(),margin=config.Margin;st.config.offsetY=-size.height/2+margin.bottom
+(config.showLabels&&(config.labelOffset+config.Label.size));st.config.offsetX=(margin.right-margin.left-config.labelOffset-config.Label.size)/2;this.st=st;this.canvas=this.st.canvas;},renderTitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,label=config.Label,title=config.Title;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.textBaseline='top';ctx.font=label.style+' bold '+' '+title.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(title.text,-size.width/2+margin.left,-size.height/2+margin.top);}},renderTicks:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,ticks=config.Ticks,title=config.Title,subtitle=config.Subtitle,label=config.Label,maxValue=this.maxValue,maxTickValue=Math.ceil(maxValue*.1)*10;if(maxTickValue==maxValue){var length=maxTickValue.toString().length;maxTickValue=maxTickValue+parseInt(pad(1,length));}
labelValue=0,labelIncrement=maxTickValue/ticks.segments,ctx=canvas.getCtx();ctx.strokeStyle=ticks.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textAlign='center';ctx.textBaseline='middle';idLabel=canvas.id+"-label";labelDim=100;container=document.getElementById(idLabel);var axis=(size.height/2)-(margin.bottom+config.labelOffset+label.size+(subtitle.text?subtitle.size+subtitle.offset:0)),htmlOrigin=size.height-(margin.bottom+config.labelOffset+label.size+(subtitle.text?subtitle.size+subtitle.offset:0)),grid=-size.height+(margin.bottom+config.labelOffset+label.size+margin.top+(title.text?title.size+title.offset:0)+(subtitle.text?subtitle.size+subtitle.offset:0)),segmentLength=grid/ticks.segments;ctx.fillStyle=ticks.color;ctx.fillRect(-(size.width/2)+margin.left+config.labelOffset+label.size-1,-(size.height/2)+margin.top+(title.text?title.size+title.offset:0),1,size.height-margin.top-margin.bottom-label.size-config.labelOffset-(title.text?title.size+title.offset:0)-(subtitle.text?subtitle.size+subtitle.offset:0));while(axis>=grid){ctx.save();ctx.translate(-(size.width/2)+margin.left,Math.round(axis));ctx.rotate(Math.PI / 2);ctx.fillStyle=label.color;if(config.showLabels){if(label.type=='Native'){ctx.fillText(labelValue,0,0);}else{labelDiv=document.createElement('div');labelDiv.innerHTML=labelValue;labelDiv.className="rotatedLabel";labelDiv.style.top=(htmlOrigin-(labelDim/2))+"px";labelDiv.style.left=margin.left+"px";labelDiv.style.width=labelDim+"px";labelDiv.style.height=labelDim+"px";labelDiv.style.textAlign="center";labelDiv.style.verticalAlign="middle";labelDiv.style.position="absolute";container.appendChild(labelDiv);}}
ctx.restore();ctx.fillStyle=ticks.color;ctx.fillRect(-(size.width/2)+margin.left+config.labelOffset+label.size,Math.round(axis),size.width-margin.right-margin.left-config.labelOffset-label.size,1);htmlOrigin+=segmentLength;axis+=segmentLength;labelValue+=labelIncrement;}},renderBackground:function(){var canvas=this.canvas,config=this.config,backgroundColor=config.backgroundColor,size=canvas.getSize(),ctx=canvas.getCtx();ctx.fillStyle=backgroundColor;ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);},clear:function(){var canvas=this.canvas;var ctx=canvas.getCtx(),size=canvas.getSize();ctx.fillStyle="rgba(255,255,255,0)";ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);ctx.clearRect(-size.width/2,-size.height/2,size.width,size.height);},resizeGraph:function(json,width){var canvas=this.canvas,size=canvas.getSize(),orgHeight=size.height;canvas.resize(width,orgHeight);if(typeof FlashCanvas=="undefined"){canvas.clear();}else{this.clear();}
this.loadJSON(json);},loadJSON:function(json){var prefix=$.time(),ch=[],st=this.st,name=$.splat(json.label),color=$.splat(json.color||this.colors),config=this.config,ticks=config.Ticks,renderBackground=config.renderBackground,gradient=!!config.type.split(":")[1],animate=config.animate,title=config.Title,groupTotalValue=0;var valArrayAll=new Array();for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];var valArray=$.splat(val.values);for(var j=0,len=valArray.length;j<len;j++){valArrayAll.push(parseInt(valArray[j]));}
groupTotalValue+=parseInt(valArray.sum());}
this.maxValue=Math.max.apply(null,valArrayAll);for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i],prev=values[i-1];var next=(i+1<l)?values[i+1]:0;var valLeft=$.splat(values[i].values);var valRight=(i+1<l)?$.splat(values[i+1].values):0;var valArray=$.zip(valLeft,valRight);var valArrayCur=$.splat(values[i].values);var linkArray=$.splat(values[i].links);var acumLeft=0,acumRight=0;var lastNode=(l-1==i)?true:false;ch.push({'id':prefix+val.label,'name':val.label,'data':{'value':valArray,'$valueArray':valArray,'$valArrayCur':valArrayCur,'$colorArray':color,'$linkArray':linkArray,'$stringArray':name,'$next':next?next.label:false,'$prev':prev?prev.label:false,'$config':config,'$lastNode':lastNode,'$groupTotalValue':groupTotalValue,'$gradient':gradient},'children':[]});}
var root={'id':prefix+'$root','name':'','data':{'$type':'none','$width':1,'$height':1},'children':ch};st.loadJSON(root);this.normalizeDims();if(renderBackground){this.renderBackground();}
if(!animate&&ticks.enable){this.renderTicks();}
if(title.text){this.renderTitle();}
st.compute();st.select(st.root);if(animate){st.fx.animate({modes:['node-property:height:dimArray'],duration:1500});}},updateJSON:function(json,onComplete){if(this.busy)return;this.busy=true;var st=this.st,graph=st.graph,labels=json.label&&$.splat(json.label),values=json.values,animate=this.config.animate,that=this;$.each(values,function(v){var n=graph.getByName(v.label);if(n){v.values=$.splat(v.values);var stringArray=n.getData('stringArray'),valArray=n.getData('valueArray');$.each(valArray,function(a,i){a[0]=v.values[i];if(labels)stringArray[i]=labels[i];});n.setData('valueArray',valArray);var prev=n.getData('prev'),next=n.getData('next'),nextNode=graph.getByName(next);if(prev){var p=graph.getByName(prev);if(p){var valArray=p.getData('valueArray');$.each(valArray,function(a,i){a[1]=v.values[i];});}}
if(!nextNode){var valArray=n.getData('valueArray');$.each(valArray,function(a,i){a[1]=v.values[i];});}}});this.normalizeDims();st.compute();st.select(st.root);if(animate){st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}},filter:function(){if(this.busy)return;this.busy=true;if(this.config.Tips.enable)this.st.tips.hide();this.select(false,false,false);var args=Array.prototype.slice.call(arguments);var rt=this.st.graph.getNode(this.st.root);var that=this;rt.eachAdjacency(function(adj){var n=adj.nodeTo,dimArray=n.getData('dimArray'),stringArray=n.getData('stringArray');n.setData('dimArray',$.map(dimArray,function(d,i){return($.indexOf(args,stringArray[i])>-1)?d:[0,0];}),'end');});this.st.fx.animate({modes:['node-property:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});},restore:function(){if(this.busy)return;this.busy=true;if(this.config.Tips.enable)this.st.tips.hide();this.select(false,false,false);this.normalizeDims();var that=this;this.st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});},select:function(id,name,index){if(!this.config.selectOnHover)return;var s=this.selected;if(s.id!=id||s.name!=name||s.index!=index){s.id=id;s.name=name;s.index=index;this.st.graph.eachNode(function(n){n.setData('border',false);});if(id){var n=this.st.graph.getNode(id);n.setData('border',s);var link=index===0?'prev':'next';link=n.getData(link);if(link){n=this.st.graph.getByName(link);if(n){n.setData('border',{name:name,index:1-index});}}}
this.st.plot();}},getLegend:function(){var legend=new Array();var name=new Array();var color=new Array();var n;this.st.graph.getNode(this.st.root).eachAdjacency(function(adj){n=adj.nodeTo;});var colors=n.getData('colorArray'),len=colors.length;$.each(n.getData('stringArray'),function(s,i){color[i]=colors[i%len];name[i]=s;});legend['name']=name;legend['color']=color;return legend;},normalizeDims:function(){var root=this.st.graph.getNode(this.st.root),l=0;root.eachAdjacency(function(){l++;});var maxValue=this.maxValue||1,size=this.st.canvas.getSize(),config=this.config,margin=config.Margin,labelOffset=config.labelOffset+config.Label.size,fixedDim=(size.width-(margin.left+margin.right+labelOffset))/(l-1),animate=config.animate,ticks=config.Ticks,height=size.height-(margin.top+margin.bottom)-(config.showAggregates&&labelOffset)
-(config.showLabels&&labelOffset);var maxTickValue=Math.ceil(maxValue*.1)*10;if(maxTickValue==maxValue){var length=maxTickValue.toString().length;maxTickValue=maxTickValue+parseInt(pad(1,length));}
this.st.graph.eachNode(function(n){var acumLeft=0,acumRight=0,animateValue=[];$.each(n.getData('valueArray'),function(v){acumLeft+=+v[0];acumRight+=+v[1];animateValue.push([0,0]);});var acum=acumRight>acumLeft?acumRight:acumLeft;n.setData('width',fixedDim);if(animate){n.setData('height',acum*height / maxValue,'end');n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return[n[0]*height / maxValue,n[1]*height / maxValue];}),'end');var dimArray=n.getData('dimArray');if(!dimArray){n.setData('dimArray',animateValue);}}else{if(ticks.enable){n.setData('height',acum*height / maxValue);n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return[n[0]*height / maxTickValue,n[1]*height / maxTickValue];}));}else{n.setData('height',acum*height / maxValue);n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return[n[0]*height / maxValue,n[1]*height / maxValue];}));}}});}});$jit.ST.Plot.NodeTypes.implement({'areachart-stacked':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,stringArray=node.getData('stringArray'),dimArray=node.getData('dimArray'),valArray=node.getData('valueArray'),valLeft=$.reduce(valArray,function(x,y){return x+y[0];},0),valRight=$.reduce(valArray,function(x,y){return x+y[1];},0),colorArray=node.getData('colorArray'),colorLength=colorArray.length,config=node.getData('config'),gradient=node.getData('gradient'),showLabels=config.showLabels,aggregates=config.showAggregates,label=config.Label,prev=node.getData('prev');var ctx=canvas.getCtx(),border=node.getData('border');if(colorArray&&dimArray&&stringArray){for(var i=0,l=dimArray.length,acumLeft=0,acumRight=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];ctx.save();if(gradient&&(dimArray[i][0]>0||dimArray[i][1]>0)){var h1=acumLeft+dimArray[i][0],h2=acumRight+dimArray[i][1],alpha=Math.atan((h2-h1)/ width),delta=55;var linear=ctx.createLinearGradient(x+width/2,y-(h1+h2)/2,x+width/2+delta*Math.sin(alpha),y-(h1+h2)/2+delta*Math.cos(alpha));var color=$.rgbToHex($.map($.hexToRgb(colorArray[i%colorLength].slice(1)),function(v){return(v*0.85)>>0;}));linear.addColorStop(0,colorArray[i%colorLength]);linear.addColorStop(1,color);ctx.fillStyle=linear;}
ctx.beginPath();ctx.moveTo(x,y-acumLeft);ctx.lineTo(x+width,y-acumRight);ctx.lineTo(x+width,y-acumRight-dimArray[i][1]);ctx.lineTo(x,y-acumLeft-dimArray[i][0]);ctx.lineTo(x,y-acumLeft);ctx.fill();ctx.restore();if(border){var strong=border.name==stringArray[i];var perc=strong?0.7:0.8;var color=$.rgbToHex($.map($.hexToRgb(colorArray[i%colorLength].slice(1)),function(v){return(v*perc)>>0;}));ctx.strokeStyle=color;ctx.lineWidth=strong?4:1;ctx.save();ctx.beginPath();if(border.index===0){ctx.moveTo(x,y-acumLeft);ctx.lineTo(x,y-acumLeft-dimArray[i][0]);}else{ctx.moveTo(x+width,y-acumRight);ctx.lineTo(x+width,y-acumRight-dimArray[i][1]);}
ctx.stroke();ctx.restore();}
acumLeft+=(dimArray[i][0]||0);acumRight+=(dimArray[i][1]||0);if(dimArray[i][0]>0)
valAcum+=(valArray[i][0]||0);}
if(prev&&label.type=='Native'){ctx.save();ctx.beginPath();ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textAlign='center';ctx.textBaseline='middle';if(aggregates(node.name,valLeft,valRight,node)){ctx.fillText(valAcum,x,y-acumLeft-config.labelOffset-label.size/2,width);}
if(showLabels(node.name,valLeft,valRight,node)){ctx.fillText(node.name,x,y+label.size/2+config.labelOffset);}
ctx.restore();}}},'contains':function(node,mpos){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),rx=mpos.x-x;if(mpos.x<x||mpos.x>x+width||mpos.y>y||mpos.y<y-height){return false;}
for(var i=0,l=dimArray.length,lAcum=y,rAcum=y;i<l;i++){var dimi=dimArray[i];lAcum-=dimi[0];rAcum-=dimi[1];var intersec=lAcum+(rAcum-lAcum)*rx / width;if(mpos.y>=intersec){var index=+(rx>width/2);return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i][index],'index':index};}}
return false;}}});$jit.AreaChart=new Class({st:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(opt){this.controller=this.config=$.merge(Options("Canvas","Margin","Label","AreaChart"),{Label:{type:'Native'}},opt);var showLabels=this.config.showLabels,typeLabels=$.type(showLabels),showAggregates=this.config.showAggregates,typeAggregates=$.type(showAggregates);this.config.showLabels=typeLabels=='function'?showLabels:$.lambda(showLabels);this.config.showAggregates=typeAggregates=='function'?showAggregates:$.lambda(showAggregates);this.initializeViz();},initializeViz:function(){var config=this.config,that=this,nodeType=config.type.split(":")[0],nodeLabels={};var st=new $jit.ST({injectInto:config.injectInto,orientation:"bottom",levelDistance:0,siblingOffset:0,subtreeOffset:0,withLabels:config.Label.type!='Native',useCanvas:config.useCanvas,Label:{type:config.Label.type},Node:{overridable:true,type:'areachart-'+nodeType,align:'left',width:1,height:1},Edge:{type:'none'},Tips:{enable:config.Tips.enable,type:'Native',force:true,onShow:function(tip,node,contains){var elem=contains;config.Tips.onShow(tip,elem,node);}},Events:{enable:true,type:'Native',onClick:function(node,eventInfo,evt){if(!config.filterOnClick&&!config.Events.enable)return;var elem=eventInfo.getContains();if(elem)config.filterOnClick&&that.filter(elem.name);config.Events.enable&&config.Events.onClick(elem,eventInfo,evt);},onRightClick:function(node,eventInfo,evt){if(!config.restoreOnRightClick)return;that.restore();},onMouseMove:function(node,eventInfo,evt){if(!config.selectOnHover)return;if(node){var elem=eventInfo.getContains();that.select(node.id,elem.name,elem.index);}else{that.select(false,false,false);}}},onCreateLabel:function(domElement,node){var labelConf=config.Label,valueArray=node.getData('valueArray'),acumLeft=$.reduce(valueArray,function(x,y){return x+y[0];},0),acumRight=$.reduce(valueArray,function(x,y){return x+y[1];},0);if(node.getData('prev')){var nlbs={wrapper:document.createElement('div'),aggregate:document.createElement('div'),label:document.createElement('div')};var wrapper=nlbs.wrapper,label=nlbs.label,aggregate=nlbs.aggregate,wrapperStyle=wrapper.style,labelStyle=label.style,aggregateStyle=aggregate.style;nodeLabels[node.id]=nlbs;wrapper.appendChild(label);wrapper.appendChild(aggregate);if(!config.showLabels(node.name,acumLeft,acumRight,node)){label.style.display='none';}
if(!config.showAggregates(node.name,acumLeft,acumRight,node)){aggregate.style.display='none';}
wrapperStyle.position='relative';wrapperStyle.overflow='visible';wrapperStyle.fontSize=labelConf.size+'px';wrapperStyle.fontFamily=labelConf.family;wrapperStyle.color=labelConf.color;wrapperStyle.textAlign='center';aggregateStyle.position=labelStyle.position='absolute';domElement.style.width=node.getData('width')+'px';domElement.style.height=node.getData('height')+'px';label.innerHTML=node.name;domElement.appendChild(wrapper);}},onPlaceLabel:function(domElement,node){if(!node.getData('prev'))return;var labels=nodeLabels[node.id],wrapperStyle=labels.wrapper.style,labelStyle=labels.label.style,aggregateStyle=labels.aggregate.style,width=node.getData('width'),height=node.getData('height'),dimArray=node.getData('dimArray'),valArray=node.getData('valueArray'),acumLeft=$.reduce(valArray,function(x,y){return x+y[0];},0),acumRight=$.reduce(valArray,function(x,y){return x+y[1];},0),font=parseInt(wrapperStyle.fontSize,10),domStyle=domElement.style;if(dimArray&&valArray){if(config.showLabels(node.name,acumLeft,acumRight,node)){labelStyle.display='';}else{labelStyle.display='none';}
if(config.showAggregates(node.name,acumLeft,acumRight,node)){aggregateStyle.display='';}else{aggregateStyle.display='none';}
wrapperStyle.width=aggregateStyle.width=labelStyle.width=domElement.style.width=width+'px';aggregateStyle.left=labelStyle.left=-width/2+'px';for(var i=0,l=valArray.length,acum=0,leftAcum=0;i<l;i++){if(dimArray[i][0]>0){acum+=valArray[i][0];leftAcum+=dimArray[i][0];}}
aggregateStyle.top=(-font-config.labelOffset)+'px';labelStyle.top=(config.labelOffset+leftAcum)+'px';domElement.style.top=parseInt(domElement.style.top,10)-leftAcum+'px';domElement.style.height=wrapperStyle.height=leftAcum+'px';labels.aggregate.innerHTML=acum;}}});var size=st.canvas.getSize(),margin=config.Margin;st.config.offsetY=-size.height/2+margin.bottom
+(config.showLabels&&(config.labelOffset+config.Label.size));st.config.offsetX=(margin.right-margin.left)/2;this.st=st;this.canvas=this.st.canvas;},loadJSON:function(json){var prefix=$.time(),ch=[],st=this.st,name=$.splat(json.label),color=$.splat(json.color||this.colors),config=this.config,gradient=!!config.type.split(":")[1],animate=config.animate;for(var i=0,values=json.values,l=values.length;i<l-1;i++){var val=values[i],prev=values[i-1],next=values[i+1];var valLeft=$.splat(values[i].values),valRight=$.splat(values[i+1].values);var valArray=$.zip(valLeft,valRight);var acumLeft=0,acumRight=0;ch.push({'id':prefix+val.label,'name':val.label,'data':{'value':valArray,'$valueArray':valArray,'$colorArray':color,'$stringArray':name,'$next':next.label,'$prev':prev?prev.label:false,'$config':config,'$gradient':gradient},'children':[]});}
var root={'id':prefix+'$root','name':'','data':{'$type':'none','$width':1,'$height':1},'children':ch};st.loadJSON(root);this.normalizeDims();st.compute();st.select(st.root);if(animate){st.fx.animate({modes:['node-property:height:dimArray'],duration:1500});}},updateJSON:function(json,onComplete){if(this.busy)return;this.busy=true;var st=this.st,graph=st.graph,labels=json.label&&$.splat(json.label),values=json.values,animate=this.config.animate,that=this;$.each(values,function(v){var n=graph.getByName(v.label);if(n){v.values=$.splat(v.values);var stringArray=n.getData('stringArray'),valArray=n.getData('valueArray');$.each(valArray,function(a,i){a[0]=v.values[i];if(labels)stringArray[i]=labels[i];});n.setData('valueArray',valArray);var prev=n.getData('prev'),next=n.getData('next'),nextNode=graph.getByName(next);if(prev){var p=graph.getByName(prev);if(p){var valArray=p.getData('valueArray');$.each(valArray,function(a,i){a[1]=v.values[i];});}}
if(!nextNode){var valArray=n.getData('valueArray');$.each(valArray,function(a,i){a[1]=v.values[i];});}}});this.normalizeDims();st.compute();st.select(st.root);if(animate){st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}},filter:function(){if(this.busy)return;this.busy=true;if(this.config.Tips.enable)this.st.tips.hide();this.select(false,false,false);var args=Array.prototype.slice.call(arguments);var rt=this.st.graph.getNode(this.st.root);var that=this;rt.eachAdjacency(function(adj){var n=adj.nodeTo,dimArray=n.getData('dimArray'),stringArray=n.getData('stringArray');n.setData('dimArray',$.map(dimArray,function(d,i){return($.indexOf(args,stringArray[i])>-1)?d:[0,0];}),'end');});this.st.fx.animate({modes:['node-property:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});},restore:function(){if(this.busy)return;this.busy=true;if(this.config.Tips.enable)this.st.tips.hide();this.select(false,false,false);this.normalizeDims();var that=this;this.st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});},select:function(id,name,index){if(!this.config.selectOnHover)return;var s=this.selected;if(s.id!=id||s.name!=name||s.index!=index){s.id=id;s.name=name;s.index=index;this.st.graph.eachNode(function(n){n.setData('border',false);});if(id){var n=this.st.graph.getNode(id);n.setData('border',s);var link=index===0?'prev':'next';link=n.getData(link);if(link){n=this.st.graph.getByName(link);if(n){n.setData('border',{name:name,index:1-index});}}}
this.st.plot();}},getLegend:function(){var legend={};var n;this.st.graph.getNode(this.st.root).eachAdjacency(function(adj){n=adj.nodeTo;});var colors=n.getData('colorArray'),len=colors.length;$.each(n.getData('stringArray'),function(s,i){legend[s]=colors[i%len];});return legend;},getMaxValue:function(){var maxValue=0;this.st.graph.eachNode(function(n){var valArray=n.getData('valueArray'),acumLeft=0,acumRight=0;$.each(valArray,function(v){acumLeft+=+v[0];acumRight+=+v[1];});var acum=acumRight>acumLeft?acumRight:acumLeft;maxValue=maxValue>acum?maxValue:acum;});return maxValue;},normalizeDims:function(){var root=this.st.graph.getNode(this.st.root),l=0;root.eachAdjacency(function(){l++;});var maxValue=this.getMaxValue()||1,size=this.st.canvas.getSize(),config=this.config,margin=config.Margin,labelOffset=config.labelOffset+config.Label.size,fixedDim=(size.width-(margin.left+margin.right))/ l,animate=config.animate,height=size.height-(margin.top+margin.bottom)-(config.showAggregates&&labelOffset)
-(config.showLabels&&labelOffset);this.st.graph.eachNode(function(n){var acumLeft=0,acumRight=0,animateValue=[];$.each(n.getData('valueArray'),function(v){acumLeft+=+v[0];acumRight+=+v[1];animateValue.push([0,0]);});var acum=acumRight>acumLeft?acumRight:acumLeft;n.setData('width',fixedDim);if(animate){n.setData('height',acum*height / maxValue,'end');n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return[n[0]*height / maxValue,n[1]*height / maxValue];}),'end');var dimArray=n.getData('dimArray');if(!dimArray){n.setData('dimArray',animateValue);}}else{n.setData('height',acum*height / maxValue);n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return[n[0]*height / maxValue,n[1]*height / maxValue];}));}});}});Options.BarChart={$extend:true,animate:true,type:'stacked',labelOffset:3,barsOffset:0,nodeCount:0,hoveredColor:'#9fd4ff',background:false,renderBackground:false,orientation:'horizontal',showAggregates:true,showLabels:true,Ticks:{enable:false,segments:4,color:'#000000'},Tips:{enable:false,onShow:$.empty,onHide:$.empty},Events:{enable:false,onClick:$.empty}};$jit.ST.Plot.NodeTypes.implement({'barchart-stacked':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),stringArray=node.getData('stringArray'),linkArray=node.getData('linkArray'),gvl=node.getData('gvl'),colorArray=node.getData('colorArray'),colorLength=colorArray.length,nodeCount=node.getData('nodeCount');var ctx=canvas.getCtx(),canvasSize=canvas.getSize(),opt={},border=node.getData('border'),gradient=node.getData('gradient'),config=node.getData('config'),horz=config.orientation=='horizontal',aggregates=config.showAggregates,showLabels=config.showLabels,label=config.Label,margin=config.Margin;if(colorArray&&dimArray&&stringArray){for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){acum+=(dimArray[i]||0);}}
if(config.shadow.enable){shadowThickness=config.shadow.size;ctx.fillStyle="rgba(0,0,0,.2)";if(horz){ctx.fillRect(x,y-shadowThickness,acum+shadowThickness,height+(shadowThickness*2));}else{ctx.fillRect(x-shadowThickness,y-acum-shadowThickness,width+(shadowThickness*2),acum+shadowThickness);}}
if(colorArray&&dimArray&&stringArray){for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];if(gradient){var linear;if(horz){linear=ctx.createLinearGradient(x+acum+dimArray[i]/2,y,x+acum+dimArray[i]/2,y+height);}else{linear=ctx.createLinearGradient(x,y-acum-dimArray[i]/2,x+width,y-acum-dimArray[i]/2);}
var color=$.rgbToHex($.map($.hexToRgb(colorArray[i%colorLength].slice(1)),function(v){return(v*0.8)>>0;}));linear.addColorStop(0,color);linear.addColorStop(0.3,colorArray[i%colorLength]);linear.addColorStop(0.7,colorArray[i%colorLength]);linear.addColorStop(1,color);ctx.fillStyle=linear;}
if(horz)
{yCoord=y;xCoord=x+acum;chartBarWidth=dimArray[i];chartBarHeight=height;}
else
{xCoord=x;yCoord=y-acum-dimArray[i];chartBarWidth=width;chartBarHeight=dimArray[i];}
ctx.fillRect(xCoord,yCoord,chartBarWidth,chartBarHeight);if(chartBarHeight>0)
{ctx.font=label.style+' '+(label.size-2)+'px '+label.family;labelText=valueArray[i].toString();mtxt=ctx.measureText(labelText);labelTextPaddingX=10;labelTextPaddingY=6;labelBoxWidth=mtxt.width+labelTextPaddingX;labelBoxHeight=label.size+labelTextPaddingY;if((horz&&(labelBoxWidth<chartBarWidth))||(!horz&&(labelBoxHeight<chartBarHeight)))
{labelBoxX=xCoord+chartBarWidth/2-mtxt.width/2-labelTextPaddingX/2;labelBoxY=yCoord+chartBarHeight/2-labelBoxHeight/2;ctx.fillStyle="rgba(255,255,255,.2)";$.roundedRect(ctx,labelBoxX,labelBoxY,labelBoxWidth,labelBoxHeight,4,"fill");ctx.fillStyle="rgba(0,0,0,.8)";$.roundedRect(ctx,labelBoxX,labelBoxY,labelBoxWidth,labelBoxHeight,4,"stroke");ctx.textAlign='center';ctx.fillStyle="rgba(255,255,255,.6)";ctx.fillText(labelText,labelBoxX+mtxt.width/2+labelTextPaddingX/2,labelBoxY+labelBoxHeight/2);ctx.fillStyle="rgba(0,0,0,.6)";ctx.fillText(labelText,labelBoxX+mtxt.width/2+labelTextPaddingX/2+1,labelBoxY+labelBoxHeight/2+1);}}
if(border&&border.name==stringArray[i]){opt.acum=acum;opt.dimValue=dimArray[i];}
acum+=(dimArray[i]||0);valAcum+=(valueArray[i]||0);}
if(border){ctx.save();ctx.lineWidth=2;ctx.strokeStyle=border.color;if(horz){ctx.strokeRect(x+opt.acum+1,y+1,opt.dimValue-2,height-2);}else{ctx.strokeRect(x+1,y-opt.acum-opt.dimValue+1,width-2,opt.dimValue-2);}
ctx.restore();}
if(label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textBaseline='middle';if(gvl){acumValueLabel=gvl;}else{acumValueLabel=valAcum;}
if(aggregates(node.name,valAcum)){if(!horz){ctx.textAlign='center';ctx.font=label.style+' '+label.size+'px '+label.family;ctx.save();gridHeight=canvasSize.height-(margin.top+margin.bottom+(config.Title.text?config.Title.size+config.Title.offset:0)+
(config.Subtitle.text?config.Subtitle.size+config.Subtitle.offset:0)+
(label?label.size+config.labelOffset:0));mtxt=ctx.measureText(acumValueLabel);boxWidth=mtxt.width+10;inset=10;boxHeight=label.size+6;if(boxHeight+acum+config.labelOffset>gridHeight){bottomPadding=acum-config.labelOffset-boxHeight;}else{bottomPadding=acum+config.labelOffset+inset;}
ctx.translate(x+width/2-(mtxt.width/2),y-bottomPadding);cornerRadius=4;boxX=-inset/2;boxY=-boxHeight/2;ctx.rotate(0*Math.PI / 180);ctx.fillStyle="rgba(255,255,255,.8)";if(boxHeight+acum+config.labelOffset>gridHeight){$.roundedRect(ctx,boxX,boxY,boxWidth,boxHeight,cornerRadius,"fill");}
ctx.fillStyle=ctx.strokeStyle=label.color;ctx.fillText(acumValueLabel,mtxt.width/2,0);ctx.restore();}}
if(showLabels(node.name,valAcum,node)){if(horz){ctx.font=label.style+' '+label.size+'px '+label.family;inset=10;gridWidth=canvasSize.width-(config.Margin.left+config.Margin.right);mtxt=ctx.measureText(node.name+": "+acumValueLabel);boxWidth=mtxt.width+10;inset=10;if(acum+boxWidth+config.labelOffset+inset>gridWidth){leftPadding=acum-config.labelOffset-boxWidth-inset;}else{leftPadding=acum+config.labelOffset;}
ctx.textAlign='left';ctx.translate(x+inset+leftPadding,y+height/2);boxHeight=label.size+6;boxX=-inset/2;boxY=-boxHeight/2;ctx.fillStyle="rgba(255,255,255,.8)";cornerRadius=4;if(acum+boxWidth+config.labelOffset+inset>gridWidth){$.roundedRect(ctx,boxX,boxY,boxWidth,boxHeight,cornerRadius,"fill");}
ctx.fillStyle=label.color;ctx.rotate(0*Math.PI / 180);ctx.fillText(node.name+": "+acumValueLabel,0,0);}else{if(nodeCount>8){ctx.textAlign='left';ctx.translate(x+width/2,y+label.size/2+config.labelOffset);ctx.rotate(45*Math.PI / 180);ctx.fillText(node.name,0,0);}else{ctx.textAlign='center';ctx.fillText(node.name,x+width/2,y+label.size/2+config.labelOffset);}}}
ctx.restore();}}},'contains':function(node,mpos){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),config=node.getData('config'),rx=mpos.x-x,horz=config.orientation=='horizontal';if(horz){if(mpos.x<x||mpos.x>x+width||mpos.y>y+height||mpos.y<y){return false;}}else{if(mpos.x<x||mpos.x>x+width||mpos.y>y||mpos.y<y-height){return false;}}
for(var i=0,l=dimArray.length,acum=(horz?x:y);i<l;i++){var dimi=dimArray[i];var url=Url.decode(node.getData('linkArray')[i]);if(horz){acum+=dimi;var intersec=acum;if(mpos.x<=intersec){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'percentage':((node.getData('valueArray')[i]/node.getData('barTotalValue'))*100).toFixed(1),'link':url,'label':node.name};}}else{acum-=dimi;var intersec=acum;if(mpos.y>=intersec){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'percentage':((node.getData('valueArray')[i]/node.getData('barTotalValue'))*100).toFixed(1),'link':url,'label':node.name};}}}
return false;}},'barchart-grouped':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),valuelabelArray=node.getData('valuelabelArray'),linkArray=node.getData('linkArray'),valueLength=valueArray.length,colorArray=node.getData('colorArray'),colorLength=colorArray.length,stringArray=node.getData('stringArray');var ctx=canvas.getCtx(),canvasSize=canvas.getSize(),opt={},border=node.getData('border'),gradient=node.getData('gradient'),config=node.getData('config'),horz=config.orientation=='horizontal',aggregates=config.showAggregates,showLabels=config.showLabels,label=config.Label,shadow=config.shadow,margin=config.Margin,fixedDim=(horz?height:width)/ valueLength;maxValue=Math.max.apply(null,dimArray);ctx.fillStyle="rgba(0,0,0,.2)";if(colorArray&&dimArray&&stringArray&&shadow.enable){shadowThickness=shadow.size;for(var i=0,l=valueLength,acum=0,valAcum=0;i<l;i++){nextBar=(dimArray[i+1])?dimArray[i+1]:false;prevBar=(dimArray[i-1])?dimArray[i-1]:false;if(horz){ctx.fillRect(x,y-shadowThickness+(fixedDim*i),dimArray[i]+shadowThickness,fixedDim+shadowThickness*2);}else{if(i==0){if(nextBar&&nextBar>dimArray[i]){ctx.fillRect((x-shadowThickness)+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim,dimArray[i]+shadowThickness);}else if(nextBar&&nextBar<dimArray[i]){ctx.fillRect((x-shadowThickness)+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim+shadowThickness*2,dimArray[i]+shadowThickness);}else{ctx.fillRect((x-shadowThickness)+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim+shadowThickness,dimArray[i]+shadowThickness);}}else if(i>0&&i<l-1){if(nextBar&&nextBar>dimArray[i]){ctx.fillRect((x-((prevBar<dimArray[i])?shadowThickness:0))+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim,dimArray[i]+shadowThickness);}else if(nextBar&&nextBar<dimArray[i]){ctx.fillRect((x-((prevBar<dimArray[i])?shadowThickness:0))+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim+shadowThickness*2,dimArray[i]+shadowThickness);}else{ctx.fillRect((x-((prevBar<dimArray[i])?shadowThickness:0))+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim+shadowThickness,dimArray[i]+shadowThickness);}}else if(i==l-1){ctx.fillRect((x-((prevBar<dimArray[i])?shadowThickness:0))+fixedDim*i,y-dimArray[i]-shadowThickness,fixedDim+shadowThickness*2,dimArray[i]+shadowThickness);}}}}
if(colorArray&&dimArray&&stringArray){for(var i=0,l=valueLength,acum=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];if(gradient){var linear;if(horz){linear=ctx.createLinearGradient(x+dimArray[i]/2,y+fixedDim*i,x+dimArray[i]/2,y+fixedDim*(i+1));}else{linear=ctx.createLinearGradient(x+fixedDim*i,y-dimArray[i]/2,x+fixedDim*(i+1),y-dimArray[i]/2);}
var color=$.rgbToHex($.map($.hexToRgb(colorArray[i%colorLength].slice(1)),function(v){return(v*0.8)>>0;}));linear.addColorStop(0,color);linear.addColorStop(0.3,colorArray[i%colorLength]);linear.addColorStop(0.7,colorArray[i%colorLength]);linear.addColorStop(1,color);ctx.fillStyle=linear;}
if(horz){ctx.fillRect(x,y+fixedDim*i,dimArray[i],fixedDim);}else{ctx.fillRect(x+fixedDim*i,y-dimArray[i],fixedDim,dimArray[i]);}
if(border&&border.name==stringArray[i]){opt.acum=fixedDim*i;opt.dimValue=dimArray[i];}
acum+=(dimArray[i]||0);valAcum+=(valueArray[i]||0);ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;inset=10;if(aggregates(node.name,valAcum)&&label.type=='Native'){if(valuelabelArray[i]){acumValueLabel=valuelabelArray[i];}else{acumValueLabel=valueArray[i];}
if(horz){ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textAlign='left';ctx.textBaseline='top';ctx.fillStyle="rgba(255,255,255,.8)";gridWidth=canvasSize.width-(margin.left+margin.right+config.labeloffset+label.size);mtxt=ctx.measureText(acumValueLabel);boxWidth=mtxt.width+10;if(boxWidth+dimArray[i]+config.labelOffset>gridWidth){leftPadding=dimArray[i]-config.labelOffset-boxWidth-inset;}else{leftPadding=dimArray[i]+config.labelOffset+inset;}
boxHeight=label.size+6;boxX=x+leftPadding;boxY=y+i*fixedDim+(fixedDim/2)-boxHeight/2;cornerRadius=4;if(boxWidth+dimArray[i]+config.labelOffset>gridWidth){$.roundedRect(ctx,boxX,boxY,boxWidth,boxHeight,cornerRadius,"fill");}
ctx.fillStyle=ctx.strokeStyle=label.color;ctx.fillText(acumValueLabel,x+inset/2+leftPadding,y+i*fixedDim+(fixedDim/2)-(label.size/2));}else{ctx.font=label.style+' '+label.size+'px '+label.family;ctx.save();ctx.textAlign='center';gridHeight=canvasSize.height-(margin.top+margin.bottom+(config.Title.text?config.Title.size+config.Title.offset:0)+
(config.Subtitle.text?config.Subtitle.size+config.Subtitle.offset:0)+
(label?label.size+config.labelOffset:0));mtxt=ctx.measureText(acumValueLabel);boxWidth=mtxt.width+10;boxHeight=label.size+6;if(boxHeight+dimArray[i]+config.labelOffset>gridHeight){bottomPadding=dimArray[i]-config.labelOffset-boxHeight-inset;}else{bottomPadding=dimArray[i]+config.labelOffset+inset;}
ctx.translate(x+(i*fixedDim)+(fixedDim/2),y-bottomPadding);boxX=-boxWidth/2;boxY=-boxHeight/2;ctx.fillStyle="rgba(255,255,255,.8)";cornerRadius=4;if(boxHeight+dimArray[i]+config.labelOffset>gridHeight){$.roundedRect(ctx,boxX,boxY,boxWidth,boxHeight,cornerRadius,"fill");}
ctx.fillStyle=ctx.strokeStyle=label.color;ctx.fillText(acumValueLabel,0,0);ctx.restore();}}}
if(border){ctx.save();ctx.lineWidth=2;ctx.strokeStyle=border.color;if(horz){ctx.strokeRect(x+1,y+opt.acum+1,opt.dimValue-2,fixedDim-2);}else{ctx.strokeRect(x+opt.acum+1,y-opt.dimValue+1,fixedDim-2,opt.dimValue-2);}
ctx.restore();}
if(label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textBaseline='middle';if(showLabels(node.name,valAcum,node)){if(horz){ctx.textAlign='center';ctx.translate(x-config.labelOffset-label.size/2,y+height/2);ctx.rotate(Math.PI / 2);ctx.fillText(node.name,0,0);}else{ctx.textAlign='center';ctx.fillText(node.name,x+width/2,y+label.size/2+config.labelOffset);}}
ctx.restore();}}},'contains':function(node,mpos){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),len=dimArray.length,config=node.getData('config'),rx=mpos.x-x,horz=config.orientation=='horizontal',fixedDim=(horz?height:width)/ len;if(horz){if(mpos.x<x||mpos.x>x+width||mpos.y>y+height||mpos.y<y){return false;}}else{if(mpos.x<x||mpos.x>x+width||mpos.y>y||mpos.y<y-height){return false;}}
for(var i=0,l=dimArray.length;i<l;i++){var dimi=dimArray[i];var url=Url.decode(node.getData('linkArray')[i]);if(horz){var limit=y+fixedDim*i;if(mpos.x<=x+dimi&&mpos.y>=limit&&mpos.y<=limit+fixedDim){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'title':node.getData('titleArray')[i],'percentage':((node.getData('valueArray')[i]/node.getData('barTotalValue'))*100).toFixed(1),'link':url,'label':node.name};}}else{var limit=x+fixedDim*i;if(mpos.x>=limit&&mpos.x<=limit+fixedDim&&mpos.y>=y-dimi){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'title':node.getData('titleArray')[i],'percentage':((node.getData('valueArray')[i]/node.getData('barTotalValue'))*100).toFixed(1),'link':url,'label':node.name};}}}
return false;}},'barchart-basic':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),valuelabelArray=node.getData('valuelabelArray'),linkArray=node.getData('linkArray'),valueLength=valueArray.length,colorArray=node.getData('colorMono'),colorLength=colorArray.length,stringArray=node.getData('stringArray');var ctx=canvas.getCtx(),canvasSize=canvas.getSize(),opt={},border=node.getData('border'),gradient=node.getData('gradient'),config=node.getData('config'),horz=config.orientation=='horizontal',aggregates=config.showAggregates,showLabels=config.showLabels,label=config.Label,fixedDim=(horz?height:width)/ valueLength,margin=config.Margin;if(colorArray&&dimArray&&stringArray){for(var i=0,l=valueLength,acum=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];if(gradient){var linear;if(horz){linear=ctx.createLinearGradient(x+dimArray[i]/2,y+fixedDim*i,x+dimArray[i]/2,y+fixedDim*(i+1));}else{linear=ctx.createLinearGradient(x+fixedDim*i,y-dimArray[i]/2,x+fixedDim*(i+1),y-dimArray[i]/2);}
if(config.shadow.size){shadowThickness=config.shadow.size;ctx.fillStyle="rgba(0,0,0,.2)";if(horz){ctx.fillRect(x,y+fixedDim*i-(shadowThickness),dimArray[i]+shadowThickness,fixedDim+(shadowThickness*2));}else{ctx.fillRect(x+fixedDim*i-(shadowThickness),y-dimArray[i]-shadowThickness,fixedDim+(shadowThickness*2),dimArray[i]+shadowThickness);}}
var color=$.rgbToHex($.map($.hexToRgb(colorArray[i%colorLength].slice(1)),function(v){return(v*0.8)>>0;}));linear.addColorStop(0,color);linear.addColorStop(0.3,colorArray[i%colorLength]);linear.addColorStop(0.7,colorArray[i%colorLength]);linear.addColorStop(1,color);ctx.fillStyle=linear;}
if(horz){ctx.fillRect(x,y+fixedDim*i,dimArray[i],fixedDim);}else{ctx.fillRect(x+fixedDim*i,y-dimArray[i],fixedDim,dimArray[i]);}
if(border&&border.name==stringArray[i]){opt.acum=fixedDim*i;opt.dimValue=dimArray[i];}
acum+=(dimArray[i]||0);valAcum+=(valueArray[i]||0);if(label.type=='Native'){ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;if(aggregates(node.name,valAcum)){if(valuelabelArray[i]){acumValueLabel=valuelabelArray[i];}else{acumValueLabel=valueArray[i];}
if(!horz){ctx.textAlign='center';ctx.font=label.style+' '+label.size+'px '+label.family;ctx.save();gridHeight=canvasSize.height-(margin.top+margin.bottom+(config.Title.text?config.Title.size+config.Title.offset:0)+
(config.Subtitle.text?config.Subtitle.size+config.Subtitle.offset:0)+
(label?label.size+config.labelOffset:0));mtxt=ctx.measureText(acumValueLabel);boxWidth=mtxt.width+10;inset=10;boxHeight=label.size+6;if(boxHeight+dimArray[i]+config.labelOffset>gridHeight){bottomPadding=dimArray[i]-config.labelOffset-inset;}else{bottomPadding=dimArray[i]+config.labelOffset+inset;}
ctx.translate(x+width/2-(mtxt.width/2),y-bottomPadding);cornerRadius=4;boxX=-inset/2;boxY=-boxHeight/2;ctx.fillStyle="rgba(255,255,255,.6)";if(boxHeight+dimArray[i]+config.labelOffset>gridHeight){$.roundedRect(ctx,boxX,boxY,boxWidth,boxHeight,cornerRadius,"fill");}
ctx.fillStyle=ctx.strokeStyle=label.color;ctx.fillText(acumValueLabel,mtxt.width/2,0);ctx.restore();}}}}
if(border){ctx.save();ctx.lineWidth=2;ctx.strokeStyle=border.color;if(horz){ctx.strokeRect(x+1,y+opt.acum+1,opt.dimValue-2,fixedDim-2);}else{ctx.strokeRect(x+opt.acum+1,y-opt.dimValue+1,fixedDim-2,opt.dimValue-2);}
ctx.restore();}
if(label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textBaseline='middle';if(showLabels(node.name,valAcum,node)){if(horz){gridWidth=canvasSize.width-(config.Margin.left+config.Margin.right);mtxt=ctx.measureText(node.name+": "+valAcum);boxWidth=mtxt.width+10;inset=10;if(acum+boxWidth+config.labelOffset+inset>gridWidth){leftPadding=acum-config.labelOffset-boxWidth-inset;}else{leftPadding=acum+config.labelOffset;}
ctx.textAlign='left';ctx.translate(x+inset+leftPadding,y+height/2);boxHeight=label.size+6;boxX=-inset/2;boxY=-boxHeight/2;ctx.fillStyle="rgba(255,255,255,.8)";cornerRadius=4;if(acum+boxWidth+config.labelOffset+inset>gridWidth){$.roundedRect(ctx,boxX,boxY,boxWidth,boxHeight,cornerRadius,"fill");}
ctx.fillStyle=label.color;ctx.fillText(node.name+": "+valAcum,0,0);}else{if(stringArray.length>8){ctx.textAlign='left';ctx.translate(x+width/2,y+label.size/2+config.labelOffset);ctx.rotate(45*Math.PI / 180);ctx.fillText(node.name,0,0);}else{ctx.textAlign='center';ctx.fillText(node.name,x+width/2,y+label.size/2+config.labelOffset);}}}
ctx.restore();}}},'contains':function(node,mpos){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),config=node.getData('config'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),len=dimArray.length,rx=mpos.x-x,horz=config.orientation=='horizontal',fixedDim=(horz?height:width)/ len;if(horz){if(mpos.x<x||mpos.x>x+width||mpos.y>y+height||mpos.y<y){return false;}}else{if(mpos.x<x||mpos.x>x+width||mpos.y>y||mpos.y<y-height){return false;}}
for(var i=0,l=dimArray.length;i<l;i++){var dimi=dimArray[i];var url=Url.decode(node.getData('linkArray')[i]);if(horz){var limit=y+fixedDim*i;if(mpos.x<=x+dimi&&mpos.y>=limit&&mpos.y<=limit+fixedDim){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'percentage':((node.getData('valueArray')[i]/node.getData('groupTotalValue'))*100).toFixed(1),'link':url,'label':node.name};}}else{var limit=x+fixedDim*i;if(mpos.x>=limit&&mpos.x<=limit+fixedDim&&mpos.y>=y-dimi){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'percentage':((node.getData('valueArray')[i]/node.getData('groupTotalValue'))*100).toFixed(1),'link':url,'label':node.name};}}}
return false;}}});$jit.BarChart=new Class({st:null,colors:["#004b9c","#9c0079","#9c0033","#28009c","#9c0000","#7d009c","#001a9c","#00809c","#009c80","#009c42","#009c07","#469c00","#799c00","#9c9600","#9c5c00"],selected:{},busy:false,initialize:function(opt){this.controller=this.config=$.merge(Options("Canvas","Margin","Label","BarChart"),{Label:{type:'Native'}},opt);var showLabels=this.config.showLabels,typeLabels=$.type(showLabels),showAggregates=this.config.showAggregates,typeAggregates=$.type(showAggregates);this.config.showLabels=typeLabels=='function'?showLabels:$.lambda(showLabels);this.config.showAggregates=typeAggregates=='function'?showAggregates:$.lambda(showAggregates);Options.Fx.clearCanvas=false;this.initializeViz();},initializeViz:function(){var config=this.config,that=this;var nodeType=config.type.split(":")[0],horz=config.orientation=='horizontal',nodeLabels={};var st=new $jit.ST({injectInto:config.injectInto,orientation:horz?'left':'bottom',background:config.background,renderBackground:config.renderBackground,backgroundColor:config.backgroundColor,colorStop1:config.colorStop1,colorStop2:config.colorStop2,levelDistance:0,nodeCount:config.nodeCount,siblingOffset:config.barsOffset,subtreeOffset:0,withLabels:config.Label.type!='Native',useCanvas:config.useCanvas,Label:{type:config.Label.type},Node:{overridable:true,type:'barchart-'+nodeType,align:'left',width:1,height:1},Edge:{type:'none'},Tips:{enable:config.Tips.enable,type:'Native',force:true,onShow:function(tip,node,contains){var elem=contains;config.Tips.onShow(tip,elem,node);if(elem.link!='undefined'&&elem.link!=''){document.body.style.cursor='pointer';}},onHide:function(call){document.body.style.cursor='default';}},Events:{enable:true,type:'Native',onClick:function(node,eventInfo,evt){if(!config.Events.enable)return;var elem=eventInfo.getContains();config.Events.onClick(elem,eventInfo,evt);},onMouseMove:function(node,eventInfo,evt){if(!config.hoveredColor)return;if(node){var elem=eventInfo.getContains();that.select(node.id,elem.name,elem.index);}else{that.select(false,false,false);}}},onCreateLabel:function(domElement,node){var labelConf=config.Label,valueArray=node.getData('valueArray'),acum=$.reduce(valueArray,function(x,y){return x+y;},0),grouped=config.type.split(':')[0]=='grouped',horz=config.orientation=='horizontal';var nlbs={wrapper:document.createElement('div'),aggregate:document.createElement('div'),label:document.createElement('div')};var wrapper=nlbs.wrapper,label=nlbs.label,aggregate=nlbs.aggregate,wrapperStyle=wrapper.style,labelStyle=label.style,aggregateStyle=aggregate.style;nodeLabels[node.id]=nlbs;wrapper.appendChild(label);wrapper.appendChild(aggregate);if(!config.showLabels(node.name,acum,node)){labelStyle.display='none';}
if(!config.showAggregates(node.name,acum,node)){aggregateStyle.display='none';}
wrapperStyle.position='relative';wrapperStyle.overflow='visible';wrapperStyle.fontSize=labelConf.size+'px';wrapperStyle.fontFamily=labelConf.family;wrapperStyle.color=labelConf.color;wrapperStyle.textAlign='center';aggregateStyle.position=labelStyle.position='absolute';domElement.style.width=node.getData('width')+'px';domElement.style.height=node.getData('height')+'px';aggregateStyle.left="0px";labelStyle.left=config.labelOffset+'px';labelStyle.whiteSpace="nowrap";label.innerHTML=node.name;domElement.appendChild(wrapper);},onPlaceLabel:function(domElement,node){if(!nodeLabels[node.id])return;var labels=nodeLabels[node.id],wrapperStyle=labels.wrapper.style,labelStyle=labels.label.style,aggregateStyle=labels.aggregate.style,grouped=config.type.split(':')[0]=='grouped',horz=config.orientation=='horizontal',dimArray=node.getData('dimArray'),valArray=node.getData('valueArray'),nodeCount=node.getData('nodeCount'),valueLength=valArray.length;valuelabelArray=node.getData('valuelabelArray'),stringArray=node.getData('stringArray'),width=(grouped&&horz)?Math.max.apply(null,dimArray):node.getData('width'),height=(grouped&&!horz)?Math.max.apply(null,dimArray):node.getData('height'),font=parseInt(wrapperStyle.fontSize,10),domStyle=domElement.style,fixedDim=(horz?height:width)/ valueLength;if(dimArray&&valArray){wrapperStyle.width=aggregateStyle.width=labelStyle.width=domElement.style.width=width+'px';aggregateStyle.width=width-config.labelOffset+"px";for(var i=0,l=valArray.length,acum=0;i<l;i++){if(dimArray[i]>0){acum+=valArray[i];}}
if(config.showLabels(node.name,acum,node)){labelStyle.display='';}else{labelStyle.display='none';}
if(config.showAggregates(node.name,acum,node)){aggregateStyle.display='';}else{aggregateStyle.display='none';}
if(config.orientation=='horizontal'){aggregateStyle.textAlign='right';labelStyle.textAlign='left';labelStyle.textIndex=aggregateStyle.textIndent=config.labelOffset+'px';aggregateStyle.top=labelStyle.top=(height-font)/2+'px';domElement.style.height=wrapperStyle.height=height+'px';}else{aggregateStyle.top=(-font-config.labelOffset)+'px';labelStyle.top=(config.labelOffset+height)+'px';domElement.style.top=parseInt(domElement.style.top,10)-height+'px';domElement.style.height=wrapperStyle.height=height+'px';if(stringArray.length>8){labels.label.className="rotatedLabelReverse";labelStyle.textAlign="left";labelStyle.top=config.labelOffset+height+width/2+"px";}}
if(horz){labels.label.innerHTML=labels.label.innerHTML+": "+acum;labels.aggregate.innerHTML="";}else{if(grouped){maxValue=Math.max.apply(null,dimArray);for(var i=0,l=valArray.length,acum=0,valAcum=0;i<l;i++){valueLabelDim=50;valueLabel=document.createElement('div');valueLabel.innerHTML=valuelabelArray[i];valueLabel.className="rotatedLabel";valueLabel.style.position="absolute";valueLabel.style.textAlign="left";valueLabel.style.verticalAlign="middle";valueLabel.style.height=valueLabelDim+"px";valueLabel.style.width=valueLabelDim+"px";valueLabel.style.top=(maxValue-dimArray[i])-valueLabelDim-config.labelOffset+"px";valueLabel.style.left=(fixedDim*i)+"px";labels.wrapper.appendChild(valueLabel);}}else{labels.aggregate.innerHTML=acum;}}}}});var size=st.canvas.getSize(),l=config.nodeCount,margin=config.Margin;title=config.Title;subtitle=config.Subtitle,grouped=config.type.split(':')[0]=='grouped',margin=config.Margin,ticks=config.Ticks,marginWidth=margin.left+margin.right+(config.Label&&grouped?config.Label.size+config.labelOffset:0),marginHeight=(title.text?title.size+title.offset:0)+(subtitle.text?subtitle.size+subtitle.offset:0)+margin.top+margin.bottom,horz=config.orientation=='horizontal',fixedDim=(size[horz?'height':'width']-(horz?marginHeight:marginWidth)-(ticks.enable?config.Label.size+config.labelOffset:0)-(l-1)*config.barsOffset)/ l,fixedDim=(fixedDim>40)?40:fixedDim;whiteSpace=size.width-(marginWidth+(fixedDim*l));if(!horz&&typeof FlashCanvas!="undefined"&&size.width<250)
location.reload();if(!grouped&&!horz){st.config.siblingOffset=whiteSpace/(l+1);}
if(horz){st.config.offsetX=size.width/2-margin.left-(grouped&&config.Label?config.labelOffset+config.Label.size:0);if(config.Ticks.enable){st.config.offsetY=((margin.bottom+config.Label.size+config.labelOffset+(subtitle.text?subtitle.size+subtitle.offset:0))-(margin.top+(title.text?title.size+title.offset:0)))/2;}else{st.config.offsetY=(margin.bottom-margin.top-(title.text?title.size+title.offset:0)-(subtitle.text?subtitle.size+subtitle.offset:0))/2;}}else{st.config.offsetY=-size.height/2+margin.bottom
+(config.showLabels&&(config.labelOffset+config.Label.size))+(subtitle.text?subtitle.size+subtitle.offset:0);if(config.Ticks.enable){st.config.offsetX=((margin.right-config.Label.size-config.labelOffset)-margin.left)/2;}else{st.config.offsetX=(margin.right-margin.left)/2;}}
this.st=st;this.canvas=this.st.canvas;},renderTitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,label=config.Label,title=config.Title;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' bold '+' '+title.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(title.text,-size.width/2+margin.left,-size.height/2+margin.top);}},renderSubtitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,label=config.Label,subtitle=config.Subtitle,nodeCount=config.nodeCount,horz=config.orientation=='horizontal'?true:false,ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' '+subtitle.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(subtitle.text,-size.width/2+margin.left,size.height/2-(!horz&&nodeCount>8?20:margin.bottom)-subtitle.size);}},renderScrollNote:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,label=config.Label,note=config.ScrollNote;ctx=canvas.getCtx();ctx.fillStyle=title.color;title=config.Title;ctx.textAlign='center';ctx.font=label.style+' bold '+' '+note.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(note.text,0,-size.height/2+margin.top+title.size);}},renderTicks:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,ticks=config.Ticks,title=config.Title,subtitle=config.Subtitle,label=config.Label,shadow=config.shadow;horz=config.orientation=='horizontal',grouped=config.type.split(':')[0]=='grouped',ctx=canvas.getCtx();ctx.strokeStyle=ticks.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textAlign='center';ctx.textBaseline='middle';idLabel=canvas.id+"-label";labelDim=100;container=document.getElementById(idLabel);if(horz){var axis=-(size.width/2)+margin.left+(grouped&&config.Label?config.labelOffset+label.size:0),grid=size.width-(margin.left+margin.right+(grouped&&config.Label?config.labelOffset+label.size:0)),segmentLength=grid/ticks.segments;ctx.fillStyle=ticks.color;var xTop=axis;var yTop=size.height / 2-margin.bottom-config.labelOffset-label.size-(subtitle.text?subtitle.size+subtitle.offset:0)+(shadow.enable?shadow.size:0);var xLength=size.width-margin.left-margin.right-(grouped&&config.Label?config.labelOffset+label.size:0);var yLength=1;ctx.fillRect(xTop,yTop,xLength,yLength);maxTickValue=config.Ticks.maxValue;var humanNumber=config.Ticks.humanNumber;var segments=config.Ticks.segments;var tempHumanNumber=humanNumber;var humanNumberPow=0;while(tempHumanNumber%1!=0)
{tempHumanNumber=tempHumanNumber*10;humanNumberPow++;}
var pixelsPerStep=xLength / maxTickValue;var lineHeight=size.height-margin.bottom-margin.top-config.labelOffset-label.size-(title.text?title.size+title.offset:0)-(subtitle.text?subtitle.size+subtitle.offset:0);for(var i=0;i<=segments;i++)
{var iX=Math.round(xTop+i*pixelsPerStep*humanNumber);ctx.save();ctx.translate(iX,yTop+yLength+margin.top);ctx.rotate(0*Math.PI / 2*3);ctx.fillStyle=label.color;var labelText=humanNumber*Math.pow(10,humanNumberPow)*i;labelText=labelText*Math.pow(10,-humanNumberPow);if(config.showLabels)
{if(label.type=='Native')
{ctx.fillText(labelText,0,0);}
else
{labelDiv=document.createElement('div');labelDiv.innerHTML=labelText;labelDiv.style.top=Math.round(size.height-margin.bottom-config.labelOffset)+"px";labelDiv.style.left=Math.round(margin.left-labelDim / 2+i*pixelsPerStep*humanNumber)+"px";labelDiv.style.width=labelDim+"px";labelDiv.style.height=labelDim+"px";labelDiv.style.textAlign="center";labelDiv.style.verticalAlign="middle";labelDiv.style.position="absolute";labelDiv.style.background='1px solid red';container.appendChild(labelDiv);}}
ctx.restore();ctx.fillStyle=ticks.color;ctx.fillRect(Math.round(axis)+i*pixelsPerStep*humanNumber,-size.height / 2+margin.top+(title.text?title.size+title.offset:0)-(shadow.enable?shadow.size:0),1,lineHeight+(shadow.enable?shadow.size*2:0));}}else{var axis=(size.height/2)-(margin.bottom+config.labelOffset+label.size+(subtitle.text?subtitle.size+subtitle.offset:0)),htmlOrigin=size.height-(margin.bottom+config.labelOffset+label.size+(subtitle.text?subtitle.size+subtitle.offset:0)),grid=-size.height+(margin.bottom+config.labelOffset+label.size+margin.top+(title.text?title.size+title.offset:0)+(subtitle.text?subtitle.size+subtitle.offset:0)),segmentLength=grid/ticks.segments;ctx.fillStyle=ticks.color;var xTop=-size.width / 2+margin.left+config.labelOffset+label.size-1;var yTop=-size.height / 2+margin.top+(title.text?title.size+title.offset:0);var xLength=1;var yLength=size.height-margin.top-margin.bottom-label.size-config.labelOffset-(title.text?title.size+title.offset:0)-(subtitle.text?subtitle.size+subtitle.offset:0);ctx.fillRect(xTop,yTop,xLength,yLength);maxTickValue=config.Ticks.maxValue;var humanNumber=config.Ticks.humanNumber;var segments=config.Ticks.segments;var tempHumanNumber=humanNumber;var humanNumberPow=0;while(tempHumanNumber%1!=0)
{tempHumanNumber=tempHumanNumber*10;humanNumberPow++;}
var pixelsPerStep=yLength / maxTickValue;for(var i=0;i<=segments;i++)
{var iY=Math.round(yTop+yLength-i*pixelsPerStep*humanNumber);ctx.save();ctx.translate(-size.width / 2+margin.left,iY);ctx.rotate(0*Math.PI / 2*3);ctx.fillStyle=label.color;var labelText=humanNumber*Math.pow(10,humanNumberPow)*i;labelText=labelText*Math.pow(10,-humanNumberPow);if(config.showLabels)
{if(label.type=='Native')
{ctx.fillText(labelText,0,0);}
else
{labelDiv=document.createElement('div');labelDiv.innerHTML=labelText;labelDiv.className="rotatedLabel";labelDiv.style.top=Math.round(htmlOrigin-labelDim / 2-i*pixelsPerStep*humanNumber)+"px";labelDiv.style.left=margin.left+"px";labelDiv.style.width=labelDim+"px";labelDiv.style.height=labelDim+"px";labelDiv.style.textAlign="center";labelDiv.style.verticalAlign="middle";labelDiv.style.position="absolute";container.appendChild(labelDiv);}}
ctx.restore();ctx.fillStyle=ticks.color;ctx.fillRect(-size.width / 2+margin.left+config.labelOffset+label.size,iY,size.width-margin.right-margin.left-config.labelOffset-label.size,1);}}},renderBackground:function(){var canvas=this.canvas,config=this.config,backgroundColor=config.backgroundColor,size=canvas.getSize(),ctx=canvas.getCtx();ctx.fillStyle=backgroundColor;ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);},clear:function(){var canvas=this.canvas;var ctx=canvas.getCtx(),size=canvas.getSize();ctx.fillStyle="rgba(255,255,255,0)";ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);ctx.clearRect(-size.width/2,-size.height/2,size.width,size.height);},resizeGraph:function(json,width){var canvas=this.canvas,size=canvas.getSize(),config=this.config,orgHeight=size.height,margin=config.Margin,st=this.st,grouped=config.type.split(':')[0]=='grouped',horz=config.orientation=='horizontal';canvas.resize(width,orgHeight);if(typeof FlashCanvas=="undefined"){canvas.clear();}else{this.clear();}
if(horz){st.config.offsetX=size.width/2-margin.left-(grouped&&config.Label?config.labelOffset+config.Label.size:0);}
this.loadJSON(json);},loadJSON:function(json){if(this.busy)return;this.busy=true;var prefix=$.time(),ch=[],st=this.st,name=$.splat(json.label),color=$.splat(json.color||this.colors),config=this.config,gradient=!!config.type.split(":")[1],renderBackground=config.renderBackground,animate=config.animate,ticks=config.Ticks,title=config.Title,note=config.ScrollNote,subtitle=config.Subtitle,horz=config.orientation=='horizontal',that=this,colorLength=color.length,nameLength=name.length;groupTotalValue=0;for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];var valArray=$.splat(val.values);groupTotalValue+=parseFloat(valArray.sum());}
for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];var valArray=$.splat(values[i].values);var valuelabelArray=$.splat(values[i].valuelabels);var linkArray=$.splat(values[i].links);var titleArray=$.splat(values[i].titles);var barTotalValue=valArray.sum();var acum=0;if(typeof val.id=='undefined'){val.id=val.label;}
ch.push({'id':prefix+val.id,'name':val.label,'data':{'value':valArray,'$linkArray':linkArray,'$gvl':val.gvaluelabel,'$titleArray':titleArray,'$valueArray':valArray,'$valuelabelArray':valuelabelArray,'$colorArray':color,'$colorMono':$.splat(color[i%colorLength]),'$stringArray':name,'$barTotalValue':barTotalValue,'$groupTotalValue':groupTotalValue,'$nodeCount':values.length,'$gradient':gradient,'$config':config},'children':[]});}
var root={'id':prefix+'$root','name':'','data':{'$type':'none','$width':1,'$height':1},'children':ch};st.loadJSON(root);this.normalizeDims();if(renderBackground){this.renderBackground();}
if(!animate&&ticks.enable){this.renderTicks();}
if(!animate&&note.text){this.renderScrollNote();}
if(!animate&&title.text){this.renderTitle();}
if(!animate&&subtitle.text){this.renderSubtitle();}
st.compute();st.select(st.root);if(animate){if(horz){st.fx.animate({modes:['node-property:width:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});}else{st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});}}else{this.busy=false;}},updateJSON:function(json,onComplete){if(this.busy)return;this.busy=true;var st=this.st;var graph=st.graph;var values=json.values;var animate=this.config.animate;var that=this;var horz=this.config.orientation=='horizontal';$.each(values,function(v){var n=graph.getByName(v.label);if(n){n.setData('valueArray',$.splat(v.values));if(json.label){n.setData('stringArray',$.splat(json.label));}}});this.normalizeDims();st.compute();st.select(st.root);if(animate){if(horz){st.fx.animate({modes:['node-property:width:dimArray'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}else{st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}}},select:function(id,name){if(!this.config.hoveredColor)return;var s=this.selected;if(s.id!=id||s.name!=name){s.id=id;s.name=name;s.color=this.config.hoveredColor;this.st.graph.eachNode(function(n){if(id==n.id){n.setData('border',s);}else{n.setData('border',false);}});this.st.plot();}},getLegend:function(){var legend=new Array();var name=new Array();var color=new Array();var n;this.st.graph.getNode(this.st.root).eachAdjacency(function(adj){n=adj.nodeTo;});var colors=n.getData('colorArray'),len=colors.length;$.each(n.getData('stringArray'),function(s,i){color[i]=colors[i%len];name[i]=s;});legend['name']=name;legend['color']=color;return legend;},getMaxValue:function(){var maxValue=0,stacked=this.config.type.split(':')[0]=='stacked';this.st.graph.eachNode(function(n){var valArray=n.getData('valueArray'),acum=0;if(!valArray)return;if(stacked){$.each(valArray,function(v){acum+=+v;});}else{acum=Math.max.apply(null,valArray);}
maxValue=maxValue>acum?maxValue:acum;});return maxValue;},setBarType:function(type){this.config.type=type;this.st.config.Node.type='barchart-'+type.split(':')[0];},normalizeDims:function(){var root=this.st.graph.getNode(this.st.root),l=0;root.eachAdjacency(function(){l++;});var maxValue=this.getMaxValue()||1,size=this.st.canvas.getSize(),config=this.config,margin=config.Margin,ticks=config.Ticks,title=config.Title,subtitle=config.Subtitle,grouped=config.type.split(':')[0]=='grouped',marginWidth=margin.left+margin.right+(config.Label&&grouped?config.Label.size+config.labelOffset:0),marginHeight=(title.text?title.size+title.offset:0)+(subtitle.text?subtitle.size+subtitle.offset:0)+margin.top+margin.bottom,horz=config.orientation=='horizontal',fixedDim=(size[horz?'height':'width']-(horz?marginHeight:marginWidth)-(ticks.enable?config.Label.size+config.labelOffset:0)-(l-1)*config.barsOffset)/ l,animate=config.animate,height=size[horz?'width':'height']-(horz?marginWidth:marginHeight)
-((config.showLabels&&!horz)?(config.Label.size+config.labelOffset):0),dim1=horz?'height':'width',dim2=horz?'width':'height',basic=config.type.split(':')[0]=='basic';var iDirection=10;var zeroCount=0;var iNumber=maxValue;if(iNumber>=0)
{while(iNumber>=1)
{zeroCount++;iNumber=iNumber / 10;}
iNumber=Math.floor(iNumber*100);}
else
{iDirection=0.1;while(iNumber<1)
{zeroCount++;iNumber=iNumber*10;}
iNumber=Math.floor(iNumber*10);}
var humanNumber=0;var iNumberTemp=iNumber+1;while(iNumberTemp%5!=0)
{iNumberTemp++;}
var isFound=false;zeroCount--;while(isFound==false)
{if(iNumberTemp%ticks.segments==0)
{humanNumber=iNumberTemp / ticks.segments;isFound=true;break;}
iNumberTemp=iNumberTemp+5;}
var maxTickValue=config.Ticks.maxValue=maxTickValue=iNumberTemp*Math.pow(iDirection,zeroCount-1);config.Ticks.humanNumber=humanNumber=humanNumber*Math.pow(iDirection,zeroCount-1);config.Ticks.segments=Math.floor(maxTickValue / humanNumber);fixedDim=fixedDim>40?40:fixedDim;this.st.graph.eachNode(function(n){var acum=0,animateValue=[];$.each(n.getData('valueArray'),function(v){acum+=+v;animateValue.push(0);});if(grouped){fixedDim=animateValue.length*40;}
n.setData(dim1,fixedDim);if(animate){n.setData(dim2,acum*height / maxValue,'end');n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return n*height / maxValue;}),'end');var dimArray=n.getData('dimArray');if(!dimArray){n.setData('dimArray',animateValue);}}else{if(ticks.enable){n.setData(dim2,acum*height / maxTickValue);n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return n*height / maxTickValue;}));}else{n.setData(dim2,acum*height / maxValue);n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return n*height / maxValue;}));}}});}});Options.FunnelChart={$extend:true,animate:true,type:'stacked',labelOffset:3,barsOffset:0,hoveredColor:'#9fd4ff',orientation:'vertical',showAggregates:true,showLabels:true,Tips:{enable:false,onShow:$.empty,onHide:$.empty},Events:{enable:false,onClick:$.empty}};$jit.ST.Plot.NodeTypes.implement({'funnelchart-basic':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),valuelabelArray=node.getData('valuelabelArray'),linkArray=node.getData('linkArray'),colorArray=node.getData('colorArray'),colorLength=colorArray.length,stringArray=node.getData('stringArray');var ctx=canvas.getCtx(),opt={},border=node.getData('border'),gradient=node.getData('gradient'),config=node.getData('config'),horz=config.orientation=='horizontal',aggregates=config.showAggregates,showLabels=config.showLabels,label=config.Label,size=canvas.getSize(),labelOffset=config.labelOffset+10;minWidth=width*.25;ratio=.65;if(colorArray&&dimArray&&stringArray){var newDimArray=this.positions(dimArray,label.size);for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];if(label.type=='Native'){if(showLabels(node.name,valAcum,node)){ctx.font=label.style+' '+label.size+'px '+label.family;var stringValue=stringArray[i];var valueLabel=String(valuelabelArray[i]);var mV=ctx.measureText(stringValue);var mVL=ctx.measureText(valueLabel);var next_mVL=0;var next_mV=0;if((i+1)<l)
{next_mV=ctx.measureText(stringArray[i+1]);next_mVL=ctx.measureText(String(valuelabelArray[i+1]));}
else
{next_mV=mV;next_mVL=mVL;}
var previousElementHeight=(i>0)?dimArray[i-1]:100;var labelOffsetHeight=(previousElementHeight<label.size&&i>0)?((dimArray[i]>label.size)?(dimArray[i]/2)-(label.size/2):label.size):0;var topWidth=minWidth+((acum+dimArray[i])*ratio);var bottomWidth=minWidth+((acum)*ratio);var bottomWidthLabel=minWidth+(newDimArray[i].position*ratio);var labelOffsetRight=(newDimArray[i].filament)?(next_mV.width+25):0;var labelOffsetLeft=(newDimArray[i].filament)?(next_mVL.width+25):0;ctx.beginPath();ctx.moveTo(bottomWidth/2,y-acum);ctx.lineTo(bottomWidthLabel / 2+(labelOffset-10),y-newDimArray[i].position);ctx.lineTo(bottomWidthLabel / 2+(labelOffset)+labelOffsetRight+mV.width,y-newDimArray[i].position);ctx.stroke();ctx.beginPath();ctx.moveTo(-bottomWidth/2,y-acum);ctx.lineTo(-bottomWidthLabel / 2-(labelOffset-10),y-newDimArray[i].position);ctx.lineTo(-bottomWidthLabel / 2-(labelOffset)-labelOffsetLeft-mVL.width,y-newDimArray[i].position);ctx.stroke();}}
acum+=(dimArray[i]||0);valAcum+=(valueArray[i]||0);}
for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){ctx.fillStyle=ctx.strokeStyle=colorArray[i%colorLength];var colori=colorArray[i%colorLength];if(label.type=='Native'){var stringValue=stringArray[i];var valueLabel=String(valuelabelArray[i]);var mV=ctx.measureText(stringValue);var mVL=ctx.measureText(valueLabel);}else{var mV=10;var mVL=10;}
if((i+1)<l)
{next_mV=ctx.measureText(stringArray[i+1]);next_mVL=ctx.measureText(String(valuelabelArray[i+1]));}
else
{next_mV=mV;next_mVL=mVL;}
var previousElementHeight=(i>0)?dimArray[i-1]:100;var labelOffsetHeight=(previousElementHeight<label.size&&i>0)?((dimArray[i]>label.size)?(dimArray[i]/2)-(label.size/2):label.size):0;var labelOffsetRight=(newDimArray[i].filament)?(next_mV.width+20):0;var labelOffsetLeft=(newDimArray[i].filament)?(next_mVL.width+20):0;var topWidth=minWidth+((acum+dimArray[i])*ratio);var bottomWidth=minWidth+((acum)*ratio);var bottomWidthLabel=minWidth+(newDimArray[i].position*ratio);if(gradient){var linear;linear=ctx.createLinearGradient(-topWidth/2,y-acum-dimArray[i]/2,topWidth/2,y-acum-dimArray[i]/2);var colorRgb=$.hexToRgb(colori);var color=$.map($.hexToRgb(colorArray[i%colorLength].slice(1)),function(v){return(v*.5)>>0;});linear.addColorStop(0,'rgba('+color+',1)');linear.addColorStop(0.5,'rgba('+colorRgb+',1)');linear.addColorStop(1,'rgba('+color+',1)');ctx.fillStyle=linear;}
ctx.beginPath();ctx.moveTo(-topWidth/2,y-acum-dimArray[i]);ctx.lineTo(topWidth/2,y-acum-dimArray[i]);ctx.lineTo(bottomWidth/2,y-acum);ctx.lineTo(-bottomWidth/2,y-acum);ctx.closePath();ctx.fill();if(border&&border.name==stringArray[i]){opt.acum=acum;opt.dimValue=dimArray[i];}
if(border){ctx.save();ctx.lineWidth=2;ctx.strokeStyle=border.color;ctx.restore();}
if(label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textBaseline='middle';acumValueLabel=valAcum;if(showLabels(node.name,valAcum,node)){ctx.textAlign='left';ctx.fillText(stringArray[i],(bottomWidthLabel / 2)+labelOffset+labelOffsetRight,y-newDimArray[i].position-label.size / 2);ctx.textAlign='right';ctx.fillText(valuelabelArray[i],(-bottomWidthLabel / 2)-labelOffset-labelOffsetLeft,y-newDimArray[i].position-label.size / 2);}
ctx.restore();}
acum+=(dimArray[i]||0);valAcum+=(valueArray[i]||0);}}},'contains':function(node,mpos){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),algnPos=this.getAlignedPos(pos,width,height),x=algnPos.x,y=algnPos.y,dimArray=node.getData('dimArray'),config=node.getData('config'),st=node.getData('st'),rx=mpos.x-x,horz=config.orientation=='horizontal',minWidth=width*.25;ratio=.65,canvas=node.getData('canvas'),size=canvas.getSize(),offsetY=st.config.offsetY;if(mpos.y>y||mpos.y<y-height){return false;}
var newY=Math.abs(mpos.y+offsetY);var bound=minWidth+(newY*ratio);var boundLeft=-bound/2;var boundRight=bound/2;if(mpos.x<boundLeft||mpos.x>boundRight){return false;}
for(var i=0,l=dimArray.length,acum=(horz?x:y);i<l;i++){var dimi=dimArray[i];var url=Url.decode(node.getData('linkArray')[i]);acum-=dimi;var intersec=acum;if(mpos.y>=intersec){return{'name':node.getData('stringArray')[i],'color':node.getData('colorArray')[i],'value':node.getData('valueArray')[i],'percentage':node.getData('percentageArray')[i],'valuelabel':node.getData('valuelabelArray')[i],'link':url,'label':node.name};}}
return false;}}});$jit.FunnelChart=new Class({st:null,colors:["#004b9c","#9c0079","#9c0033","#28009c","#9c0000","#7d009c","#001a9c","#00809c","#009c80","#009c42","#009c07","#469c00","#799c00","#9c9600","#9c5c00"],selected:{},busy:false,initialize:function(opt){this.controller=this.config=$.merge(Options("Canvas","Margin","Label","BarChart"),{Label:{type:'Native'}},opt);var showLabels=this.config.showLabels,typeLabels=$.type(showLabels),showAggregates=this.config.showAggregates,typeAggregates=$.type(showAggregates);this.config.showLabels=typeLabels=='function'?showLabels:$.lambda(showLabels);this.config.showAggregates=typeAggregates=='function'?showAggregates:$.lambda(showAggregates);Options.Fx.clearCanvas=false;this.initializeViz();},initializeViz:function(){var config=this.config,that=this;var nodeType=config.type.split(":")[0],horz=config.orientation=='horizontal',nodeLabels={};var st=new $jit.ST({injectInto:config.injectInto,orientation:horz?'left':'bottom',levelDistance:0,background:config.background,renderBackground:config.renderBackground,backgroundColor:config.backgroundColor,colorStop1:config.colorStop1,colorStop2:config.colorStop2,siblingOffset:config.segmentOffset,subtreeOffset:0,withLabels:config.Label.type!='Native',useCanvas:config.useCanvas,Label:{type:config.Label.type},Node:{overridable:true,type:'funnelchart-'+nodeType,align:'left',width:1,height:1},Edge:{type:'none'},Tips:{enable:config.Tips.enable,type:'Native',force:true,onShow:function(tip,node,contains){var elem=contains;config.Tips.onShow(tip,elem,node);if(elem.link!='undefined'&&elem.link!=''){document.body.style.cursor='pointer';}},onHide:function(call){document.body.style.cursor='default';}},Events:{enable:true,type:'Native',onClick:function(node,eventInfo,evt){if(!config.Events.enable)return;var elem=eventInfo.getContains();config.Events.onClick(elem,eventInfo,evt);},onMouseMove:function(node,eventInfo,evt){if(!config.hoveredColor)return;if(node){var elem=eventInfo.getContains();that.select(node.id,elem.name,elem.index);}else{that.select(false,false,false);}}},onCreateLabel:function(domElement,node){var labelConf=config.Label,valueArray=node.getData('valueArray'),idArray=node.getData('idArray'),valuelabelArray=node.getData('valuelabelArray'),stringArray=node.getData('stringArray');size=st.canvas.getSize()
prefix=$.time();for(var i=0,l=valueArray.length;i<l;i++){var nlbs={wrapper:document.createElement('div'),valueLabel:document.createElement('div'),label:document.createElement('div')};var wrapper=nlbs.wrapper,label=nlbs.label,valueLabel=nlbs.valueLabel,wrapperStyle=wrapper.style,labelStyle=label.style,valueLabelStyle=valueLabel.style;nodeLabels[idArray[i]]=nlbs;wrapper.appendChild(label);wrapper.appendChild(valueLabel);wrapperStyle.position='relative';wrapperStyle.overflow='visible';wrapperStyle.fontSize=labelConf.size+'px';wrapperStyle.fontFamily=labelConf.family;wrapperStyle.color=labelConf.color;wrapperStyle.textAlign='center';wrapperStyle.width=size.width+'px';valueLabelStyle.position=labelStyle.position='absolute';valueLabelStyle.left=labelStyle.left='0px';valueLabelStyle.width=(size.width/3)+'px';valueLabelStyle.textAlign='right';label.innerHTML=stringArray[i];valueLabel.innerHTML=valuelabelArray[i];domElement.id=prefix+'funnel';domElement.style.width=size.width+'px';domElement.appendChild(wrapper);}},onPlaceLabel:function(domElement,node){var dimArray=node.getData('dimArray'),idArray=node.getData('idArray'),valueArray=node.getData('valueArray'),valuelabelArray=node.getData('valuelabelArray'),stringArray=node.getData('stringArray');size=st.canvas.getSize(),pos=node.pos.getc(true),domElement.style.left="0px",domElement.style.top="0px",minWidth=node.getData('width')*.25,ratio=.65,pos=node.pos.getc(true),labelConf=config.Label;for(var i=0,l=valueArray.length,acum=0;i<l;i++){var labels=nodeLabels[idArray[i]],wrapperStyle=labels.wrapper.style,labelStyle=labels.label.style,valueLabelStyle=labels.valueLabel.style;var bottomWidth=minWidth+(acum*ratio);font=parseInt(wrapperStyle.fontSize,10),domStyle=domElement.style;wrapperStyle.top=(pos.y+size.height/2)-acum-labelConf.size+"px";valueLabelStyle.left=(size.width/2)-(bottomWidth/2)-config.labelOffset-(size.width/3)+'px';labelStyle.left=(size.width/2)+(bottomWidth/2)+config.labelOffset+'px';;acum+=(dimArray[i]||0);}}});var size=st.canvas.getSize(),margin=config.Margin;title=config.Title;subtitle=config.Subtitle;st.config.offsetY=-size.height/2+margin.bottom
+(config.showLabels&&(config.labelOffset+config.Label.size))+(subtitle.text?subtitle.size+subtitle.offset:0);st.config.offsetX=(margin.right-margin.left)/2;this.st=st;this.canvas=this.st.canvas;},renderTitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,label=config.Label,title=config.Title;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' bold '+' '+title.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(title.text,-size.width/2+margin.left,-size.height/2+margin.top);}},renderSubtitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,label=config.Label,subtitle=config.Subtitle;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' '+subtitle.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(subtitle.text,-size.width/2+margin.left,size.height/2-margin.bottom-subtitle.size);}},renderDropShadow:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,horz=config.orientation=='horizontal',label=config.Label,title=config.Title,shadowThickness=4,subtitle=config.Subtitle,ctx=canvas.getCtx(),minwidth=(size.width/8)*.25,marginHeight=(title.text?title.size+title.offset:0)+(subtitle.text?subtitle.size+subtitle.offset:0)+margin.top+margin.bottom,topMargin=(title.text?title.size+title.offset:0)+margin.top,height=size[horz?'width':'height']-(horz?marginWidth:marginHeight)
-(config.showLabels&&(config.Label.size+config.labelOffset)),ratio=.65,topWidth=minwidth+((height+(shadowThickness*4))*ratio);topY=(-size.height/2)+topMargin-shadowThickness;bottomY=(-size.height/2)+topMargin+height+shadowThickness;bottomWidth=minwidth+shadowThickness;ctx.beginPath();ctx.fillStyle="rgba(0,0,0,.2)";ctx.moveTo(0,topY);ctx.lineTo(-topWidth/2,topY);ctx.lineTo(-bottomWidth/2,bottomY);ctx.lineTo(bottomWidth/2,bottomY);ctx.lineTo(topWidth/2,topY);ctx.closePath();ctx.fill();},renderBackground:function(){var canvas=this.canvas,config=this.config,backgroundColor=config.backgroundColor,size=canvas.getSize(),ctx=canvas.getCtx();ctx.fillStyle=backgroundColor;ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);},clear:function(){var canvas=this.canvas;var ctx=canvas.getCtx(),size=canvas.getSize();ctx.fillStyle="rgba(255,255,255,0)";ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);ctx.clearRect(-size.width/2,-size.height/2,size.width,size.height);},resizeGraph:function(json,width){var canvas=this.canvas,size=canvas.getSize(),config=this.config,orgHeight=size.height;canvas.resize(width,orgHeight);if(typeof FlashCanvas=="undefined"){canvas.clear();}else{this.clear();}
this.loadJSON(json);},loadJSON:function(json){if(this.busy)return;this.busy=true;var prefix=$.time(),ch=[],st=this.st,name=$.splat(json.label),color=$.splat(json.color||this.colors),config=this.config,canvas=this.canvas,gradient=!!config.type.split(":")[1],animate=config.animate,title=config.Title,subtitle=config.Subtitle,renderBackground=config.renderBackground,horz=config.orientation=='horizontal',that=this,colorLength=color.length,nameLength=name.length,totalValue=0;for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];var valArray=$.splat(val.values);totalValue+=parseFloat(valArray.sum());}
var nameArray=new Array();var idArray=new Array();var valArray=new Array();var valuelabelArray=new Array();var linkArray=new Array();var titleArray=new Array();var percentageArray=new Array();for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];nameArray[i]=$.splat(val.label);idArray[i]=$.splat(prefix+val.label);valArray[i]=$.splat(val.values);valuelabelArray[i]=$.splat(val.valuelabels);linkArray[i]=$.splat(val.links);titleArray[i]=$.splat(val.titles);percentageArray[i]=(($.splat(val.values).sum()/totalValue)*100).toFixed(1);var acum=0;}
nameArray.reverse();valArray.reverse();valuelabelArray.reverse();linkArray.reverse();titleArray.reverse();percentageArray.reverse();ch.push({'id':prefix+val.label,'name':val.label,'data':{'value':valArray,'$idArray':idArray,'$linkArray':linkArray,'$titleArray':titleArray,'$valueArray':valArray,'$valuelabelArray':valuelabelArray,'$colorArray':color,'$colorMono':$.splat(color[i%colorLength]),'$stringArray':(typeof FlashCanvas=="undefined")?nameArray:name.reverse(),'$gradient':gradient,'$config':config,'$percentageArray':percentageArray,'$canvas':canvas,'$st':st},'children':[]});var root={'id':prefix+'$root','name':'','data':{'$type':'none','$width':1,'$height':1},'children':ch};st.loadJSON(root);this.normalizeDims();if(renderBackground){this.renderBackground();}
if(!animate&&title.text){this.renderTitle();}
if(!animate&&subtitle.text){this.renderSubtitle();}
if(typeof FlashCanvas=="undefined"){this.renderDropShadow();}
st.compute();st.select(st.root);if(animate){if(horz){st.fx.animate({modes:['node-property:width:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});}else{st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;}});}}else{this.busy=false;}},updateJSON:function(json,onComplete){if(this.busy)return;this.busy=true;var st=this.st;var graph=st.graph;var values=json.values;var animate=this.config.animate;var that=this;var horz=this.config.orientation=='horizontal';$.each(values,function(v){var n=graph.getByName(v.label);if(n){n.setData('valueArray',$.splat(v.values));if(json.label){n.setData('stringArray',$.splat(json.label));}}});this.normalizeDims();st.compute();st.select(st.root);if(animate){if(horz){st.fx.animate({modes:['node-property:width:dimArray'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}else{st.fx.animate({modes:['node-property:height:dimArray'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}}},select:function(id,name){if(!this.config.hoveredColor)return;var s=this.selected;if(s.id!=id||s.name!=name){s.id=id;s.name=name;s.color=this.config.hoveredColor;this.st.graph.eachNode(function(n){if(id==n.id){n.setData('border',s);}else{n.setData('border',false);}});this.st.plot();}},getLegend:function(){var legend=new Array();var name=new Array();var color=new Array();var n;this.st.graph.getNode(this.st.root).eachAdjacency(function(adj){n=adj.nodeTo;});var colors=n.getData('colorArray'),len=colors.length;$.each(n.getData('stringArray'),function(s,i){color[i]=colors[i%len];name[i]=s;});legend['name']=name;legend['color']=color;return legend;},getMaxValue:function(){var maxValue=0,stacked=true;this.st.graph.eachNode(function(n){var valArray=n.getData('valueArray'),acum=0;if(!valArray)return;if(stacked){$.each(valArray,function(v){acum+=+v;});}else{acum=Math.max.apply(null,valArray);}
maxValue=maxValue>acum?maxValue:acum;});return maxValue;},setBarType:function(type){this.config.type=type;this.st.config.Node.type='funnelchart-'+type.split(':')[0];},normalizeDims:function(){var root=this.st.graph.getNode(this.st.root),l=0;root.eachAdjacency(function(){l++;});var maxValue=this.getMaxValue()||1,size=this.st.canvas.getSize(),config=this.config,margin=config.Margin,title=config.Title,subtitle=config.Subtitle,marginWidth=margin.left+margin.right,marginHeight=(title.text?title.size+title.offset:0)+(subtitle.text?subtitle.size+subtitle.offset:0)+margin.top+margin.bottom,horz=config.orientation=='horizontal',animate=config.animate,height=size[horz?'width':'height']-(horz?marginWidth:marginHeight)
-(config.showLabels&&(config.Label.size+config.labelOffset)),dim1=horz?'height':'width',dim2=horz?'width':'height';minWidth=size.width/8;this.st.graph.eachNode(function(n){var acum=0,animateValue=[];$.each(n.getData('valueArray'),function(v){acum+=+v;animateValue.push(0);});n.setData(dim1,minWidth);if(animate){n.setData(dim2,acum*height / maxValue,'end');n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return n*height / maxValue;}),'end');var dimArray=n.getData('dimArray');if(!dimArray){n.setData('dimArray',animateValue);}}else{n.setData(dim2,acum*height / maxValue);n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return n*height / maxValue;}));}});}});Options.PieChart={$extend:true,animate:true,offset:25,sliceOffset:0,labelOffset:3,type:'stacked',labelType:'name',hoveredColor:'#9fd4ff',Events:{enable:false,onClick:$.empty},Tips:{enable:false,onShow:$.empty,onHide:$.empty},showLabels:true,resizeLabels:false,updateHeights:false};Layouts.Radial=new Class({compute:function(property){var prop=$.splat(property||['current','start','end']);NodeDim.compute(this.graph,prop,this.config);this.graph.computeLevels(this.root,0,"ignore");var lengthFunc=this.createLevelDistanceFunc();this.computeAngularWidths(prop);this.computePositions(prop,lengthFunc);},computePositions:function(property,getLength){var propArray=property;var graph=this.graph;var root=graph.getNode(this.root);var parent=this.parent;var config=this.config;for(var i=0,l=propArray.length;i<l;i++){var pi=propArray[i];root.setPos($P(0,0),pi);root.setData('span',Math.PI*2,pi);}
root.angleSpan={begin:0,end:2*Math.PI};graph.eachBFS(this.root,function(elem){var angleSpan=elem.angleSpan.end-elem.angleSpan.begin;var angleInit=elem.angleSpan.begin;var len=getLength(elem);var totalAngularWidths=0,subnodes=[],maxDim={};elem.eachSubnode(function(sib){totalAngularWidths+=sib._treeAngularWidth;for(var i=0,l=propArray.length;i<l;i++){var pi=propArray[i],dim=sib.getData('dim',pi);maxDim[pi]=(pi in maxDim)?(dim>maxDim[pi]?dim:maxDim[pi]):dim;}
subnodes.push(sib);},"ignore");if(parent&&parent.id==elem.id&&subnodes.length>0&&subnodes[0].dist){subnodes.sort(function(a,b){return(a.dist>=b.dist)-(a.dist<=b.dist);});}
for(var k=0,ls=subnodes.length;k<ls;k++){var child=subnodes[k];if(!child._flag){var angleProportion=child._treeAngularWidth / totalAngularWidths*angleSpan;var theta=angleInit+angleProportion / 2;for(var i=0,l=propArray.length;i<l;i++){var pi=propArray[i];child.setPos($P(theta,len),pi);child.setData('span',angleProportion,pi);child.setData('dim-quotient',child.getData('dim',pi)/ maxDim[pi],pi);}
child.angleSpan={begin:angleInit,end:angleInit+angleProportion};angleInit+=angleProportion;}}},"ignore");},setAngularWidthForNodes:function(prop){this.graph.eachBFS(this.root,function(elem,i){var diamValue=elem.getData('angularWidth',prop[0])||5;elem._angularWidth=diamValue / i;},"ignore");},setSubtreesAngularWidth:function(){var that=this;this.graph.eachNode(function(elem){that.setSubtreeAngularWidth(elem);},"ignore");},setSubtreeAngularWidth:function(elem){var that=this,nodeAW=elem._angularWidth,sumAW=0;elem.eachSubnode(function(child){that.setSubtreeAngularWidth(child);sumAW+=child._treeAngularWidth;},"ignore");elem._treeAngularWidth=Math.max(nodeAW,sumAW);},computeAngularWidths:function(prop){this.setAngularWidthForNodes(prop);this.setSubtreesAngularWidth();}});$jit.Sunburst=new Class({Implements:[Loader,Extras,Layouts.Radial],initialize:function(controller){var $Sunburst=$jit.Sunburst;var config={interpolation:'linear',levelDistance:100,Node:{'type':'multipie','height':0},Edge:{'type':'none'},Label:{textAlign:'start',textBaseline:'middle'}};this.controller=this.config=$.merge(Options("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label"),config,controller);var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{if(canvasConfig.background){canvasConfig.background=$.merge({type:'Fade',colorStop1:this.config.colorStop1,colorStop2:this.config.colorStop2},canvasConfig.background);}
this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':false,'Node':{'selected':false,'exist':true,'drawn':true}};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new $Sunburst.Label[canvasConfig.Label.type](this);this.fx=new $Sunburst.Plot(this,$Sunburst);this.op=new $Sunburst.Op(this);this.json=null;this.root=null;this.rotated=null;this.busy=false;this.initializeExtras();},createLevelDistanceFunc:function(){var ld=this.config.levelDistance;return function(elem){return(elem._depth+1)*ld;};},refresh:function(){this.compute();this.plot();},reposition:function(){this.compute('end');},rotate:function(node,method,opt){var theta=node.getPos(opt.property||'current').getp(true).theta;this.rotated=node;this.rotateAngle(-theta,method,opt);},rotateAngle:function(theta,method,opt){var that=this;var options=$.merge(this.config,opt||{},{modes:['polar']});var prop=opt.property||(method==="animate"?'end':'current');if(method==='animate'){this.fx.animation.pause();}
this.graph.eachNode(function(n){var p=n.getPos(prop);p.theta+=theta;if(p.theta<0){p.theta+=Math.PI*2;}});if(method=='animate'){this.fx.animate(options);}else if(method=='replot'){this.fx.plot();this.busy=false;}},plot:function(){this.fx.plot();}});$jit.Sunburst.$extend=true;(function(Sunburst){Sunburst.Op=new Class({Implements:Graph.Op});Sunburst.Plot=new Class({Implements:Graph.Plot});Sunburst.Label={};Sunburst.Label.Native=new Class({Implements:Graph.Label.Native,initialize:function(viz){this.viz=viz;this.label=viz.config.Label;this.config=viz.config;},renderLabel:function(canvas,node,controller){var span=node.getData('span');if(span<Math.PI /2&&Math.tan(span)*this.config.levelDistance*node._depth<10){return;}
var ctx=canvas.getCtx();var measure=ctx.measureText(node.name);if(node.id==this.viz.root){var x=-measure.width / 2,y=0,thetap=0;var ld=0;}else{var indent=5;var ld=controller.levelDistance-indent;var clone=node.pos.clone();clone.rho+=indent;var p=clone.getp(true);var ct=clone.getc(true);var x=ct.x,y=ct.y;var pi=Math.PI;var cond=(p.theta>pi / 2&&p.theta<3*pi / 2);var thetap=cond?p.theta+pi:p.theta;if(cond){x-=Math.abs(Math.cos(p.theta)*measure.width);y+=Math.sin(p.theta)*measure.width;}else if(node.id==this.viz.root){x-=measure.width / 2;}}
ctx.save();ctx.translate(x,y);ctx.rotate(thetap);ctx.fillText(node.name,0,0);ctx.restore();}});Sunburst.Label.SVG=new Class({Implements:Graph.Label.SVG,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),viz=this.viz,canvas=this.viz.canvas;var radius=canvas.getSize();var labelPos={x:Math.round(pos.x+radius.width / 2),y:Math.round(pos.y+radius.height / 2)};tag.setAttribute('x',labelPos.x);tag.setAttribute('y',labelPos.y);var bb=tag.getBBox();if(bb){var x=tag.getAttribute('x');var y=tag.getAttribute('y');var p=node.pos.getp(true);var pi=Math.PI;var cond=(p.theta>pi / 2&&p.theta<3*pi / 2);if(cond){tag.setAttribute('x',x-bb.width);tag.setAttribute('y',y-bb.height);}else if(node.id==viz.root){tag.setAttribute('x',x-bb.width / 2);}
var thetap=cond?p.theta+pi:p.theta;if(node._depth)
tag.setAttribute('transform','rotate('+thetap*360 /(2*pi)+' '+x
+' '+y+')');}
controller.onPlaceLabel(tag,node);}});Sunburst.Label.HTML=new Class({Implements:Graph.Label.HTML,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.clone(),canvas=this.viz.canvas,height=node.getData('height'),ldist=((height||node._depth==0)?height:this.viz.config.levelDistance)/2,radius=canvas.getSize();pos.rho+=ldist;pos=pos.getc(true);var labelPos={x:Math.round(pos.x+radius.width / 2),y:Math.round(pos.y+radius.height / 2)};var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.display=this.fitsInCanvas(labelPos,canvas)?'':'none';controller.onPlaceLabel(tag,node);}});Sunburst.Plot.NodeTypes=new Class({'none':{'render':$.empty,'contains':$.lambda(false),'anglecontains':function(node,pos){var span=node.getData('span')/ 2,theta=node.pos.theta;var begin=theta-span,end=theta+span;if(begin<0)
begin+=Math.PI*2;var atan=Math.atan2(pos.y,pos.x);if(atan<0)
atan+=Math.PI*2;if(begin>end){return(atan>begin&&atan<=Math.PI*2)||atan<end;}else{return atan>begin&&atan<end;}},'anglecontainsgauge':function(node,pos){var span=node.getData('span')/ 2,theta=node.pos.theta;var config=node.getData('config');var ld=this.config.levelDistance;var yOffset=pos.y-(ld/2);var begin=((theta-span)/2)+Math.PI,end=((theta+span)/2)+Math.PI;if(begin<0)
begin+=Math.PI*2;var atan=Math.atan2(yOffset,pos.x);if(atan<0)
atan+=Math.PI*2;if(begin>end){return(atan>begin&&atan<=Math.PI*2)||atan<end;}else{return atan>begin&&atan<end;}}},'pie':{'render':function(node,canvas){var span=node.getData('span')/ 2,theta=node.pos.theta;var begin=theta-span,end=theta+span;var polarNode=node.pos.getp(true);var polar=new Polar(polarNode.rho,begin);var p1coord=polar.getc(true);polar.theta=end;var p2coord=polar.getc(true);var ctx=canvas.getCtx();ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(p1coord.x,p1coord.y);ctx.moveTo(0,0);ctx.lineTo(p2coord.x,p2coord.y);ctx.moveTo(0,0);ctx.arc(0,0,polarNode.rho*node.getData('dim-quotient'),begin,end,false);ctx.fill();},'contains':function(node,pos){if(this.nodeTypes['none'].anglecontains.call(this,node,pos)){var rho=Math.sqrt(pos.x*pos.x+pos.y*pos.y);var ld=this.config.levelDistance,d=node._depth;return(rho<=ld*d);}
return false;}},'multipie':{'render':function(node,canvas){var height=node.getData('height');var ldist=height?height:this.config.levelDistance;var span=node.getData('span')/ 2,theta=node.pos.theta;var begin=theta-span,end=theta+span;var polarNode=node.pos.getp(true);var polar=new Polar(polarNode.rho,begin);var p1coord=polar.getc(true);polar.theta=end;var p2coord=polar.getc(true);polar.rho+=ldist;var p3coord=polar.getc(true);polar.theta=begin;var p4coord=polar.getc(true);var ctx=canvas.getCtx();ctx.moveTo(0,0);ctx.beginPath();ctx.arc(0,0,polarNode.rho,begin,end,false);ctx.arc(0,0,polarNode.rho+ldist,end,begin,true);ctx.moveTo(p1coord.x,p1coord.y);ctx.lineTo(p4coord.x,p4coord.y);ctx.moveTo(p2coord.x,p2coord.y);ctx.lineTo(p3coord.x,p3coord.y);ctx.fill();if(node.collapsed){ctx.save();ctx.lineWidth=2;ctx.moveTo(0,0);ctx.beginPath();ctx.arc(0,0,polarNode.rho+ldist+5,end-0.01,begin+0.01,true);ctx.stroke();ctx.restore();}},'contains':function(node,pos){if(this.nodeTypes['none'].anglecontains.call(this,node,pos)){var rho=Math.sqrt(pos.x*pos.x+pos.y*pos.y);var height=node.getData('height');var ldist=height?height:this.config.levelDistance;var ld=this.config.levelDistance,d=node._depth;return(rho>=ld*d)&&(rho<=(ld*d+ldist));}
return false;}},'gradient-multipie':{'render':function(node,canvas){var ctx=canvas.getCtx();var height=node.getData('height');var ldist=height?height:this.config.levelDistance;var radialGradient=ctx.createRadialGradient(0,0,node.getPos().rho,0,0,node.getPos().rho+ldist);var colorArray=$.hexToRgb(node.getData('color')),ans=[];$.each(colorArray,function(i){ans.push(parseInt(i*0.5,10));});var endColor=$.rgbToHex(ans);radialGradient.addColorStop(0,endColor);radialGradient.addColorStop(1,node.getData('color'));ctx.fillStyle=radialGradient;this.nodeTypes['multipie'].render.call(this,node,canvas);},'contains':function(node,pos){return this.nodeTypes['multipie'].contains.call(this,node,pos);}},'gradient-pie':{'render':function(node,canvas){var ctx=canvas.getCtx();var radialGradient=ctx.createRadialGradient(0,0,0,0,0,node.getPos().rho);var colorArray=$.hexToRgb(node.getData('color')),ans=[];$.each(colorArray,function(i){ans.push(parseInt(i*0.5,10));});var endColor=$.rgbToHex(ans);radialGradient.addColorStop(1,endColor);radialGradient.addColorStop(0,node.getData('color'));ctx.fillStyle=radialGradient;this.nodeTypes['pie'].render.call(this,node,canvas);},'contains':function(node,pos){return this.nodeTypes['pie'].contains.call(this,node,pos);}}});Sunburst.Plot.EdgeTypes=new Class({'none':$.empty,'line':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);this.edgeHelper.line.render(from,to,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);return this.edgeHelper.line.contains(from,to,pos,this.edge.epsilon);}},'arrow':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),dim=adj.getData('dim'),direction=adj.data.$direction,inv=(direction&&direction.length>1&&direction[0]!=adj.nodeFrom.id);this.edgeHelper.arrow.render(from,to,dim,inv,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);return this.edgeHelper.arrow.contains(from,to,pos,this.edge.epsilon);}},'hyperline':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(),to=adj.nodeTo.pos.getc(),dim=Math.max(from.norm(),to.norm());this.edgeHelper.hyperline.render(from.$scale(1/dim),to.$scale(1/dim),dim,canvas);},'contains':$.lambda(false)}});})($jit.Sunburst);$jit.Sunburst.Plot.NodeTypes.implement({'piechart-stacked':{'render':function(node,canvas){var pos=node.pos.getp(true),dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),colorArray=node.getData('colorArray'),colorLength=colorArray.length,stringArray=node.getData('stringArray'),span=node.getData('span')/ 2,theta=node.pos.theta,begin=theta-span,end=theta+span,polar=new Polar;var ctx=canvas.getCtx(),opt={},gradient=node.getData('gradient'),border=node.getData('border'),config=node.getData('config'),showLabels=config.showLabels,resizeLabels=config.resizeLabels,label=config.Label;var xpos=config.sliceOffset*Math.cos((begin+end)/2);var ypos=config.sliceOffset*Math.sin((begin+end)/2);if(colorArray&&dimArray&&stringArray){for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){var dimi=dimArray[i],colori=colorArray[i%colorLength];if(dimi<=0)continue;ctx.fillStyle=ctx.strokeStyle=colori;if(gradient&&dimi){var radialGradient=ctx.createRadialGradient(xpos,ypos,acum+config.sliceOffset,xpos,ypos,acum+dimi+config.sliceOffset);var colorRgb=$.hexToRgb(colori),ans=$.map(colorRgb,function(i){return(i*0.8)>>0;}),endColor=$.rgbToHex(ans);radialGradient.addColorStop(0,colori);radialGradient.addColorStop(0.5,colori);radialGradient.addColorStop(1,endColor);ctx.fillStyle=radialGradient;}
polar.rho=acum+config.sliceOffset;polar.theta=begin;var p1coord=polar.getc(true);polar.theta=end;var p2coord=polar.getc(true);polar.rho+=dimi;var p3coord=polar.getc(true);polar.theta=begin;var p4coord=polar.getc(true);ctx.beginPath();ctx.arc(xpos,ypos,acum+.01,begin,end,false);ctx.arc(xpos,ypos,acum+dimi+.01,end,begin,true);ctx.fill();if(border&&border.name==stringArray[i]){opt.acum=acum;opt.dimValue=dimArray[i];opt.begin=begin;opt.end=end;}
acum+=(dimi||0);valAcum+=(valueArray[i]||0);}
if(border){ctx.save();ctx.globalCompositeOperation="source-over";ctx.lineWidth=2;ctx.strokeStyle=border.color;var s=begin<end?1:-1;ctx.beginPath();ctx.arc(xpos,ypos,opt.acum+.01+1,opt.begin,opt.end,false);ctx.arc(xpos,ypos,opt.acum+opt.dimValue+.01-1,opt.end,opt.begin,true);ctx.closePath();ctx.stroke();ctx.restore();}
if(showLabels&&label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;var scale=resizeLabels?node.getData('normalizedDim'):1,fontSize=(label.size*scale)>>0;fontSize=fontSize<+resizeLabels?+resizeLabels:fontSize;ctx.font=label.style+' '+fontSize+'px '+label.family;ctx.textBaseline='middle';ctx.textAlign='center';polar.rho=acum+config.labelOffset+config.sliceOffset;polar.theta=node.pos.theta;var cart=polar.getc(true);ctx.fillText(node.name,cart.x,cart.y);ctx.restore();}}},'contains':function(node,pos){if(this.nodeTypes['none'].anglecontains.call(this,node,pos)){var rho=Math.sqrt(pos.x*pos.x+pos.y*pos.y);var ld=this.config.levelDistance,d=node._depth;var config=node.getData('config');if(rho<=ld*d+config.sliceOffset){var dimArray=node.getData('dimArray');for(var i=0,l=dimArray.length,acum=config.sliceOffset;i<l;i++){var dimi=dimArray[i];if(rho>=acum&&rho<=acum+dimi){return{name:node.getData('stringArray')[i],color:node.getData('colorArray')[i],value:node.getData('valueArray')[i],label:node.name};}
acum+=dimi;}}
return false;}
return false;}},'piechart-basic':{'render':function(node,canvas){var pos=node.pos.getp(true),dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),colorArray=node.getData('colorMono'),colorLength=colorArray.length,stringArray=node.getData('stringArray'),percentage=node.getData('percentage'),iteration=node.getData('iteration'),span=node.getData('span')/ 2,theta=node.pos.theta,begin=theta-span,end=theta+span,polar=new Polar;var ctx=canvas.getCtx(),opt={},gradient=node.getData('gradient'),border=node.getData('border'),config=node.getData('config'),renderSubtitle=node.getData('renderSubtitle'),renderBackground=config.renderBackground,showLabels=config.showLabels,resizeLabels=config.resizeLabels,label=config.Label;var xpos=config.sliceOffset*Math.cos((begin+end)/2);var ypos=config.sliceOffset*Math.sin((begin+end)/2);if(iteration==0&&typeof FlashCanvas!="undefined"&&renderBackground){backgroundColor=config.backgroundColor,size=canvas.getSize();ctx.save();ctx.fillStyle=backgroundColor;ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);var margin=config.Margin,title=config.Title,subtitle=config.Subtitle;ctx.fillStyle=title.color;ctx.textAlign='left';if(title.text!=""){ctx.font=label.style+' bold '+' '+title.size+'px '+label.family;ctx.moveTo(0,0);if(label.type=='Native'){ctx.fillText(title.text,-size.width/2+margin.left,-size.height/2+margin.top);}}
if(subtitle.text!=""){ctx.font=label.style+' '+subtitle.size+'px '+label.family;if(label.type=='Native'){ctx.fillText(subtitle.text,-size.width/2+margin.left,size.height/2-margin.bottom);}}
ctx.restore();}
if(colorArray&&dimArray&&stringArray){for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){var dimi=dimArray[i],colori=colorArray[i%colorLength];if(dimi<=0)continue;ctx.fillStyle=ctx.strokeStyle=colori;polar.rho=acum+config.sliceOffset;polar.theta=begin;var p1coord=polar.getc(true);polar.theta=end;var p2coord=polar.getc(true);polar.rho+=dimi;var p3coord=polar.getc(true);polar.theta=begin;var p4coord=polar.getc(true);if(typeof FlashCanvas=="undefined"){ctx.beginPath();ctx.fillStyle="rgba(0,0,0,.2)";ctx.arc(xpos,ypos,acum+.01,begin,end,false);ctx.arc(xpos,ypos,acum+dimi+4+.01,end,begin,true);ctx.fill();if(gradient&&dimi){var radialGradient=ctx.createRadialGradient(xpos,ypos,acum+config.sliceOffset,xpos,ypos,acum+dimi+config.sliceOffset);var colorRgb=$.hexToRgb(colori),endColor=$.map(colorRgb,function(i){return(i*0.85)>>0;}),endColor2=$.map(colorRgb,function(i){return(i*0.7)>>0;});radialGradient.addColorStop(0,'rgba('+colorRgb+',1)');radialGradient.addColorStop(.7,'rgba('+colorRgb+',1)');radialGradient.addColorStop(.98,'rgba('+endColor+',1)');radialGradient.addColorStop(1,'rgba('+endColor2+',1)');ctx.fillStyle=radialGradient;}}
ctx.beginPath();ctx.arc(xpos,ypos,acum+.01,begin,end,false);ctx.arc(xpos,ypos,acum+dimi+.01,end,begin,true);ctx.fill();if(border&&border.name==stringArray[i]){opt.acum=acum;opt.dimValue=dimArray[i];opt.begin=begin;opt.end=end;opt.sliceValue=valueArray[i];}
acum+=(dimi||0);valAcum+=(valueArray[i]||0);}
if(border){ctx.save();ctx.globalCompositeOperation="source-over";ctx.lineWidth=2;ctx.strokeStyle=border.color;var s=begin<end?1:-1;ctx.beginPath();ctx.arc(xpos,ypos,opt.acum+.01+1,opt.begin,opt.end,false);ctx.arc(xpos,ypos,opt.acum+opt.dimValue+.01-1,opt.end,opt.begin,true);ctx.closePath();ctx.stroke();ctx.restore();}
if(showLabels&&label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;var scale=resizeLabels?node.getData('normalizedDim'):1,fontSize=(label.size*scale)>>0;fontSize=fontSize<+resizeLabels?+resizeLabels:fontSize;ctx.font=label.style+' '+fontSize+'px '+label.family;ctx.textBaseline='middle';ctx.textAlign='center';pi=Math.PI;angle=theta*360 /(2*pi);polar.rho=acum+config.labelOffset+config.sliceOffset;polar.theta=node.pos.theta;var cart=polar.getc(true);if(((angle>=225&&angle<=315)||(angle<=135&&angle>=45))&&percentage<=5){}else{if(config.labelType=='name'){ctx.fillText(node.name,cart.x,cart.y);}else{ctx.fillText(node.data.valuelabel,cart.x,cart.y);}}
ctx.restore();}}},'contains':function(node,pos){if(this.nodeTypes['none'].anglecontains.call(this,node,pos)){var rho=Math.sqrt(pos.x*pos.x+pos.y*pos.y);var ld=this.config.levelDistance,d=node._depth;var config=node.getData('config');if(rho<=ld*d+config.sliceOffset){var dimArray=node.getData('dimArray');for(var i=0,l=dimArray.length,acum=config.sliceOffset;i<l;i++){var dimi=dimArray[i];if(rho>=acum&&rho<=acum+dimi){var url=Url.decode(node.getData('linkArray')[i]);return{name:node.getData('stringArray')[i],link:url,color:node.getData('colorArray')[i],value:node.getData('valueArray')[i],percentage:node.getData('percentage'),valuelabel:node.getData('valuelabelsArray')[i],label:node.name};}
acum+=dimi;}}
return false;}
return false;}}});$jit.PieChart=new Class({sb:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(opt){this.controller=this.config=$.merge(Options("Canvas","PieChart","Label"),{Label:{type:'Native'}},opt);this.initializeViz();},initializeViz:function(){var config=this.config,that=this;var nodeType=config.type.split(":")[0];var sb=new $jit.Sunburst({injectInto:config.injectInto,useCanvas:config.useCanvas,withLabels:config.Label.type!='Native',background:config.background,renderBackground:config.renderBackground,backgroundColor:config.backgroundColor,colorStop1:config.colorStop1,colorStop2:config.colorStop2,Label:{type:config.Label.type},Node:{overridable:true,type:'piechart-'+nodeType,width:1,height:1},Edge:{type:'none'},Tips:{enable:config.Tips.enable,type:'Native',force:true,onShow:function(tip,node,contains){var elem=contains;config.Tips.onShow(tip,elem,node);if(elem.link!='undefined'&&elem.link!=''){document.body.style.cursor='pointer';}},onHide:function(){document.body.style.cursor='default';}},Events:{enable:true,type:'Native',onClick:function(node,eventInfo,evt){if(!config.Events.enable)return;var elem=eventInfo.getContains();config.Events.onClick(elem,eventInfo,evt);},onMouseMove:function(node,eventInfo,evt){if(!config.hoveredColor)return;if(node){var elem=eventInfo.getContains();that.select(node.id,elem.name,elem.index);}else{that.select(false,false,false);}}},onCreateLabel:function(domElement,node){var labelConf=config.Label;if(config.showLabels){var style=domElement.style;style.fontSize=labelConf.size+'px';style.fontFamily=labelConf.family;style.color=labelConf.color;style.textAlign='center';if(config.labelType=='name'){domElement.innerHTML=node.name;}else{domElement.innerHTML=(node.data.valuelabel!=undefined)?node.data.valuelabel:"";}
domElement.style.width='400px';}},onPlaceLabel:function(domElement,node){if(!config.showLabels)return;var pos=node.pos.getp(true),dimArray=node.getData('dimArray'),span=node.getData('span')/ 2,theta=node.pos.theta,begin=theta-span,end=theta+span,polar=new Polar;var showLabels=config.showLabels,resizeLabels=config.resizeLabels,label=config.Label;if(dimArray){for(var i=0,l=dimArray.length,acum=0;i<l;i++){acum+=dimArray[i];}
var scale=resizeLabels?node.getData('normalizedDim'):1,fontSize=(label.size*scale)>>0;fontSize=fontSize<+resizeLabels?+resizeLabels:fontSize;domElement.style.fontSize=fontSize+'px';polar.rho=acum+config.labelOffset+config.sliceOffset;polar.theta=(begin+end)/ 2;var pos=polar.getc(true);var radius=that.canvas.getSize();var labelPos={x:Math.round(pos.x+radius.width / 2),y:Math.round(pos.y+radius.height / 2)};domElement.style.left=(labelPos.x-200)+'px';domElement.style.top=labelPos.y+'px';}}});var size=sb.canvas.getSize(),min=Math.min;sb.config.levelDistance=min(size.width,size.height)/2
-config.offset-config.sliceOffset;this.sb=sb;this.canvas=this.sb.canvas;this.canvas.getCtx().globalCompositeOperation='lighter';},renderBackground:function(){var canvas=this.canvas,config=this.config,backgroundColor=config.backgroundColor,size=canvas.getSize(),ctx=canvas.getCtx();ctx.globalCompositeOperation="destination-over";ctx.fillStyle=backgroundColor;ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);},renderTitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,radius=this.sb.config.levelDistance,title=config.Title,label=config.Label,subtitle=config.Subtitle;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' bold '+' '+title.size+'px '+label.family;ctx.moveTo(0,0);if(label.type=='Native'){ctx.fillText(title.text,-size.width/2+margin.left,-size.height/2+margin.top);}},renderSubtitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,radius=this.sb.config.levelDistance,title=config.Title,label=config.Label,subtitle=config.Subtitle;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' '+subtitle.size+'px '+label.family;ctx.moveTo(0,0);if(label.type=='Native'){ctx.fillText(subtitle.text,-size.width/2+margin.left,size.height/2-margin.bottom);}},clear:function(){var canvas=this.canvas;var ctx=canvas.getCtx(),size=canvas.getSize();ctx.fillStyle="rgba(255,255,255,0)";ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);ctx.clearRect(-size.width/2,-size.height/2,size.width,size.height);},resizeGraph:function(json,width){var canvas=this.canvas,size=canvas.getSize(),config=this.config,orgHeight=size.height;canvas.resize(width,orgHeight);if(typeof FlashCanvas=="undefined"){canvas.clear();}else{this.clear();}
this.loadJSON(json);},loadJSON:function(json){var prefix=$.time(),ch=[],sb=this.sb,name=$.splat(json.label),nameLength=name.length,color=$.splat(json.color||this.colors),colorLength=color.length,config=this.config,renderBackground=config.renderBackground,title=config.Title,subtitle=config.Subtitle,gradient=!!config.type.split(":")[1],animate=config.animate,mono=nameLength==1;totalValue=0;for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];var valArray=$.splat(val.values);totalValue+=parseFloat(valArray.sum());}
for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];var valArray=$.splat(val.values);var percentage=(valArray.sum()/totalValue)*100;var linkArray=$.splat(val.links);var valuelabelsArray=$.splat(val.valuelabels);ch.push({'id':prefix+val.label,'name':val.label,'data':{'value':valArray,'valuelabel':valuelabelsArray,'$linkArray':linkArray,'$valuelabelsArray':valuelabelsArray,'$valueArray':valArray,'$colorArray':mono?$.splat(color[i%colorLength]):color,'$colorMono':$.splat(color[i%colorLength]),'$stringArray':name,'$gradient':gradient,'$config':config,'$iteration':i,'$percentage':percentage.toFixed(1),'$angularWidth':$.reduce(valArray,function(x,y){return x+y;})},'children':[]});}
var root={'id':prefix+'$root','name':'','data':{'$type':'none','$width':1,'$height':1},'children':ch};sb.loadJSON(root);this.normalizeDims();sb.refresh();if(title.text!=""){this.renderTitle();}
if(subtitle.text!=""){this.renderSubtitle();}
if(renderBackground&&typeof FlashCanvas=="undefined"){this.renderBackground();}
if(animate){sb.fx.animate({modes:['node-property:dimArray'],duration:1500});}},updateJSON:function(json,onComplete){if(this.busy)return;this.busy=true;var sb=this.sb;var graph=sb.graph;var values=json.values;var animate=this.config.animate;var that=this;$.each(values,function(v){var n=graph.getByName(v.label),vals=$.splat(v.values);if(n){n.setData('valueArray',vals);n.setData('angularWidth',$.reduce(vals,function(x,y){return x+y;}));if(json.label){n.setData('stringArray',$.splat(json.label));}}});this.normalizeDims();if(animate){sb.compute('end');sb.fx.animate({modes:['node-property:dimArray:span','linear'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}else{sb.refresh();}},select:function(id,name){if(!this.config.hoveredColor)return;var s=this.selected;if(s.id!=id||s.name!=name){s.id=id;s.name=name;s.color=this.config.hoveredColor;this.sb.graph.eachNode(function(n){if(id==n.id){n.setData('border',s);}else{n.setData('border',false);}});this.sb.plot();}},getLegend:function(){var legend=new Array();var name=new Array();var color=new Array();var n;this.sb.graph.getNode(this.sb.root).eachAdjacency(function(adj){n=adj.nodeTo;});var colors=n.getData('colorArray'),len=colors.length;$.each(n.getData('stringArray'),function(s,i){color[i]=colors[i%len];name[i]=s;});legend['name']=name;legend['color']=color;return legend;},getMaxValue:function(){var maxValue=0;this.sb.graph.eachNode(function(n){var valArray=n.getData('valueArray'),acum=0;$.each(valArray,function(v){acum+=+v;});maxValue=maxValue>acum?maxValue:acum;});return maxValue;},normalizeDims:function(){var root=this.sb.graph.getNode(this.sb.root),l=0;root.eachAdjacency(function(){l++;});var maxValue=this.getMaxValue()||1,config=this.config,animate=config.animate,rho=this.sb.config.levelDistance;this.sb.graph.eachNode(function(n){var acum=0,animateValue=[];$.each(n.getData('valueArray'),function(v){acum+=+v;animateValue.push(1);});var stat=(animateValue.length==1)&&!config.updateHeights;if(animate){n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return stat?rho:(n*rho / maxValue);}),'end');var dimArray=n.getData('dimArray');if(!dimArray){n.setData('dimArray',animateValue);}}else{n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return stat?rho:(n*rho / maxValue);}));}
n.setData('normalizedDim',acum / maxValue);});}});Options.GaugeChart={$extend:true,animate:true,offset:25,sliceOffset:0,labelOffset:3,type:'stacked',labelType:'name',hoveredColor:'#9fd4ff',Events:{enable:false,onClick:$.empty},Tips:{enable:false,onShow:$.empty,onHide:$.empty},showLabels:true,resizeLabels:false,updateHeights:false};$jit.Sunburst.Plot.NodeTypes.implement({'gaugechart-basic':{'render':function(node,canvas){var pos=node.pos.getp(true),dimArray=node.getData('dimArray'),valueArray=node.getData('valueArray'),valuelabelsArray=node.getData('valuelabelsArray'),gaugeTarget=node.getData('gaugeTarget'),nodeIteration=node.getData('nodeIteration'),nodeLength=node.getData('nodeLength'),colorArray=node.getData('colorMono'),colorLength=colorArray.length,stringArray=node.getData('stringArray'),span=node.getData('span')/ 2,theta=node.pos.theta,begin=((theta-span)/2)+Math.PI,end=((theta+span)/2)+Math.PI,polar=new Polar;var ctx=canvas.getCtx(),opt={},gradient=node.getData('gradient'),border=node.getData('border'),config=node.getData('config'),showLabels=config.showLabels,resizeLabels=config.resizeLabels,label=config.Label;var xpos=Math.cos((begin+end)/2);var ypos=Math.sin((begin+end)/2);if(colorArray&&dimArray&&stringArray&&gaugeTarget!=0){for(var i=0,l=dimArray.length,acum=0,valAcum=0;i<l;i++){var dimi=dimArray[i],colori=colorArray[i%colorLength];if(dimi<=0)continue;ctx.fillStyle=ctx.strokeStyle=colori;if(gradient&&dimi){var radialGradient=ctx.createRadialGradient(xpos,(ypos+dimi/2),acum,xpos,(ypos+dimi/2),acum+dimi);var colorRgb=$.hexToRgb(colori),ans=$.map(colorRgb,function(i){return(i*.8)>>0;}),endColor=$.rgbToHex(ans);radialGradient.addColorStop(0,'rgba('+colorRgb+',1)');radialGradient.addColorStop(0.1,'rgba('+colorRgb+',1)');radialGradient.addColorStop(0.85,'rgba('+colorRgb+',1)');radialGradient.addColorStop(1,'rgba('+ans+',1)');ctx.fillStyle=radialGradient;}
polar.rho=acum;polar.theta=begin;var p1coord=polar.getc(true);polar.theta=end;var p2coord=polar.getc(true);polar.rho+=dimi;var p3coord=polar.getc(true);polar.theta=begin;var p4coord=polar.getc(true);ctx.beginPath();ctx.arc(xpos,(ypos+dimi/2),(acum+dimi+.01)*.8,begin,end,false);ctx.arc(xpos,(ypos+dimi/2),(acum+dimi+.01),end,begin,true);ctx.fill();acum+=(dimi||0);valAcum+=(valueArray[i]||0);}
if(showLabels&&label.type=='Native'){ctx.save();ctx.fillStyle=ctx.strokeStyle=label.color;ctx.font=label.style+' '+label.size+'px '+label.family;ctx.textBaseline='bottom';ctx.textAlign='center';polar.rho=acum*.65;polar.theta=begin;var cart=polar.getc(true);if(nodeIteration==1){textY=cart.y-(label.size/2)+acum /2;}else{textY=cart.y+acum/2;}
if(config.labelType=='name'){ctx.fillText(node.name,cart.x,textY);}else{ctx.fillText(valuelabelsArray[0],cart.x,textY);}
if(nodeIteration==nodeLength){polar.theta=end;var cart=polar.getc(true);if(config.labelType=='name'){ctx.fillText(node.name,cart.x,cart.x,cart.y-(label.size/2)+acum/2);}else{ctx.fillText(valuelabelsArray[1],cart.x,cart.y-(label.size/2)+acum/2);}}
ctx.restore();}}},'contains':function(node,pos){if(this.nodeTypes['none'].anglecontainsgauge.call(this,node,pos)){var config=node.getData('config');var ld=this.config.levelDistance,d=node._depth;var yOffset=pos.y-(ld/2);var xOffset=pos.x;var rho=Math.sqrt(xOffset*xOffset+yOffset*yOffset);if(rho<=parseInt(ld*d)){var dimArray=node.getData('dimArray');for(var i=0,l=dimArray.length,acum=config.sliceOffset;i<l;i++){var dimi=dimArray[i];if(rho>=ld*.8&&rho<=acum+dimi){var url=Url.decode(node.getData('linkArray')[i]);return{name:node.getData('stringArray')[i],link:url,color:node.getData('colorArray')[i],value:node.getData('valueArray')[i],valuelabel:node.getData('valuelabelsArray')[0]+" - "+node.getData('valuelabelsArray')[1],label:node.name};}
acum+=dimi;}}
return false;}
return false;}}});$jit.GaugeChart=new Class({sb:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(opt){this.controller=this.config=$.merge(Options("Canvas","GaugeChart","Label"),{Label:{type:'Native'}},opt);this.initializeViz();},initializeViz:function(){var config=this.config,that=this;var nodeType=config.type.split(":")[0];var sb=new $jit.Sunburst({injectInto:config.injectInto,useCanvas:config.useCanvas,withLabels:config.Label.type!='Native',background:config.background,renderBackground:config.renderBackground,backgroundColor:config.backgroundColor,colorStop1:config.colorStop1,colorStop2:config.colorStop2,Label:{type:config.Label.type},Node:{overridable:true,type:'gaugechart-'+nodeType,width:1,height:1},Edge:{type:'none'},Tips:{enable:config.Tips.enable,type:'Native',force:true,onShow:function(tip,node,contains){var elem=contains;config.Tips.onShow(tip,elem,node);if(elem.link!='undefined'&&elem.link!=''){document.body.style.cursor='pointer';}},onHide:function(){document.body.style.cursor='default';}},Events:{enable:true,type:'Native',onClick:function(node,eventInfo,evt){if(!config.Events.enable)return;var elem=eventInfo.getContains();config.Events.onClick(elem,eventInfo,evt);}},onCreateLabel:function(domElement,node){var labelConf=config.Label;if(config.showLabels){var style=domElement.style;style.fontSize=labelConf.size+'px';style.fontFamily=labelConf.family;style.color=labelConf.color;style.textAlign='center';valuelabelsArray=node.getData('valuelabelsArray'),nodeIteration=node.getData('nodeIteration'),nodeLength=node.getData('nodeLength'),canvas=sb.canvas,prefix=$.time();if(config.labelType=='name'){domElement.innerHTML=node.name;}else{domElement.innerHTML=(valuelabelsArray[0]!=undefined)?valuelabelsArray[0]:"";}
domElement.style.width='400px';if(nodeIteration==nodeLength&&nodeLength!=0){idLabel=canvas.id+"-label";container=document.getElementById(idLabel);finalLabel=document.createElement('div');finalLabelStyle=finalLabel.style;finalLabel.id=prefix+"finalLabel";finalLabelStyle.position="absolute";finalLabelStyle.width="400px";finalLabelStyle.left="0px";container.appendChild(finalLabel);if(config.labelType=='name'){finalLabel.innerHTML=node.name;}else{finalLabel.innerHTML=(valuelabelsArray[1]!=undefined)?valuelabelsArray[1]:"";}}}},onPlaceLabel:function(domElement,node){if(!config.showLabels)return;var pos=node.pos.getp(true),dimArray=node.getData('dimArray'),nodeIteration=node.getData('nodeIteration'),nodeLength=node.getData('nodeLength'),span=node.getData('span')/ 2,theta=node.pos.theta,begin=((theta-span)/2)+Math.PI,end=((theta+span)/2)+Math.PI,polar=new Polar;var showLabels=config.showLabels,resizeLabels=config.resizeLabels,label=config.Label,radiusOffset=sb.config.levelDistance;if(dimArray){for(var i=0,l=dimArray.length,acum=0;i<l;i++){acum+=dimArray[i];}
var scale=resizeLabels?node.getData('normalizedDim'):1,fontSize=(label.size*scale)>>0;fontSize=fontSize<+resizeLabels?+resizeLabels:fontSize;domElement.style.fontSize=fontSize+'px';polar.rho=acum*.65;polar.theta=begin;var pos=polar.getc(true);var radius=that.canvas.getSize();var labelPos={x:Math.round(pos.x+radius.width / 2),y:Math.round(pos.y+(radius.height / 2)+radiusOffset/2)};domElement.style.left=(labelPos.x-200)+'px';domElement.style.top=labelPos.y+'px';if(nodeIteration==1){domElement.style.top=labelPos.y-label.size+'px';}
if(nodeIteration==nodeLength&&nodeLength!=0){polar.theta=end;var final=polar.getc(true);var finalPos={x:Math.round(final.x+radius.width / 2),y:Math.round(final.y+(radius.height / 2)+radiusOffset/2)};finalLabel.style.left=(finalPos.x-200)+"px";finalLabel.style.top=finalPos.y-label.size+"px";}}}});this.sb=sb;this.canvas=this.sb.canvas;var size=sb.canvas.getSize(),min=Math.min;sb.config.levelDistance=min(size.width,size.height)/2
-config.offset-config.sliceOffset;},renderBackground:function(){var canvas=this.sb.canvas,config=this.config,style=config.gaugeStyle,ctx=canvas.getCtx(),size=canvas.getSize(),radius=this.sb.config.levelDistance,startAngle=(Math.PI/180)*1,endAngle=(Math.PI/180)*179;ctx.fillStyle=style.borderColor;ctx.beginPath();ctx.arc(0,radius/2,radius+4,startAngle,endAngle,true);ctx.fill();var radialGradient=ctx.createRadialGradient(0,radius/2,0,0,radius/2,radius);radialGradient.addColorStop(0,'#ffffff');radialGradient.addColorStop(0.3,style.backgroundColor);radialGradient.addColorStop(0.6,style.backgroundColor);radialGradient.addColorStop(1,'#FFFFFF');ctx.fillStyle=radialGradient;startAngle=(Math.PI/180)*0;endAngle=(Math.PI/180)*180;ctx.beginPath();ctx.arc(0,radius/2,radius,startAngle,endAngle,true);ctx.fill();},renderNeedle:function(gaugePosition,target){var canvas=this.sb.canvas,config=this.config,style=config.gaugeStyle,ctx=canvas.getCtx(),size=canvas.getSize(),radius=this.sb.config.levelDistance;gaugeCenter=(radius/2);startAngle=0;endAngle=(Math.PI/180)*180;ctx.fillStyle=style.needleColor;var segments=180/target;needleAngle=gaugePosition*segments;ctx.translate(0,gaugeCenter);ctx.save();ctx.rotate(needleAngle*Math.PI / 180);ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(0,-4);ctx.lineTo(-radius*.9,-1);ctx.lineTo(-radius*.9,1);ctx.lineTo(0,4);ctx.lineTo(0,0);ctx.closePath();ctx.fill();ctx.restore();ctx.lineWidth=1;ctx.strokeStyle='#aa0000';ctx.save();ctx.rotate(needleAngle*Math.PI / 180);ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(0,-4);ctx.lineTo(-radius*.8,-1);ctx.lineTo(-radius*.8,1);ctx.lineTo(0,4);ctx.lineTo(0,0);ctx.closePath();ctx.stroke();ctx.restore();ctx.fillStyle="#000000";ctx.lineWidth=style.borderSize;ctx.strokeStyle=style.borderColor;var radialGradient=ctx.createRadialGradient(0,style.borderSize,0,0,style.borderSize,radius*.2);radialGradient.addColorStop(0,'#666666');radialGradient.addColorStop(0.8,'#444444');radialGradient.addColorStop(1,'rgba(0,0,0,0)');ctx.fillStyle=radialGradient;ctx.translate(0,5);ctx.save();ctx.beginPath();ctx.arc(0,0,radius*.2,startAngle,endAngle,true);ctx.fill();ctx.restore();},renderTicks:function(values){var canvas=this.sb.canvas,config=this.config,style=config.gaugeStyle,ctx=canvas.getCtx(),size=canvas.getSize(),radius=this.sb.config.levelDistance,gaugeCenter=(radius/2);ctx.strokeStyle=style.borderColor;ctx.lineWidth=5;ctx.lineCap="round";for(var i=0,total=0,l=values.length;i<l;i++){var val=values[i];if(val.label!='GaugePosition'){total+=(parseInt(val.values)||0);}}
for(var i=0,acum=0,l=values.length;i<l-1;i++){var val=values[i];if(val.label!='GaugePosition'){acum+=(parseInt(val.values)||0);var segments=180/total;angle=acum*segments;ctx.save();ctx.translate(0,gaugeCenter);ctx.beginPath();ctx.rotate(angle*(Math.PI/180));ctx.moveTo(-radius,0);ctx.lineTo(-radius*.75,0);ctx.stroke();ctx.restore();}}},renderPositionLabel:function(position){var canvas=this.sb.canvas,config=this.config,label=config.Label,style=config.gaugeStyle,ctx=canvas.getCtx(),size=canvas.getSize(),radius=this.sb.config.levelDistance,gaugeCenter=(radius/2);ctx.textBaseline='middle';ctx.textAlign='center';ctx.font=style.positionFontSize+'px '+label.family;ctx.fillStyle="#ffffff";ctx.lineWidth=2;height=style.positionFontSize+10,cornerRadius=8,idLabel=canvas.id+"-label";container=document.getElementById(idLabel);if(label.type=='Native'){var m=ctx.measureText(position),width=m.width+40;}else{var width=70;}
$.roundedRect(ctx,-width/2,0,width,height,cornerRadius,"fill");$.roundedRect(ctx,-width/2,0,width,height,cornerRadius,"stroke");if(label.type=='Native'){ctx.fillStyle=label.color;ctx.fillText(position,0,(height/2)+style.positionOffset);}else{var labelDiv=document.createElement('div');labelDivStyle=labelDiv.style;labelDivStyle.color=label.color;labelDivStyle.fontSize=style.positionFontSize+"px";labelDivStyle.position="absolute";labelDivStyle.width=width+"px";labelDivStyle.left=(size.width/2)-(width/2)+"px";labelDivStyle.top=(size.height/2)+style.positionOffset+"px";labelDiv.innerHTML=position;container.appendChild(labelDiv);}},renderSubtitle:function(){var canvas=this.canvas,size=canvas.getSize(),config=this.config,margin=config.Margin,radius=this.sb.config.levelDistance,title=config.Title,label=config.Label,subtitle=config.Subtitle;ctx=canvas.getCtx();ctx.fillStyle=title.color;ctx.textAlign='left';ctx.font=label.style+' '+subtitle.size+'px '+label.family;ctx.moveTo(0,0);if(label.type=='Native'){ctx.fillText(subtitle.text,-radius-4,subtitle.size+subtitle.offset+(radius/2));}},renderChartBackground:function(){var canvas=this.canvas,config=this.config,backgroundColor=config.backgroundColor,size=canvas.getSize(),ctx=canvas.getCtx();ctx.fillStyle=backgroundColor;ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);},clear:function(){var canvas=this.canvas;var ctx=canvas.getCtx(),size=canvas.getSize();ctx.fillStyle="rgba(255,255,255,0)";ctx.fillRect(-size.width/2,-size.height/2,size.width,size.height);ctx.clearRect(-size.width/2,-size.height/2,size.width,size.height);},resizeGraph:function(json,width){var canvas=this.canvas,size=canvas.getSize(),orgHeight=size.height;canvas.resize(width,orgHeight);if(typeof FlashCanvas=="undefined"){canvas.clear();}else{this.clear();}
this.loadJSON(json);},loadJSON:function(json){var prefix=$.time(),ch=[],sb=this.sb,name=$.splat(json.label),nameLength=name.length,color=$.splat(json.color||this.colors),colorLength=color.length,config=this.config,renderBackground=config.renderBackground,gradient=!!config.type.split(":")[1],animate=config.animate,mono=nameLength==1;var props=$.splat(json.properties)[0];for(var i=0,values=json.values,l=values.length;i<l;i++){var val=values[i];if(val.label!='GaugePosition'){var valArray=$.splat(val.values);var linkArray=(val.links=="undefined"||val.links==undefined)?new Array():$.splat(val.links);var valuelabelsArray=$.splat(val.valuelabels);ch.push({'id':prefix+val.label,'name':val.label,'data':{'value':valArray,'valuelabel':valuelabelsArray,'$linkArray':linkArray,'$valuelabelsArray':valuelabelsArray,'$valueArray':valArray,'$nodeIteration':i,'$nodeLength':l-1,'$colorArray':mono?$.splat(color[i%colorLength]):color,'$colorMono':$.splat(color[i%colorLength]),'$stringArray':name,'$gradient':gradient,'$config':config,'$gaugeTarget':props['gaugeTarget'],'$angularWidth':$.reduce(valArray,function(x,y){return x+y;})},'children':[]});}else{var gaugePosition=val.gvalue;var gaugePositionLabel=val.gvaluelabel;}}
var root={'id':prefix+'$root','name':'','data':{'$type':'none','$width':1,'$height':1},'children':ch};sb.loadJSON(root);if(renderBackground){this.renderChartBackground();}
this.renderBackground();this.renderSubtitle();this.normalizeDims();sb.refresh();if(animate){sb.fx.animate({modes:['node-property:dimArray'],duration:1500});}
this.renderPositionLabel(gaugePositionLabel);if(props['gaugeTarget']!=0){this.renderTicks(json.values);this.renderNeedle(gaugePosition,props['gaugeTarget']);}},updateJSON:function(json,onComplete){if(this.busy)return;this.busy=true;var sb=this.sb;var graph=sb.graph;var values=json.values;var animate=this.config.animate;var that=this;$.each(values,function(v){var n=graph.getByName(v.label),vals=$.splat(v.values);if(n){n.setData('valueArray',vals);n.setData('angularWidth',$.reduce(vals,function(x,y){return x+y;}));if(json.label){n.setData('stringArray',$.splat(json.label));}}});this.normalizeDims();if(animate){sb.compute('end');sb.fx.animate({modes:['node-property:dimArray:span','linear'],duration:1500,onComplete:function(){that.busy=false;onComplete&&onComplete.onComplete();}});}else{sb.refresh();}},select:function(id,name){if(!this.config.hoveredColor)return;var s=this.selected;if(s.id!=id||s.name!=name){s.id=id;s.name=name;s.color=this.config.hoveredColor;this.sb.graph.eachNode(function(n){if(id==n.id){n.setData('border',s);}else{n.setData('border',false);}});this.sb.plot();}},getLegend:function(){var legend=new Array();var name=new Array();var color=new Array();var n;this.sb.graph.getNode(this.sb.root).eachAdjacency(function(adj){n=adj.nodeTo;});var colors=n.getData('colorArray'),len=colors.length;$.each(n.getData('stringArray'),function(s,i){color[i]=colors[i%len];name[i]=s;});legend['name']=name;legend['color']=color;return legend;},getMaxValue:function(){var maxValue=0;this.sb.graph.eachNode(function(n){var valArray=n.getData('valueArray'),acum=0;$.each(valArray,function(v){acum+=+v;});maxValue=maxValue>acum?maxValue:acum;});return maxValue;},normalizeDims:function(){var root=this.sb.graph.getNode(this.sb.root),l=0;root.eachAdjacency(function(){l++;});var maxValue=this.getMaxValue()||1,config=this.config,animate=config.animate,rho=this.sb.config.levelDistance;this.sb.graph.eachNode(function(n){var acum=0,animateValue=[];$.each(n.getData('valueArray'),function(v){acum+=+v;animateValue.push(1);});var stat=(animateValue.length==1)&&!config.updateHeights;if(animate){n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return stat?rho:(n*rho / maxValue);}),'end');var dimArray=n.getData('dimArray');if(!dimArray){n.setData('dimArray',animateValue);}}else{n.setData('dimArray',$.map(n.getData('valueArray'),function(n){return stat?rho:(n*rho / maxValue);}));}
n.setData('normalizedDim',acum / maxValue);});}});Layouts.TM={};Layouts.TM.SliceAndDice=new Class({compute:function(prop){var root=this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root);this.controller.onBeforeCompute(root);var size=this.canvas.getSize(),config=this.config,width=size.width,height=size.height;this.graph.computeLevels(this.root,0,"ignore");root.getPos(prop).setc(-width/2,-height/2);root.setData('width',width,prop);root.setData('height',height+config.titleHeight,prop);this.computePositions(root,root,this.layout.orientation,prop);this.controller.onAfterCompute(root);},computePositions:function(par,ch,orn,prop){var totalArea=0;par.eachSubnode(function(n){totalArea+=n.getData('area',prop);});var config=this.config,offst=config.offset,width=par.getData('width',prop),height=par.getData('height',prop)-config.titleHeight,fact=par==ch?1:(ch.getData('area',prop)/ totalArea);var otherSize,size,dim,pos,pos2,posth,pos2th;var horizontal=(orn=="h");if(horizontal){orn='v';otherSize=height;size=width*fact;dim='height';pos='y';pos2='x';posth=config.titleHeight;pos2th=0;}else{orn='h';otherSize=height*fact;size=width;dim='width';pos='x';pos2='y';posth=0;pos2th=config.titleHeight;}
var cpos=ch.getPos(prop);ch.setData('width',size,prop);ch.setData('height',otherSize,prop);var offsetSize=0,tm=this;ch.eachSubnode(function(n){var p=n.getPos(prop);p[pos]=offsetSize+cpos[pos]+posth;p[pos2]=cpos[pos2]+pos2th;tm.computePositions(ch,n,orn,prop);offsetSize+=n.getData(dim,prop);});}});Layouts.TM.Area={compute:function(prop){prop=prop||"current";var root=this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root);this.controller.onBeforeCompute(root);var config=this.config,size=this.canvas.getSize(),width=size.width,height=size.height,offst=config.offset,offwdth=width-offst,offhght=height-offst;this.graph.computeLevels(this.root,0,"ignore");root.getPos(prop).setc(-width/2,-height/2);root.setData('width',width,prop);root.setData('height',height,prop);var coord={'top':-height/2+config.titleHeight,'left':-width/2,'width':offwdth,'height':offhght-config.titleHeight};this.computePositions(root,coord,prop);this.controller.onAfterCompute(root);},computeDim:function(tail,initElem,w,coord,comp,prop){if(tail.length+initElem.length==1){var l=(tail.length==1)?tail:initElem;this.layoutLast(l,w,coord,prop);return;}
if(tail.length>=2&&initElem.length==0){initElem=[tail.shift()];}
if(tail.length==0){if(initElem.length>0)this.layoutRow(initElem,w,coord,prop);return;}
var c=tail[0];if(comp(initElem,w)>=comp([c].concat(initElem),w)){this.computeDim(tail.slice(1),initElem.concat([c]),w,coord,comp,prop);}else{var newCoords=this.layoutRow(initElem,w,coord,prop);this.computeDim(tail,[],newCoords.dim,newCoords,comp,prop);}},worstAspectRatio:function(ch,w){if(!ch||ch.length==0)return Number.MAX_VALUE;var areaSum=0,maxArea=0,minArea=Number.MAX_VALUE;for(var i=0,l=ch.length;i<l;i++){var area=ch[i]._area;areaSum+=area;minArea=minArea<area?minArea:area;maxArea=maxArea>area?maxArea:area;}
var sqw=w*w,sqAreaSum=areaSum*areaSum;return Math.max(sqw*maxArea / sqAreaSum,sqAreaSum /(sqw*minArea));},avgAspectRatio:function(ch,w){if(!ch||ch.length==0)return Number.MAX_VALUE;var arSum=0;for(var i=0,l=ch.length;i<l;i++){var area=ch[i]._area;var h=area / w;arSum+=w>h?w / h:h / w;}
return arSum / l;},layoutLast:function(ch,w,coord,prop){var child=ch[0];child.getPos(prop).setc(coord.left,coord.top);child.setData('width',coord.width,prop);child.setData('height',coord.height,prop);}};Layouts.TM.Squarified=new Class({Implements:Layouts.TM.Area,computePositions:function(node,coord,prop){var config=this.config;if(coord.width>=coord.height)
this.layout.orientation='h';else
this.layout.orientation='v';var ch=node.getSubnodes([1,1],"ignore");if(ch.length>0){this.processChildrenLayout(node,ch,coord,prop);for(var i=0,l=ch.length;i<l;i++){var chi=ch[i];var offst=config.offset,height=chi.getData('height',prop)-offst-config.titleHeight,width=chi.getData('width',prop)-offst;var chipos=chi.getPos(prop);coord={'width':width,'height':height,'top':chipos.y+config.titleHeight,'left':chipos.x};this.computePositions(chi,coord,prop);}}},processChildrenLayout:function(par,ch,coord,prop){var parentArea=coord.width*coord.height;var i,l=ch.length,totalChArea=0,chArea=[];for(i=0;i<l;i++){chArea[i]=parseFloat(ch[i].getData('area',prop));totalChArea+=chArea[i];}
for(i=0;i<l;i++){ch[i]._area=parentArea*chArea[i]/ totalChArea;}
var minimumSideValue=this.layout.horizontal()?coord.height:coord.width;ch.sort(function(a,b){var diff=b._area-a._area;return diff?diff:(b.id==a.id?0:(b.id<a.id?1:-1));});var initElem=[ch[0]];var tail=ch.slice(1);this.squarify(tail,initElem,minimumSideValue,coord,prop);},squarify:function(tail,initElem,w,coord,prop){this.computeDim(tail,initElem,w,coord,this.worstAspectRatio,prop);},layoutRow:function(ch,w,coord,prop){if(this.layout.horizontal()){return this.layoutV(ch,w,coord,prop);}else{return this.layoutH(ch,w,coord,prop);}},layoutV:function(ch,w,coord,prop){var totalArea=0,rnd=function(x){return x;};$.each(ch,function(elem){totalArea+=elem._area;});var width=rnd(totalArea / w),top=0;for(var i=0,l=ch.length;i<l;i++){var h=rnd(ch[i]._area / width);var chi=ch[i];chi.getPos(prop).setc(coord.left,coord.top+top);chi.setData('width',width,prop);chi.setData('height',h,prop);top+=h;}
var ans={'height':coord.height,'width':coord.width-width,'top':coord.top,'left':coord.left+width};ans.dim=Math.min(ans.width,ans.height);if(ans.dim!=ans.height)this.layout.change();return ans;},layoutH:function(ch,w,coord,prop){var totalArea=0;$.each(ch,function(elem){totalArea+=elem._area;});var height=totalArea / w,top=coord.top,left=0;for(var i=0,l=ch.length;i<l;i++){var chi=ch[i];var w=chi._area / height;chi.getPos(prop).setc(coord.left+left,top);chi.setData('width',w,prop);chi.setData('height',height,prop);left+=w;}
var ans={'height':coord.height-height,'width':coord.width,'top':coord.top+height,'left':coord.left};ans.dim=Math.min(ans.width,ans.height);if(ans.dim!=ans.width)this.layout.change();return ans;}});Layouts.TM.Strip=new Class({Implements:Layouts.TM.Area,computePositions:function(node,coord,prop){var ch=node.getSubnodes([1,1],"ignore"),config=this.config;if(ch.length>0){this.processChildrenLayout(node,ch,coord,prop);for(var i=0,l=ch.length;i<l;i++){var chi=ch[i];var offst=config.offset,height=chi.getData('height',prop)-offst-config.titleHeight,width=chi.getData('width',prop)-offst;var chipos=chi.getPos(prop);coord={'width':width,'height':height,'top':chipos.y+config.titleHeight,'left':chipos.x};this.computePositions(chi,coord,prop);}}},processChildrenLayout:function(par,ch,coord,prop){var parentArea=coord.width*coord.height;var i,l=ch.length,totalChArea=0,chArea=[];for(i=0;i<l;i++){chArea[i]=+ch[i].getData('area',prop);totalChArea+=chArea[i];}
for(i=0;i<l;i++){ch[i]._area=parentArea*chArea[i]/ totalChArea;}
var side=this.layout.horizontal()?coord.width:coord.height;var initElem=[ch[0]];var tail=ch.slice(1);this.stripify(tail,initElem,side,coord,prop);},stripify:function(tail,initElem,w,coord,prop){this.computeDim(tail,initElem,w,coord,this.avgAspectRatio,prop);},layoutRow:function(ch,w,coord,prop){if(this.layout.horizontal()){return this.layoutH(ch,w,coord,prop);}else{return this.layoutV(ch,w,coord,prop);}},layoutV:function(ch,w,coord,prop){var totalArea=0;$.each(ch,function(elem){totalArea+=elem._area;});var width=totalArea / w,top=0;for(var i=0,l=ch.length;i<l;i++){var chi=ch[i];var h=chi._area / width;chi.getPos(prop).setc(coord.left,coord.top+(w-h-top));chi.setData('width',width,prop);chi.setData('height',h,prop);top+=h;}
return{'height':coord.height,'width':coord.width-width,'top':coord.top,'left':coord.left+width,'dim':w};},layoutH:function(ch,w,coord,prop){var totalArea=0;$.each(ch,function(elem){totalArea+=elem._area;});var height=totalArea / w,top=coord.height-height,left=0;for(var i=0,l=ch.length;i<l;i++){var chi=ch[i];var s=chi._area / height;chi.getPos(prop).setc(coord.left+left,coord.top+top);chi.setData('width',s,prop);chi.setData('height',height,prop);left+=s;}
return{'height':coord.height-height,'width':coord.width,'top':coord.top,'left':coord.left,'dim':w};}});Layouts.Icicle=new Class({compute:function(posType){posType=posType||"current";var root=this.graph.getNode(this.root),config=this.config,size=this.canvas.getSize(),width=size.width,height=size.height,offset=config.offset,levelsToShow=config.constrained?config.levelsToShow:Number.MAX_VALUE;this.controller.onBeforeCompute(root);Graph.Util.computeLevels(this.graph,root.id,0,"ignore");var treeDepth=0;Graph.Util.eachLevel(root,0,false,function(n,d){if(d>treeDepth)treeDepth=d;});var startNode=this.graph.getNode(this.clickedNode&&this.clickedNode.id||root.id);var maxDepth=Math.min(treeDepth,levelsToShow-1);var initialDepth=startNode._depth;if(this.layout.horizontal()){this.computeSubtree(startNode,-width/2,-height/2,width/(maxDepth+1),height,initialDepth,maxDepth,posType);}else{this.computeSubtree(startNode,-width/2,-height/2,width,height/(maxDepth+1),initialDepth,maxDepth,posType);}},computeSubtree:function(root,x,y,width,height,initialDepth,maxDepth,posType){root.getPos(posType).setc(x,y);root.setData('width',width,posType);root.setData('height',height,posType);var nodeLength,prevNodeLength=0,totalDim=0;var children=Graph.Util.getSubnodes(root,[1,1]);if(!children.length)
return;$.each(children,function(e){totalDim+=e.getData('dim');});for(var i=0,l=children.length;i<l;i++){if(this.layout.horizontal()){nodeLength=height*children[i].getData('dim')/ totalDim;this.computeSubtree(children[i],x+width,y,width,nodeLength,initialDepth,maxDepth,posType);y+=nodeLength;}else{nodeLength=width*children[i].getData('dim')/ totalDim;this.computeSubtree(children[i],x,y+height,nodeLength,height,initialDepth,maxDepth,posType);x+=nodeLength;}}}});$jit.Icicle=new Class({Implements:[Loader,Extras,Layouts.Icicle],layout:{orientation:"h",vertical:function(){return this.orientation=="v";},horizontal:function(){return this.orientation=="h";},change:function(){this.orientation=this.vertical()?"h":"v";}},initialize:function(controller){var config={animate:false,orientation:"h",offset:2,levelsToShow:Number.MAX_VALUE,constrained:false,Node:{type:'rectangle',overridable:true},Edge:{type:'none'},Label:{type:'Native'},duration:700,fps:45};var opts=Options("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label");this.controller=this.config=$.merge(opts,config,controller);this.layout.orientation=this.config.orientation;var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':true,'Node':{'selected':false,'exist':true,'drawn':true}};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge,this.config.Label);this.labels=new $jit.Icicle.Label[this.config.Label.type](this);this.fx=new $jit.Icicle.Plot(this,$jit.Icicle);this.op=new $jit.Icicle.Op(this);this.group=new $jit.Icicle.Group(this);this.clickedNode=null;this.initializeExtras();},refresh:function(){var labelType=this.config.Label.type;if(labelType!='Native'){var that=this;this.graph.eachNode(function(n){that.labels.hideLabel(n,false);});}
this.compute();this.plot();},plot:function(){this.fx.plot(this.config);},enter:function(node){if(this.busy)
return;this.busy=true;var that=this,config=this.config;var callback={onComplete:function(){if(config.request)
that.compute();if(config.animate){that.graph.nodeList.setDataset(['current','end'],{'alpha':[1,0]});Graph.Util.eachSubgraph(node,function(n){n.setData('alpha',1,'end');},"ignore");that.fx.animate({duration:500,modes:['node-property:alpha'],onComplete:function(){that.clickedNode=node;that.compute('end');that.fx.animate({modes:['linear','node-property:width:height'],duration:1000,onComplete:function(){that.busy=false;that.clickedNode=node;}});}});}else{that.clickedNode=node;that.busy=false;that.refresh();}}};if(config.request){this.requestNodes(clickedNode,callback);}else{callback.onComplete();}},out:function(){if(this.busy)
return;var that=this,GUtil=Graph.Util,config=this.config,graph=this.graph,parents=GUtil.getParents(graph.getNode(this.clickedNode&&this.clickedNode.id||this.root)),parent=parents[0],clickedNode=parent,previousClickedNode=this.clickedNode;this.busy=true;this.events.hoveredNode=false;if(!parent){this.busy=false;return;}
callback={onComplete:function(){that.clickedNode=parent;if(config.request){that.requestNodes(parent,{onComplete:function(){that.compute();that.plot();that.busy=false;}});}else{that.compute();that.plot();that.busy=false;}}};if(config.animate){this.clickedNode=clickedNode;this.compute('end');this.clickedNode=previousClickedNode;this.fx.animate({modes:['linear','node-property:width:height'],duration:1000,onComplete:function(){that.clickedNode=clickedNode;graph.nodeList.setDataset(['current','end'],{'alpha':[0,1]});GUtil.eachSubgraph(previousClickedNode,function(node){node.setData('alpha',1);},"ignore");that.fx.animate({duration:500,modes:['node-property:alpha'],onComplete:function(){callback.onComplete();}});}});}else{callback.onComplete();}},requestNodes:function(node,onComplete){var handler=$.merge(this.controller,onComplete),levelsToShow=this.config.constrained?this.config.levelsToShow:Number.MAX_VALUE;if(handler.request){var leaves=[],d=node._depth;Graph.Util.eachLevel(node,0,levelsToShow,function(n){if(n.drawn&&!Graph.Util.anySubnode(n)){leaves.push(n);n._level=n._depth-d;if(this.config.constrained)
n._level=levelsToShow-n._level;}});this.group.requestNodes(leaves,handler);}else{handler.onComplete();}}});$jit.Icicle.Op=new Class({Implements:Graph.Op});$jit.Icicle.Group=new Class({initialize:function(viz){this.viz=viz;this.canvas=viz.canvas;this.config=viz.config;},requestNodes:function(nodes,controller){var counter=0,len=nodes.length,nodeSelected={};var complete=function(){controller.onComplete();};var viz=this.viz;if(len==0)
complete();for(var i=0;i<len;i++){nodeSelected[nodes[i].id]=nodes[i];controller.request(nodes[i].id,nodes[i]._level,{onComplete:function(nodeId,data){if(data&&data.children){data.id=nodeId;viz.op.sum(data,{type:'nothing'});}
if(++counter==len){Graph.Util.computeLevels(viz.graph,viz.root,0);complete();}}});}}});$jit.Icicle.Plot=new Class({Implements:Graph.Plot,plot:function(opt,animating){opt=opt||this.viz.controller;var viz=this.viz,graph=viz.graph,root=graph.getNode(viz.clickedNode&&viz.clickedNode.id||viz.root),initialDepth=root._depth;viz.canvas.clear();this.plotTree(root,$.merge(opt,{'withLabels':true,'hideLabels':false,'plotSubtree':function(root,node){return!viz.config.constrained||(node._depth-initialDepth<viz.config.levelsToShow);}}),animating);}});$jit.Icicle.Label={};$jit.Icicle.Label.Native=new Class({Implements:Graph.Label.Native,renderLabel:function(canvas,node,controller){var ctx=canvas.getCtx(),width=node.getData('width'),height=node.getData('height'),size=node.getLabelData('size'),m=ctx.measureText(node.name);if(height<(size*1.5)||width<m.width)
return;var pos=node.pos.getc(true);ctx.fillText(node.name,pos.x+width / 2,pos.y+height / 2);}});$jit.Icicle.Label.SVG=new Class({Implements:Graph.Label.SVG,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas;var radius=canvas.getSize();var labelPos={x:Math.round(pos.x+radius.width / 2),y:Math.round(pos.y+radius.height / 2)};tag.setAttribute('x',labelPos.x);tag.setAttribute('y',labelPos.y);controller.onPlaceLabel(tag,node);}});$jit.Icicle.Label.HTML=new Class({Implements:Graph.Label.HTML,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas;var radius=canvas.getSize();var labelPos={x:Math.round(pos.x+radius.width / 2),y:Math.round(pos.y+radius.height / 2)};var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.display='';controller.onPlaceLabel(tag,node);}});$jit.Icicle.Plot.NodeTypes=new Class({'none':{'render':$.empty},'rectangle':{'render':function(node,canvas,animating){var config=this.viz.config;var offset=config.offset;var width=node.getData('width');var height=node.getData('height');var border=node.getData('border');var pos=node.pos.getc(true);var posx=pos.x+offset / 2,posy=pos.y+offset / 2;var ctx=canvas.getCtx();if(width-offset<2||height-offset<2)return;if(config.cushion){var color=node.getData('color');var lg=ctx.createRadialGradient(posx+(width-offset)/2,posy+(height-offset)/2,1,posx+(width-offset)/2,posy+(height-offset)/2,width<height?height:width);var colorGrad=$.rgbToHex($.map($.hexToRgb(color),function(r){return r*0.3>>0;}));lg.addColorStop(0,color);lg.addColorStop(1,colorGrad);ctx.fillStyle=lg;}
if(border){ctx.strokeStyle=border;ctx.lineWidth=3;}
ctx.fillRect(posx,posy,Math.max(0,width-offset),Math.max(0,height-offset));border&&ctx.strokeRect(pos.x,pos.y,width,height);},'contains':function(node,pos){if(this.viz.clickedNode&&!$jit.Graph.Util.isDescendantOf(node,this.viz.clickedNode.id))return false;var npos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');return this.nodeHelper.rectangle.contains({x:npos.x+width/2,y:npos.y+height/2},pos,width,height);}}});$jit.Icicle.Plot.EdgeTypes=new Class({'none':$.empty});Layouts.ForceDirected=new Class({getOptions:function(random){var s=this.canvas.getSize();var w=s.width,h=s.height;var count=0;this.graph.eachNode(function(n){count++;});var k2=w*h / count,k=Math.sqrt(k2);var l=this.config.levelDistance;return{width:w,height:h,tstart:w*0.1,nodef:function(x){return k2 /(x||1);},edgef:function(x){return k*(x-l);}};},compute:function(property,incremental){var prop=$.splat(property||['current','start','end']);var opt=this.getOptions();NodeDim.compute(this.graph,prop,this.config);this.graph.computeLevels(this.root,0,"ignore");this.graph.eachNode(function(n){$.each(prop,function(p){var pos=n.getPos(p);if(pos.equals(Complex.KER)){pos.x=opt.width/5*(Math.random()-0.5);pos.y=opt.height/5*(Math.random()-0.5);}
n.disp={};$.each(prop,function(p){n.disp[p]=$C(0,0);});});});this.computePositions(prop,opt,incremental);},computePositions:function(property,opt,incremental){var times=this.config.iterations,i=0,that=this;if(incremental){(function iter(){for(var total=incremental.iter,j=0;j<total;j++){opt.t=opt.tstart*(1-i++/(times-1));that.computePositionStep(property,opt);if(i>=times){incremental.onComplete();return;}}
incremental.onStep(Math.round(i /(times-1)*100));setTimeout(iter,1);})();}else{for(;i<times;i++){opt.t=opt.tstart*(1-i/(times-1));this.computePositionStep(property,opt);}}},computePositionStep:function(property,opt){var graph=this.graph;var min=Math.min,max=Math.max;var dpos=$C(0,0);graph.eachNode(function(v){$.each(property,function(p){v.disp[p].x=0;v.disp[p].y=0;});graph.eachNode(function(u){if(u.id!=v.id){$.each(property,function(p){var vp=v.getPos(p),up=u.getPos(p);dpos.x=vp.x-up.x;dpos.y=vp.y-up.y;var norm=dpos.norm()||1;v.disp[p].$add(dpos.$scale(opt.nodef(norm)/ norm));});}});});var T=!!graph.getNode(this.root).visited;graph.eachNode(function(node){node.eachAdjacency(function(adj){var nodeTo=adj.nodeTo;if(!!nodeTo.visited===T){$.each(property,function(p){var vp=node.getPos(p),up=nodeTo.getPos(p);dpos.x=vp.x-up.x;dpos.y=vp.y-up.y;var norm=dpos.norm()||1;node.disp[p].$add(dpos.$scale(-opt.edgef(norm)/ norm));nodeTo.disp[p].$add(dpos.$scale(-1));});}});node.visited=!T;});var t=opt.t,w2=opt.width / 2,h2=opt.height / 2;graph.eachNode(function(u){$.each(property,function(p){var disp=u.disp[p];var norm=disp.norm()||1;var p=u.getPos(p);p.$add($C(disp.x*min(Math.abs(disp.x),t)/ norm,disp.y*min(Math.abs(disp.y),t)/ norm));p.x=min(w2,max(-w2,p.x));p.y=min(h2,max(-h2,p.y));});});}});$jit.ForceDirected=new Class({Implements:[Loader,Extras,Layouts.ForceDirected],initialize:function(controller){var $ForceDirected=$jit.ForceDirected;var config={iterations:50,levelDistance:50};this.controller=this.config=$.merge(Options("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label"),config,controller);var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{if(canvasConfig.background){canvasConfig.background=$.merge({type:'Circles'},canvasConfig.background);}
this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':true,'Node':{'selected':false,'exist':true,'drawn':true}};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new $ForceDirected.Label[canvasConfig.Label.type](this);this.fx=new $ForceDirected.Plot(this,$ForceDirected);this.op=new $ForceDirected.Op(this);this.json=null;this.busy=false;this.initializeExtras();},refresh:function(){this.compute();this.plot();},reposition:function(){this.compute('end');},computeIncremental:function(opt){opt=$.merge({iter:20,property:'end',onStep:$.empty,onComplete:$.empty},opt||{});this.config.onBeforeCompute(this.graph.getNode(this.root));this.compute(opt.property,opt);},plot:function(){this.fx.plot();},animate:function(opt){this.fx.animate($.merge({modes:['linear']},opt||{}));}});$jit.ForceDirected.$extend=true;(function(ForceDirected){ForceDirected.Op=new Class({Implements:Graph.Op});ForceDirected.Plot=new Class({Implements:Graph.Plot});ForceDirected.Label={};ForceDirected.Label.Native=new Class({Implements:Graph.Label.Native});ForceDirected.Label.SVG=new Class({Implements:Graph.Label.SVG,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize();var labelPos={x:Math.round(pos.x*sx+ox+radius.width / 2),y:Math.round(pos.y*sy+oy+radius.height / 2)};tag.setAttribute('x',labelPos.x);tag.setAttribute('y',labelPos.y);controller.onPlaceLabel(tag,node);}});ForceDirected.Label.HTML=new Class({Implements:Graph.Label.HTML,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize();var labelPos={x:Math.round(pos.x*sx+ox+radius.width / 2),y:Math.round(pos.y*sy+oy+radius.height / 2)};var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.display=this.fitsInCanvas(labelPos,canvas)?'':'none';controller.onPlaceLabel(tag,node);}});ForceDirected.Plot.NodeTypes=new Class({'none':{'render':$.empty,'contains':$.lambda(false)},'circle':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.circle.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.circle.contains(npos,pos,dim);}},'ellipse':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');this.nodeHelper.ellipse.render('fill',pos,width,height,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');return this.nodeHelper.ellipse.contains(npos,pos,width,height);}},'square':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.square.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.square.contains(npos,pos,dim);}},'rectangle':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');this.nodeHelper.rectangle.render('fill',pos,width,height,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');return this.nodeHelper.rectangle.contains(npos,pos,width,height);}},'triangle':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.triangle.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.triangle.contains(npos,pos,dim);}},'star':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.star.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.star.contains(npos,pos,dim);}}});ForceDirected.Plot.EdgeTypes=new Class({'none':$.empty,'line':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);this.edgeHelper.line.render(from,to,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);return this.edgeHelper.line.contains(from,to,pos,this.edge.epsilon);}},'arrow':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),dim=adj.getData('dim'),direction=adj.data.$direction,inv=(direction&&direction.length>1&&direction[0]!=adj.nodeFrom.id);this.edgeHelper.arrow.render(from,to,dim,inv,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);return this.edgeHelper.arrow.contains(from,to,pos,this.edge.epsilon);}}});})($jit.ForceDirected);$jit.TM={};var TM=$jit.TM;$jit.TM.$extend=true;TM.Base={layout:{orientation:"h",vertical:function(){return this.orientation=="v";},horizontal:function(){return this.orientation=="h";},change:function(){this.orientation=this.vertical()?"h":"v";}},initialize:function(controller){var config={orientation:"h",titleHeight:13,offset:2,levelsToShow:0,constrained:false,animate:false,Node:{type:'rectangle',overridable:true,width:3,height:3,color:'#444'},Label:{textAlign:'center',textBaseline:'top'},Edge:{type:'none'},duration:700,fps:45};this.controller=this.config=$.merge(Options("Canvas","Node","Edge","Fx","Controller","Tips","NodeStyles","Events","Navigation","Label"),config,controller);this.layout.orientation=this.config.orientation;var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{if(canvasConfig.background){canvasConfig.background=$.merge({type:'Circles'},canvasConfig.background);}
this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':true,'Node':{'selected':false,'exist':true,'drawn':true}};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new TM.Label[canvasConfig.Label.type](this);this.fx=new TM.Plot(this);this.op=new TM.Op(this);this.group=new TM.Group(this);this.geom=new TM.Geom(this);this.clickedNode=null;this.busy=false;this.initializeExtras();},refresh:function(){if(this.busy)return;this.busy=true;var that=this;if(this.config.animate){this.compute('end');this.config.levelsToShow>0&&this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root));this.fx.animate($.merge(this.config,{modes:['linear','node-property:width:height'],onComplete:function(){that.busy=false;}}));}else{var labelType=this.config.Label.type;if(labelType!='Native'){var that=this;this.graph.eachNode(function(n){that.labels.hideLabel(n,false);});}
this.busy=false;this.compute();this.config.levelsToShow>0&&this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root));this.plot();}},plot:function(){this.fx.plot();},leaf:function(n){return n.getSubnodes([1,1],"ignore").length==0;},enter:function(n){if(this.busy)return;this.busy=true;var that=this,config=this.config,graph=this.graph,clickedNode=n,previousClickedNode=this.clickedNode;var callback={onComplete:function(){if(config.levelsToShow>0){that.geom.setRightLevelToShow(n);}
if(config.levelsToShow>0||config.request)that.compute();if(config.animate){graph.nodeList.setData('alpha',0,'end');n.eachSubgraph(function(n){n.setData('alpha',1,'end');},"ignore");that.fx.animate({duration:500,modes:['node-property:alpha'],onComplete:function(){that.clickedNode=clickedNode;that.compute('end');that.clickedNode=previousClickedNode;that.fx.animate({modes:['linear','node-property:width:height'],duration:1000,onComplete:function(){that.busy=false;that.clickedNode=clickedNode;}});}});}else{that.busy=false;that.clickedNode=n;that.refresh();}}};if(config.request){this.requestNodes(clickedNode,callback);}else{callback.onComplete();}},out:function(){if(this.busy)return;this.busy=true;this.events.hoveredNode=false;var that=this,config=this.config,graph=this.graph,parents=graph.getNode(this.clickedNode&&this.clickedNode.id||this.root).getParents(),parent=parents[0],clickedNode=parent,previousClickedNode=this.clickedNode;if(!parent){this.busy=false;return;}
callback={onComplete:function(){that.clickedNode=parent;if(config.request){that.requestNodes(parent,{onComplete:function(){that.compute();that.plot();that.busy=false;}});}else{that.compute();that.plot();that.busy=false;}}};if(config.levelsToShow>0)
this.geom.setRightLevelToShow(parent);if(config.animate){this.clickedNode=clickedNode;this.compute('end');this.clickedNode=previousClickedNode;this.fx.animate({modes:['linear','node-property:width:height'],duration:1000,onComplete:function(){that.clickedNode=clickedNode;graph.eachNode(function(n){n.setDataset(['current','end'],{'alpha':[0,1]});},"ignore");previousClickedNode.eachSubgraph(function(node){node.setData('alpha',1);},"ignore");that.fx.animate({duration:500,modes:['node-property:alpha'],onComplete:function(){callback.onComplete();}});}});}else{callback.onComplete();}},requestNodes:function(node,onComplete){var handler=$.merge(this.controller,onComplete),lev=this.config.levelsToShow;if(handler.request){var leaves=[],d=node._depth;node.eachLevel(0,lev,function(n){var nodeLevel=lev-(n._depth-d);if(n.drawn&&!n.anySubnode()&&nodeLevel>0){leaves.push(n);n._level=nodeLevel;}});this.group.requestNodes(leaves,handler);}else{handler.onComplete();}}};TM.Op=new Class({Implements:Graph.Op,initialize:function(viz){this.viz=viz;}});TM.Geom=new Class({Implements:Graph.Geom,getRightLevelToShow:function(){return this.viz.config.levelsToShow;},setRightLevelToShow:function(node){var level=this.getRightLevelToShow(),fx=this.viz.labels;node.eachLevel(0,level+1,function(n){var d=n._depth-node._depth;if(d>level){n.drawn=false;n.exist=false;n.ignore=true;fx.hideLabel(n,false);}else{n.drawn=true;n.exist=true;delete n.ignore;}});node.drawn=true;delete node.ignore;}});TM.Group=new Class({initialize:function(viz){this.viz=viz;this.canvas=viz.canvas;this.config=viz.config;},requestNodes:function(nodes,controller){var counter=0,len=nodes.length,nodeSelected={};var complete=function(){controller.onComplete();};var viz=this.viz;if(len==0)
complete();for(var i=0;i<len;i++){nodeSelected[nodes[i].id]=nodes[i];controller.request(nodes[i].id,nodes[i]._level,{onComplete:function(nodeId,data){if(data&&data.children){data.id=nodeId;viz.op.sum(data,{type:'nothing'});}
if(++counter==len){viz.graph.computeLevels(viz.root,0);complete();}}});}}});TM.Plot=new Class({Implements:Graph.Plot,initialize:function(viz){this.viz=viz;this.config=viz.config;this.node=this.config.Node;this.edge=this.config.Edge;this.animation=new Animation;this.nodeTypes=new TM.Plot.NodeTypes;this.edgeTypes=new TM.Plot.EdgeTypes;this.labels=viz.labels;},plot:function(opt,animating){var viz=this.viz,graph=viz.graph;viz.canvas.clear();this.plotTree(graph.getNode(viz.clickedNode&&viz.clickedNode.id||viz.root),$.merge(viz.config,opt||{},{'withLabels':true,'hideLabels':false,'plotSubtree':function(n,ch){return n.anySubnode("exist");}}),animating);}});TM.Label={};TM.Label.Native=new Class({Implements:Graph.Label.Native,initialize:function(viz){this.config=viz.config;this.leaf=viz.leaf;},renderLabel:function(canvas,node,controller){if(!this.leaf(node)&&!this.config.titleHeight)return;var pos=node.pos.getc(true),ctx=canvas.getCtx(),width=node.getData('width'),height=node.getData('height'),x=pos.x+width/2,y=pos.y;ctx.fillText(node.name,x,y,width);}});TM.Label.SVG=new Class({Implements:Graph.Label.SVG,initialize:function(viz){this.viz=viz;this.leaf=viz.leaf;this.config=viz.config;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize();var labelPos={x:Math.round(pos.x*sx+ox+radius.width / 2),y:Math.round(pos.y*sy+oy+radius.height / 2)};tag.setAttribute('x',labelPos.x);tag.setAttribute('y',labelPos.y);if(!this.leaf(node)&&!this.config.titleHeight){tag.style.display='none';}
controller.onPlaceLabel(tag,node);}});TM.Label.HTML=new Class({Implements:Graph.Label.HTML,initialize:function(viz){this.viz=viz;this.leaf=viz.leaf;this.config=viz.config;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize();var labelPos={x:Math.round(pos.x*sx+ox+radius.width / 2),y:Math.round(pos.y*sy+oy+radius.height / 2)};var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.width=node.getData('width')*sx+'px';style.height=node.getData('height')*sy+'px';style.zIndex=node._depth*100;style.display='';if(!this.leaf(node)&&!this.config.titleHeight){tag.style.display='none';}
controller.onPlaceLabel(tag,node);}});TM.Plot.NodeTypes=new Class({'none':{'render':$.empty},'rectangle':{'render':function(node,canvas,animating){var leaf=this.viz.leaf(node),config=this.config,offst=config.offset,titleHeight=config.titleHeight,pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height'),border=node.getData('border'),ctx=canvas.getCtx(),posx=pos.x+offst / 2,posy=pos.y+offst / 2;if(width<=offst||height<=offst)return;if(leaf){if(config.cushion){var lg=ctx.createRadialGradient(posx+(width-offst)/2,posy+(height-offst)/2,1,posx+(width-offst)/2,posy+(height-offst)/2,width<height?height:width);var color=node.getData('color');var colorGrad=$.rgbToHex($.map($.hexToRgb(color),function(r){return r*0.2>>0;}));lg.addColorStop(0,color);lg.addColorStop(1,colorGrad);ctx.fillStyle=lg;}
ctx.fillRect(posx,posy,width-offst,height-offst);if(border){ctx.save();ctx.strokeStyle=border;ctx.strokeRect(posx,posy,width-offst,height-offst);ctx.restore();}}else if(titleHeight>0){ctx.fillRect(pos.x+offst / 2,pos.y+offst / 2,width-offst,titleHeight-offst);if(border){ctx.save();ctx.strokeStyle=border;ctx.strokeRect(pos.x+offst / 2,pos.y+offst / 2,width-offst,height-offst);ctx.restore();}}},'contains':function(node,pos){if(this.viz.clickedNode&&!node.isDescendantOf(this.viz.clickedNode.id)||node.ignore)return false;var npos=node.pos.getc(true),width=node.getData('width'),leaf=this.viz.leaf(node),height=leaf?node.getData('height'):this.config.titleHeight;return this.nodeHelper.rectangle.contains({x:npos.x+width/2,y:npos.y+height/2},pos,width,height);}}});TM.Plot.EdgeTypes=new Class({'none':$.empty});TM.SliceAndDice=new Class({Implements:[Loader,Extras,TM.Base,Layouts.TM.SliceAndDice]});TM.Squarified=new Class({Implements:[Loader,Extras,TM.Base,Layouts.TM.Squarified]});TM.Strip=new Class({Implements:[Loader,Extras,TM.Base,Layouts.TM.Strip]});$jit.RGraph=new Class({Implements:[Loader,Extras,Layouts.Radial],initialize:function(controller){var $RGraph=$jit.RGraph;var config={interpolation:'linear',levelDistance:100};this.controller=this.config=$.merge(Options("Canvas","Node","Edge","Fx","Controller","Tips","NodeStyles","Events","Navigation","Label"),config,controller);var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{if(canvasConfig.background){canvasConfig.background=$.merge({type:'Circles'},canvasConfig.background);}
this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':false,'Node':{'selected':false,'exist':true,'drawn':true}};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new $RGraph.Label[canvasConfig.Label.type](this);this.fx=new $RGraph.Plot(this,$RGraph);this.op=new $RGraph.Op(this);this.json=null;this.root=null;this.busy=false;this.parent=false;this.initializeExtras();},createLevelDistanceFunc:function(){var ld=this.config.levelDistance;return function(elem){return(elem._depth+1)*ld;};},refresh:function(){this.compute();this.plot();},reposition:function(){this.compute('end');},plot:function(){this.fx.plot();},getNodeAndParentAngle:function(id){var theta=false;var n=this.graph.getNode(id);var ps=n.getParents();var p=(ps.length>0)?ps[0]:false;if(p){var posParent=p.pos.getc(),posChild=n.pos.getc();var newPos=posParent.add(posChild.scale(-1));theta=Math.atan2(newPos.y,newPos.x);if(theta<0)
theta+=2*Math.PI;}
return{parent:p,theta:theta};},tagChildren:function(par,id){if(par.angleSpan){var adjs=[];par.eachAdjacency(function(elem){adjs.push(elem.nodeTo);},"ignore");var len=adjs.length;for(var i=0;i<len&&id!=adjs[i].id;i++);for(var j=(i+1)%len,k=0;id!=adjs[j].id;j=(j+1)%len){adjs[j].dist=k++;}}},onClick:function(id,opt){if(this.root!=id&&!this.busy){this.busy=true;this.root=id;that=this;this.controller.onBeforeCompute(this.graph.getNode(id));var obj=this.getNodeAndParentAngle(id);this.tagChildren(obj.parent,id);this.parent=obj.parent;this.compute('end');var thetaDiff=obj.theta-obj.parent.endPos.theta;this.graph.eachNode(function(elem){elem.endPos.set(elem.endPos.getp().add($P(thetaDiff,0)));});var mode=this.config.interpolation;opt=$.merge({onComplete:$.empty},opt||{});this.fx.animate($.merge({hideLabels:true,modes:[mode]},opt,{onComplete:function(){that.busy=false;opt.onComplete();}}));}}});$jit.RGraph.$extend=true;(function(RGraph){RGraph.Op=new Class({Implements:Graph.Op});RGraph.Plot=new Class({Implements:Graph.Plot});RGraph.Label={};RGraph.Label.Native=new Class({Implements:Graph.Label.Native});RGraph.Label.SVG=new Class({Implements:Graph.Label.SVG,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize();var labelPos={x:Math.round(pos.x*sx+ox+radius.width / 2),y:Math.round(pos.y*sy+oy+radius.height / 2)};tag.setAttribute('x',labelPos.x);tag.setAttribute('y',labelPos.y);controller.onPlaceLabel(tag,node);}});RGraph.Label.HTML=new Class({Implements:Graph.Label.HTML,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize();var labelPos={x:Math.round(pos.x*sx+ox+radius.width / 2),y:Math.round(pos.y*sy+oy+radius.height / 2)};var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.display=this.fitsInCanvas(labelPos,canvas)?'':'none';controller.onPlaceLabel(tag,node);}});RGraph.Plot.NodeTypes=new Class({'none':{'render':$.empty,'contains':$.lambda(false)},'circle':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.circle.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.circle.contains(npos,pos,dim);}},'ellipse':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');this.nodeHelper.ellipse.render('fill',pos,width,height,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');return this.nodeHelper.ellipse.contains(npos,pos,width,height);}},'square':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.square.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.square.contains(npos,pos,dim);}},'rectangle':{'render':function(node,canvas){var pos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');this.nodeHelper.rectangle.render('fill',pos,width,height,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),width=node.getData('width'),height=node.getData('height');return this.nodeHelper.rectangle.contains(npos,pos,width,height);}},'triangle':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.triangle.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.triangle.contains(npos,pos,dim);}},'star':{'render':function(node,canvas){var pos=node.pos.getc(true),dim=node.getData('dim');this.nodeHelper.star.render('fill',pos,dim,canvas);},'contains':function(node,pos){var npos=node.pos.getc(true),dim=node.getData('dim');return this.nodeHelper.star.contains(npos,pos,dim);}}});RGraph.Plot.EdgeTypes=new Class({'none':$.empty,'line':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);this.edgeHelper.line.render(from,to,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);return this.edgeHelper.line.contains(from,to,pos,this.edge.epsilon);}},'arrow':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),dim=adj.getData('dim'),direction=adj.data.$direction,inv=(direction&&direction.length>1&&direction[0]!=adj.nodeFrom.id);this.edgeHelper.arrow.render(from,to,dim,inv,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true);return this.edgeHelper.arrow.contains(from,to,pos,this.edge.epsilon);}}});})($jit.RGraph);Complex.prototype.moebiusTransformation=function(c){var num=this.add(c);var den=c.$conjugate().$prod(this);den.x++;return num.$div(den);};Graph.Util.moebiusTransformation=function(graph,pos,prop,startPos,flags){this.eachNode(graph,function(elem){for(var i=0;i<prop.length;i++){var p=pos[i].scale(-1),property=startPos?startPos:prop[i];elem.getPos(prop[i]).set(elem.getPos(property).getc().moebiusTransformation(p));}},flags);};$jit.Hypertree=new Class({Implements:[Loader,Extras,Layouts.Radial],initialize:function(controller){var $Hypertree=$jit.Hypertree;var config={radius:"auto",offset:0,Edge:{type:'hyperline'},duration:1500,fps:35};this.controller=this.config=$.merge(Options("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label"),config,controller);var canvasConfig=this.config;if(canvasConfig.useCanvas){this.canvas=canvasConfig.useCanvas;this.config.labelContainer=this.canvas.id+'-label';}else{if(canvasConfig.background){canvasConfig.background=$.merge({type:'Circles'},canvasConfig.background);}
this.canvas=new Canvas(this,canvasConfig);this.config.labelContainer=(typeof canvasConfig.injectInto=='string'?canvasConfig.injectInto:canvasConfig.injectInto.id)+'-label';}
this.graphOptions={'complex':false,'Node':{'selected':false,'exist':true,'drawn':true}};this.graph=new Graph(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new $Hypertree.Label[canvasConfig.Label.type](this);this.fx=new $Hypertree.Plot(this,$Hypertree);this.op=new $Hypertree.Op(this);this.json=null;this.root=null;this.busy=false;this.initializeExtras();},createLevelDistanceFunc:function(){var r=this.getRadius();var depth=0,max=Math.max,config=this.config;this.graph.eachNode(function(node){depth=max(node._depth,depth);},"ignore");depth++;var genDistFunc=function(a){return function(node){node.scale=r;var d=node._depth+1;var acum=0,pow=Math.pow;while(d){acum+=pow(a,d--);}
return acum-config.offset;};};for(var i=0.51;i<=1;i+=0.01){var valSeries=(1-Math.pow(i,depth))/(1-i);if(valSeries>=2){return genDistFunc(i-0.01);}}
return genDistFunc(0.75);},getRadius:function(){var rad=this.config.radius;if(rad!=="auto"){return rad;}
var s=this.canvas.getSize();return Math.min(s.width,s.height)/ 2;},refresh:function(reposition){if(reposition){this.reposition();this.graph.eachNode(function(node){node.startPos.rho=node.pos.rho=node.endPos.rho;node.startPos.theta=node.pos.theta=node.endPos.theta;});}else{this.compute();}
this.plot();},reposition:function(){this.compute('end');var vector=this.graph.getNode(this.root).pos.getc().scale(-1);Graph.Util.moebiusTransformation(this.graph,[vector],['end'],'end',"ignore");this.graph.eachNode(function(node){if(node.ignore){node.endPos.rho=node.pos.rho;node.endPos.theta=node.pos.theta;}});},plot:function(){this.fx.plot();},onClick:function(id,opt){var pos=this.graph.getNode(id).pos.getc(true);this.move(pos,opt);},move:function(pos,opt){var versor=$C(pos.x,pos.y);if(this.busy===false&&versor.norm()<1){this.busy=true;var root=this.graph.getClosestNodeToPos(versor),that=this;this.graph.computeLevels(root.id,0);this.controller.onBeforeCompute(root);opt=$.merge({onComplete:$.empty},opt||{});this.fx.animate($.merge({modes:['moebius'],hideLabels:true},opt,{onComplete:function(){that.busy=false;opt.onComplete();}}),versor);}}});$jit.Hypertree.$extend=true;(function(Hypertree){Hypertree.Op=new Class({Implements:Graph.Op});Hypertree.Plot=new Class({Implements:Graph.Plot});Hypertree.Label={};Hypertree.Label.Native=new Class({Implements:Graph.Label.Native,initialize:function(viz){this.viz=viz;},renderLabel:function(canvas,node,controller){var ctx=canvas.getCtx();var coord=node.pos.getc(true);var s=this.viz.getRadius();ctx.fillText(node.name,coord.x*s,coord.y*s);}});Hypertree.Label.SVG=new Class({Implements:Graph.Label.SVG,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize(),r=this.viz.getRadius();var labelPos={x:Math.round((pos.x*sx)*r+ox+radius.width / 2),y:Math.round((pos.y*sy)*r+oy+radius.height / 2)};tag.setAttribute('x',labelPos.x);tag.setAttribute('y',labelPos.y);controller.onPlaceLabel(tag,node);}});Hypertree.Label.HTML=new Class({Implements:Graph.Label.HTML,initialize:function(viz){this.viz=viz;},placeLabel:function(tag,node,controller){var pos=node.pos.getc(true),canvas=this.viz.canvas,ox=canvas.translateOffsetX,oy=canvas.translateOffsetY,sx=canvas.scaleOffsetX,sy=canvas.scaleOffsetY,radius=canvas.getSize(),r=this.viz.getRadius();var labelPos={x:Math.round((pos.x*sx)*r+ox+radius.width / 2),y:Math.round((pos.y*sy)*r+oy+radius.height / 2)};var style=tag.style;style.left=labelPos.x+'px';style.top=labelPos.y+'px';style.display=this.fitsInCanvas(labelPos,canvas)?'':'none';controller.onPlaceLabel(tag,node);}});Hypertree.Plot.NodeTypes=new Class({'none':{'render':$.empty,'contains':$.lambda(false)},'circle':{'render':function(node,canvas){var nconfig=this.node,dim=node.getData('dim'),p=node.pos.getc();dim=nconfig.transform?dim*(1-p.squaredNorm()):dim;p.$scale(node.scale);if(dim>0.2){this.nodeHelper.circle.render('fill',p,dim,canvas);}},'contains':function(node,pos){var dim=node.getData('dim'),npos=node.pos.getc().$scale(node.scale);return this.nodeHelper.circle.contains(npos,pos,dim);}},'ellipse':{'render':function(node,canvas){var pos=node.pos.getc().$scale(node.scale),width=node.getData('width'),height=node.getData('height');this.nodeHelper.ellipse.render('fill',pos,width,height,canvas);},'contains':function(node,pos){var width=node.getData('width'),height=node.getData('height'),npos=node.pos.getc().$scale(node.scale);return this.nodeHelper.circle.contains(npos,pos,width,height);}},'square':{'render':function(node,canvas){var nconfig=this.node,dim=node.getData('dim'),p=node.pos.getc();dim=nconfig.transform?dim*(1-p.squaredNorm()):dim;p.$scale(node.scale);if(dim>0.2){this.nodeHelper.square.render('fill',p,dim,canvas);}},'contains':function(node,pos){var dim=node.getData('dim'),npos=node.pos.getc().$scale(node.scale);return this.nodeHelper.square.contains(npos,pos,dim);}},'rectangle':{'render':function(node,canvas){var nconfig=this.node,width=node.getData('width'),height=node.getData('height'),pos=node.pos.getc();width=nconfig.transform?width*(1-pos.squaredNorm()):width;height=nconfig.transform?height*(1-pos.squaredNorm()):height;pos.$scale(node.scale);if(width>0.2&&height>0.2){this.nodeHelper.rectangle.render('fill',pos,width,height,canvas);}},'contains':function(node,pos){var width=node.getData('width'),height=node.getData('height'),npos=node.pos.getc().$scale(node.scale);return this.nodeHelper.square.contains(npos,pos,width,height);}},'triangle':{'render':function(node,canvas){var nconfig=this.node,dim=node.getData('dim'),p=node.pos.getc();dim=nconfig.transform?dim*(1-p.squaredNorm()):dim;p.$scale(node.scale);if(dim>0.2){this.nodeHelper.triangle.render('fill',p,dim,canvas);}},'contains':function(node,pos){var dim=node.getData('dim'),npos=node.pos.getc().$scale(node.scale);return this.nodeHelper.triangle.contains(npos,pos,dim);}},'star':{'render':function(node,canvas){var nconfig=this.node,dim=node.getData('dim'),p=node.pos.getc();dim=nconfig.transform?dim*(1-p.squaredNorm()):dim;p.$scale(node.scale);if(dim>0.2){this.nodeHelper.star.render('fill',p,dim,canvas);}},'contains':function(node,pos){var dim=node.getData('dim'),npos=node.pos.getc().$scale(node.scale);return this.nodeHelper.star.contains(npos,pos,dim);}}});Hypertree.Plot.EdgeTypes=new Class({'none':$.empty,'line':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),r=adj.nodeFrom.scale;this.edgeHelper.line.render({x:from.x*r,y:from.y*r},{x:to.x*r,y:to.y*r},canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),r=adj.nodeFrom.scale;this.edgeHelper.line.contains({x:from.x*r,y:from.y*r},{x:to.x*r,y:to.y*r},pos,this.edge.epsilon);}},'arrow':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),r=adj.nodeFrom.scale,dim=adj.getData('dim'),direction=adj.data.$direction,inv=(direction&&direction.length>1&&direction[0]!=adj.nodeFrom.id);this.edgeHelper.arrow.render({x:from.x*r,y:from.y*r},{x:to.x*r,y:to.y*r},dim,inv,canvas);},'contains':function(adj,pos){var from=adj.nodeFrom.pos.getc(true),to=adj.nodeTo.pos.getc(true),r=adj.nodeFrom.scale;this.edgeHelper.arrow.contains({x:from.x*r,y:from.y*r},{x:to.x*r,y:to.y*r},pos,this.edge.epsilon);}},'hyperline':{'render':function(adj,canvas){var from=adj.nodeFrom.pos.getc(),to=adj.nodeTo.pos.getc(),dim=this.viz.getRadius();this.edgeHelper.hyperline.render(from,to,dim,canvas);},'contains':$.lambda(false)}});})($jit.Hypertree);})();