(function(){'use strict';horizonApp.controller('DummyCtrl',function(){});}());(function(){'use strict';horizonApp.directive('notBlank',function(){return{require:'ngModel',link:function(scope,elm,attrs,ctrl){ctrl.$parsers.unshift(function(viewValue){if(viewValue.length){ctrl.$setValidity('notBlank',true);return viewValue;}
ctrl.$setValidity('notBlank',false);return undefined;});}};});}());(function(){'use strict';angular.module('hz.conf',[]).constant('hzConfig',{debug:null,static_url:null,ajax:{queue_limit:null},spinner_options:{inline:{lines:10,length:5,width:2,radius:3,color:'#000',speed:0.8,trail:50,zIndex:100},modal:{lines:10,length:15,width:4,radius:10,color:'#000',speed:0.8,trail:50},line_chart:{lines:10,length:15,width:4,radius:11,color:'#000',speed:0.8,trail:50}}});}());(function(){'use strict';function utils(hzConfig,$log,$rootScope,$compile){return{log:function(msg,lvl){if(hzConfig.debug){($log[lvl]||$log.log)(msg);}},capitalize:function(string){return string.charAt(0).toUpperCase()+string.slice(1);},humanizeNumbers:function(number){return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",");},truncate:function(string,size,includeEllipsis){if(string.length>size){if(includeEllipsis){return string.substring(0,(size-3))+"&hellip;";}
return string.substring(0,size);}
return string;},loadAngular:function(element){try{$compile(element)($rootScope);$rootScope.$apply();}catch(err){}}};}
angular.module('hz.utils.hzUtils',['hz.conf']).service('hzUtils',['hzConfig','$log','$rootScope','$compile',utils]);angular.module('hz.utils',['hz.utils.hzUtils']);}());(function($){$.cookie=function(key,value,options){if(arguments.length>1&&(!/Object/.test(Object.prototype.toString.call(value))||value===null||value===undefined)){options=$.extend({},options);if(value===null||value===undefined){options.expires=-1;}
if(typeof options.expires==='number'){var days=options.expires,t=options.expires=new Date();t.setDate(t.getDate()+days);}
value=String(value);return(document.cookie=[encodeURIComponent(key),'=',options.raw?value:encodeURIComponent(value),options.expires?'; expires='+options.expires.toUTCString():'',options.path?'; path='+options.path:'',options.domain?'; domain='+options.domain:'',options.secure?'; secure':''].join(''));}
options=value||{};var decode=options.raw?function(s){return s;}:decodeURIComponent;var pairs=document.cookie.split('; ');for(var i=0,pair;pair=pairs[i]&&pairs[i].split('=');i++){if(decode(pair[0])===key)return decode(pair[1]||'');}
return null;};})(jQuery);(function($,window,document,undefined){$.fn.quicksearch=function(target,opt){var timeout,cache,rowcache,jq_results,val='',e=this,options=$.extend({delay:100,selector:null,stripeRows:null,loader:null,noResults:'',bind:'keyup',onBefore:function(){return;},onAfter:function(){return;},show:function(){this.style.display="";},hide:function(){this.style.display="none";},prepareQuery:function(val){return val.toLowerCase().split(' ');},testQuery:function(query,txt,_row){for(var i=0;i<query.length;i+=1){if(txt.indexOf(query[i])===-1){return false;}}
return true;}},opt);this.go=function(){var i=0,noresults=true,query=options.prepareQuery(val),val_empty=(val.replace(' ','').length===0);for(var i=0,len=rowcache.length;i<len;i++){if(val_empty||options.testQuery(query,cache[i],rowcache[i])){options.show.apply(rowcache[i]);noresults=false;}else{options.hide.apply(rowcache[i]);}}
if(noresults){this.results(false);}else{this.results(true);this.stripe();}
this.loader(false);options.onAfter();return this;};this.stripe=function(){if(typeof options.stripeRows==="object"&&options.stripeRows!==null)
{var joined=options.stripeRows.join(' ');var stripeRows_length=options.stripeRows.length;jq_results.not(':hidden').each(function(i){$(this).removeClass(joined).addClass(options.stripeRows[i%stripeRows_length]);});}
return this;};this.strip_html=function(input){var output=input.replace(new RegExp('<[^<]+\>','g'),"");output=$.trim(output.toLowerCase());return output;};this.results=function(bool){if(typeof options.noResults==="string"&&options.noResults!==""){if(bool){$(options.noResults).hide();}else{$(options.noResults).show();}}
return this;};this.loader=function(bool){if(typeof options.loader==="string"&&options.loader!==""){(bool)?$(options.loader).show():$(options.loader).hide();}
return this;};this.cache=function(){jq_results=$(target);if(typeof options.noResults==="string"&&options.noResults!==""){jq_results=jq_results.not(options.noResults);}
var t=(typeof options.selector==="string")?jq_results.find(options.selector):$(target).not(options.noResults);cache=t.map(function(){return e.strip_html(this.innerHTML);});rowcache=jq_results.map(function(){return this;});return this.go();};this.trigger=function(){this.loader(true);options.onBefore();window.clearTimeout(timeout);timeout=window.setTimeout(function(){e.go();},options.delay);return this;};this.cache();this.results(true);this.stripe();this.loader(false);return this.each(function(){$(this).bind(options.bind,function(){val=$(this).val();e.trigger();});});};}(jQuery,this,document));!(function($){"use strict";$.extend({tablesorter:new function(){var ts=this;ts.version="2.14.5";ts.parsers=[];ts.widgets=[];ts.defaults={theme:'default',widthFixed:false,showProcessing:false,headerTemplate:'{content}',onRenderTemplate:null,onRenderHeader:null,cancelSelection:true,tabIndex:true,dateFormat:'mmddyyyy',sortMultiSortKey:'shiftKey',sortResetKey:'ctrlKey',usNumberFormat:true,delayInit:false,serverSideSorting:false,headers:{},ignoreCase:true,sortForce:null,sortList:[],sortAppend:null,sortStable:false,sortInitialOrder:'asc',sortLocaleCompare:false,sortReset:false,sortRestart:false,emptyTo:'bottom',stringTo:'max',textExtraction:'simple',textSorter:null,numberSorter:null,widgets:[],widgetOptions:{zebra:['even','odd']},initWidgets:true,initialized:null,tableClass:'',cssAsc:'',cssDesc:'',cssHeader:'',cssHeaderRow:'',cssProcessing:'',cssChildRow:'tablesorter-childRow',cssIcon:'tablesorter-icon',cssInfoBlock:'tablesorter-infoOnly',selectorHeaders:'> thead th, > thead td',selectorSort:'th, td',selectorRemove:'.remove-me',debug:false,headerList:[],empties:{},strings:{},parsers:[]};ts.css={table:'tablesorter',childRow:'tablesorter-childRow',header:'tablesorter-header',headerRow:'tablesorter-headerRow',icon:'tablesorter-icon',info:'tablesorter-infoOnly',processing:'tablesorter-processing',sortAsc:'tablesorter-headerAsc',sortDesc:'tablesorter-headerDesc'};function log(){var s=arguments.length>1?Array.prototype.slice.call(arguments):arguments[0];if(typeof console!=="undefined"&&typeof console.log!=="undefined"){console.log(s);}else{alert(s);}}
function benchmark(s,d){log(s+" ("+(new Date().getTime()-d.getTime())+"ms)");}
ts.log=log;ts.benchmark=benchmark;function isEmptyObject(obj){for(var name in obj){return false;}
return true;}
function getElementText(table,node,cellIndex){if(!node){return"";}
var c=table.config,t=c.textExtraction,text="";if(t==="simple"){if(c.supportsTextContent){text=node.textContent;}else{text=$(node).text();}}else{if(typeof t==="function"){text=t(node,table,cellIndex);}else if(typeof t==="object"&&t.hasOwnProperty(cellIndex)){text=t[cellIndex](node,table,cellIndex);}else{text=c.supportsTextContent?node.textContent:$(node).text();}}
return $.trim(text);}
function detectParserForColumn(table,rows,rowIndex,cellIndex){var cur,i=ts.parsers.length,node=false,nodeValue='',keepLooking=true;while(nodeValue===''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=rows[rowIndex].cells[cellIndex];nodeValue=getElementText(table,node,cellIndex);if(table.config.debug){log('Checking if value was empty on row '+rowIndex+', column: '+cellIndex+': "'+nodeValue+'"');}}else{keepLooking=false;}}
while(--i>=0){cur=ts.parsers[i];if(cur&&cur.id!=='text'&&cur.is&&cur.is(nodeValue,table,node)){return cur;}}
return ts.getParserById('text');}
function buildParserCache(table){var c=table.config,tb=c.$tbodies=c.$table.children('tbody:not(.'+c.cssInfoBlock+')'),rows,list,l,i,h,ch,p,time,parsersDebug="";if(tb.length===0){return c.debug?log('*Empty table!* Not building a parser cache'):'';}else if(c.debug){time=new Date();log('Detecting parsers for each column');}
rows=tb[0].rows;if(rows[0]){list=[];l=rows[0].cells.length;for(i=0;i<l;i++){h=c.$headers.filter(':not([colspan])');h=h.add(c.$headers.filter('[colspan="1"]')).filter('[data-column="'+i+'"]:last');ch=c.headers[i];p=ts.getParserById(ts.getData(h,ch,'sorter'));c.empties[i]=ts.getData(h,ch,'empty')||c.emptyTo||(c.emptyToBottom?'bottom':'top');c.strings[i]=ts.getData(h,ch,'string')||c.stringTo||'max';if(!p){p=detectParserForColumn(table,rows,-1,i);}
if(c.debug){parsersDebug+="column:"+i+"; parser:"+p.id+"; string:"+c.strings[i]+'; empty: '+c.empties[i]+"\n";}
list.push(p);}}
if(c.debug){log(parsersDebug);benchmark("Completed detecting parsers",time);}
c.parsers=list;}
function buildCache(table){var b=table.tBodies,tc=table.config,totalRows,totalCells,parsers=tc.parsers,t,v,i,j,k,c,cols,cacheTime,colMax=[];tc.cache={};if(!parsers){return tc.debug?log('*Empty table!* Not building a cache'):'';}
if(tc.debug){cacheTime=new Date();}
if(tc.showProcessing){ts.isProcessing(table,true);}
for(k=0;k<b.length;k++){tc.cache[k]={row:[],normalized:[]};if(!$(b[k]).hasClass(tc.cssInfoBlock)){totalRows=(b[k]&&b[k].rows.length)||0;totalCells=(b[k].rows[0]&&b[k].rows[0].cells.length)||0;for(i=0;i<totalRows;++i){c=$(b[k].rows[i]);cols=[];if(c.hasClass(tc.cssChildRow)){tc.cache[k].row[tc.cache[k].row.length-1]=tc.cache[k].row[tc.cache[k].row.length-1].add(c);continue;}
tc.cache[k].row.push(c);for(j=0;j<totalCells;++j){t=getElementText(table,c[0].cells[j],j);v=parsers[j].format(t,table,c[0].cells[j],j);cols.push(v);if((parsers[j].type||'').toLowerCase()==="numeric"){colMax[j]=Math.max(Math.abs(v)||0,colMax[j]||0);}}
cols.push(tc.cache[k].normalized.length);tc.cache[k].normalized.push(cols);}
tc.cache[k].colMax=colMax;}}
if(tc.showProcessing){ts.isProcessing(table);}
if(tc.debug){benchmark("Building cache for "+totalRows+" rows",cacheTime);}}
function appendToTable(table,init){var c=table.config,wo=c.widgetOptions,b=table.tBodies,rows=[],c2=c.cache,r,n,totalRows,checkCell,$bk,$tb,i,j,k,l,pos,appendTime;if(isEmptyObject(c2)){return;}
if(c.debug){appendTime=new Date();}
for(k=0;k<b.length;k++){$bk=$(b[k]);if($bk.length&&!$bk.hasClass(c.cssInfoBlock)){$tb=ts.processTbody(table,$bk,true);r=c2[k].row;n=c2[k].normalized;totalRows=n.length;checkCell=totalRows?(n[0].length-1):0;for(i=0;i<totalRows;i++){pos=n[i][checkCell];rows.push(r[pos]);if(!c.appender||(c.pager&&(!c.pager.removeRows||!wo.pager_removeRows)&&!c.pager.ajax)){l=r[pos].length;for(j=0;j<l;j++){$tb.append(r[pos][j]);}}}
ts.processTbody(table,$tb,false);}}
if(c.appender){c.appender(table,rows);}
if(c.debug){benchmark("Rebuilt table",appendTime);}
if(!init&&!c.appender){ts.applyWidget(table);}
$(table).trigger("sortEnd",table);$(table).trigger("updateComplete",table);}
function computeThIndexes(t){var matrix=[],lookup={},cols=0,trs=$(t).find('thead:eq(0), tfoot').children('tr'),i,j,k,l,c,cells,rowIndex,cellId,rowSpan,colSpan,firstAvailCol,matrixrow;for(i=0;i<trs.length;i++){cells=trs[i].cells;for(j=0;j<cells.length;j++){c=cells[j];rowIndex=c.parentNode.rowIndex;cellId=rowIndex+"-"+c.cellIndex;rowSpan=c.rowSpan||1;colSpan=c.colSpan||1;if(typeof(matrix[rowIndex])==="undefined"){matrix[rowIndex]=[];}
for(k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])==="undefined"){firstAvailCol=k;break;}}
lookup[cellId]=firstAvailCol;cols=Math.max(firstAvailCol,cols);$(c).attr({'data-column':firstAvailCol});for(k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])==="undefined"){matrix[k]=[];}
matrixrow=matrix[k];for(l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}
t.config.columns=cols+1;return lookup;}
function formatSortingOrder(v){return(/^d/i.test(v)||v===1);}
function buildHeaders(table){var header_index=computeThIndexes(table),ch,$t,h,i,t,lock,time,c=table.config;c.headerList=[];c.headerContent=[];if(c.debug){time=new Date();}
i=c.cssIcon?'<i class="'+(c.cssIcon===ts.css.icon?ts.css.icon:c.cssIcon+' '+ts.css.icon)+'"></i>':'';c.$headers=$(table).find(c.selectorHeaders).each(function(index){$t=$(this);ch=c.headers[index];c.headerContent[index]=$(this).html();t=c.headerTemplate.replace(/\{content\}/g,$(this).html()).replace(/\{icon\}/g,i);if(c.onRenderTemplate){h=c.onRenderTemplate.apply($t,[index,t]);if(h&&typeof h==='string'){t=h;}}
$(this).html('<div class="tablesorter-header-inner">'+t+'</div>');if(c.onRenderHeader){c.onRenderHeader.apply($t,[index]);}
this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(ts.getData($t,ch,'sortInitialOrder')||c.sortInitialOrder)?[1,0,2]:[0,1,2];this.count=-1;this.lockedOrder=false;lock=ts.getData($t,ch,'lockedOrder')||false;if(typeof lock!=='undefined'&&lock!==false){this.order=this.lockedOrder=formatSortingOrder(lock)?[1,1,1]:[0,0,0];}
$t.addClass(ts.css.header+' '+c.cssHeader);c.headerList[index]=this;$t.parent().addClass(ts.css.headerRow+' '+c.cssHeaderRow);if(c.tabIndex){$t.attr("tabindex",0);}});updateHeader(table);if(c.debug){benchmark("Built headers:",time);log(c.$headers);}}
function commonUpdate(table,resort,callback){var c=table.config;c.$table.find(c.selectorRemove).remove();buildParserCache(table);buildCache(table);checkResort(c.$table,resort,callback);}
function updateHeader(table){var s,c=table.config;c.$headers.each(function(index,th){s=ts.getData(th,c.headers[index],'sorter')==='false';th.sortDisabled=s;$(th)[s?'addClass':'removeClass']('sorter-false');});}
function setHeadersCss(table){var f,i,j,l,c=table.config,list=c.sortList,css=[ts.css.sortAsc+' '+c.cssAsc,ts.css.sortDesc+' '+c.cssDesc],$t=$(table).find('tfoot tr').children().removeClass(css.join(' '));c.$headers.removeClass(css.join(' '));l=list.length;for(i=0;i<l;i++){if(list[i][1]!==2){f=c.$headers.not('.sorter-false').filter('[data-column="'+list[i][0]+'"]'+(l===1?':last':''));if(f.length){for(j=0;j<f.length;j++){if(!f[j].sortDisabled){f.eq(j).addClass(css[list[i][1]]);if($t.length){$t.filter('[data-column="'+list[i][0]+'"]').eq(j).addClass(css[list[i][1]]);}}}}}}}
function fixColumnWidth(table){if(table.config.widthFixed&&$(table).find('colgroup').length===0){var colgroup=$('<colgroup>'),overallWidth=$(table).width();$(table.tBodies[0]).find("tr:first").children("td:visible").each(function(){colgroup.append($('<col>').css('width',parseInt(($(this).width()/overallWidth)*1000,10)/10+'%'));});$(table).prepend(colgroup);}}
function updateHeaderSortCount(table,list){var s,t,o,c=table.config,sl=list||c.sortList;c.sortList=[];$.each(sl,function(i,v){s=[parseInt(v[0],10),parseInt(v[1],10)];o=c.$headers[s[0]];if(o){c.sortList.push(s);t=$.inArray(s[1],o.order);o.count=t>=0?t:s[1]%(c.sortReset?3:2);}});}
function getCachedSortType(parsers,i){return(parsers&&parsers[i])?parsers[i].type||'':'';}
function initSort(table,cell,e){var a,i,j,o,s,c=table.config,k=!e[c.sortMultiSortKey],$this=$(table);$this.trigger("sortStart",table);cell.count=e[c.sortResetKey]?2:(cell.count+1)%(c.sortReset?3:2);if(c.sortRestart){i=cell;c.$headers.each(function(){if(this!==i&&(k||!$(this).is('.'+ts.css.sortDesc+',.'+ts.css.sortAsc))){this.count=-1;}});}
i=cell.column;if(k){c.sortList=[];if(c.sortForce!==null){a=c.sortForce;for(j=0;j<a.length;j++){if(a[j][0]!==i){c.sortList.push(a[j]);}}}
o=cell.order[cell.count];if(o<2){c.sortList.push([i,o]);if(cell.colSpan>1){for(j=1;j<cell.colSpan;j++){c.sortList.push([i+j,o]);}}}}else{if(c.sortAppend&&c.sortList.length>1){if(ts.isValueInArray(c.sortAppend[0][0],c.sortList)){c.sortList.pop();}}
if(ts.isValueInArray(i,c.sortList)){for(j=0;j<c.sortList.length;j++){s=c.sortList[j];o=c.$headers[s[0]];if(s[0]===i){s[1]=o.order[cell.count];if(s[1]===2){c.sortList.splice(j,1);o.count=-1;}}}}else{o=cell.order[cell.count];if(o<2){c.sortList.push([i,o]);if(cell.colSpan>1){for(j=1;j<cell.colSpan;j++){c.sortList.push([i+j,o]);}}}}}
if(c.sortAppend!==null){a=c.sortAppend;for(j=0;j<a.length;j++){if(a[j][0]!==i){c.sortList.push(a[j]);}}}
$this.trigger("sortBegin",table);setTimeout(function(){setHeadersCss(table);multisort(table);appendToTable(table);},1);}
function multisort(table){var i,k,num,col,colMax,cache,lc,order,orgOrderCol,sortTime,sort,x,y,dir=0,c=table.config,cts=c.textSorter||'',sortList=c.sortList,l=sortList.length,bl=table.tBodies.length;if(c.serverSideSorting||isEmptyObject(c.cache)){return;}
if(c.debug){sortTime=new Date();}
for(k=0;k<bl;k++){colMax=c.cache[k].colMax;cache=c.cache[k].normalized;lc=cache.length;orgOrderCol=(cache&&cache[0])?cache[0].length-1:0;cache.sort(function(a,b){for(i=0;i<l;i++){col=sortList[i][0];order=sortList[i][1];dir=order===0;if(c.sortStable&&a[col]===b[col]&&l===1){return a[orgOrderCol]-b[orgOrderCol];}
num=/n/i.test(getCachedSortType(c.parsers,col));if(num&&c.strings[col]){if(typeof(c.string[c.strings[col]])==='boolean'){num=(dir?1:-1)*(c.string[c.strings[col]]?-1:1);}else{num=(c.strings[col])?c.string[c.strings[col]]||0:0;}
sort=c.numberSorter?c.numberSorter(x[col],y[col],dir,colMax[col],table):ts['sortNumeric'+(dir?'Asc':'Desc')](a[col],b[col],num,colMax[col],col,table);}else{x=dir?a:b;y=dir?b:a;if(typeof(cts)==='function'){sort=cts(x[col],y[col],dir,col,table);}else if(typeof(cts)==='object'&&cts.hasOwnProperty(col)){sort=cts[col](x[col],y[col],dir,col,table);}else{sort=ts['sortNatural'+(dir?'Asc':'Desc')](a[col],b[col],col,table,c);}}
if(sort){return sort;}}
return a[orgOrderCol]-b[orgOrderCol];});}
if(c.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time",sortTime);}}
function resortComplete($table,callback){var c=$table[0].config;if(c.pager&&!c.pager.ajax){$table.trigger('updateComplete');}
if(typeof callback==="function"){callback($table[0]);}}
function checkResort($table,flag,callback){if(flag!==false&&!$table[0].isProcessing){$table.trigger("sorton",[$table[0].config.sortList,function(){resortComplete($table,callback);}]);}else{resortComplete($table,callback);}}
function bindEvents(table){var c=table.config,$this=c.$table,j,downTime;c.$headers.find(c.selectorSort).add(c.$headers.filter(c.selectorSort)).unbind('mousedown.tablesorter mouseup.tablesorter sort.tablesorter keypress.tablesorter').bind('mousedown.tablesorter mouseup.tablesorter sort.tablesorter keypress.tablesorter',function(e,external){if(((e.which||e.button)!==1&&!/sort|keypress/.test(e.type))||(e.type==='keypress'&&e.which!==13)){return;}
if(e.type==='mouseup'&&external!==true&&(new Date().getTime()-downTime>250)){return;}
if(e.type==='mousedown'){downTime=new Date().getTime();return e.target.tagName==="INPUT"?'':!c.cancelSelection;}
if(c.delayInit&&isEmptyObject(c.cache)){buildCache(table);}
var $cell=/TH|TD/.test(this.tagName)?$(this):$(this).parents('th, td').filter(':first'),cell=$cell[0];if(!cell.sortDisabled){initSort(table,cell,e);}});if(c.cancelSelection){c.$headers.attr('unselectable','on').bind('selectstart',false).css({'user-select':'none','MozUserSelect':'none'});}
$this.unbind('sortReset update updateRows updateCell updateAll addRows sorton appendCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave '.split(' ').join('.tablesorter ')).bind("sortReset.tablesorter",function(e){e.stopPropagation();c.sortList=[];setHeadersCss(table);multisort(table);appendToTable(table);}).bind("updateAll.tablesorter",function(e,resort,callback){e.stopPropagation();ts.refreshWidgets(table,true,true);ts.restoreHeaders(table);buildHeaders(table);bindEvents(table);commonUpdate(table,resort,callback);}).bind("update.tablesorter updateRows.tablesorter",function(e,resort,callback){e.stopPropagation();updateHeader(table);commonUpdate(table,resort,callback);}).bind("updateCell.tablesorter",function(e,cell,resort,callback){e.stopPropagation();$this.find(c.selectorRemove).remove();var l,row,icell,$tb=$this.find('tbody'),tbdy=$tb.index($(cell).parents('tbody').filter(':first')),$row=$(cell).parents('tr').filter(':first');cell=$(cell)[0];if($tb.length&&tbdy>=0){row=$tb.eq(tbdy).find('tr').index($row);icell=cell.cellIndex;l=c.cache[tbdy].normalized[row].length-1;c.cache[tbdy].row[table.config.cache[tbdy].normalized[row][l]]=$row;c.cache[tbdy].normalized[row][icell]=c.parsers[icell].format(getElementText(table,cell,icell),table,cell,icell);checkResort($this,resort,callback);}}).bind("addRows.tablesorter",function(e,$row,resort,callback){e.stopPropagation();if(isEmptyObject(c.cache)){updateHeader(table);commonUpdate(table,resort,callback);}else{var i,rows=$row.filter('tr').length,dat=[],l=$row[0].cells.length,tbdy=$this.find('tbody').index($row.parents('tbody').filter(':first'));if(!c.parsers){buildParserCache(table);}
for(i=0;i<rows;i++){for(j=0;j<l;j++){dat[j]=c.parsers[j].format(getElementText(table,$row[i].cells[j],j),table,$row[i].cells[j],j);}
dat.push(c.cache[tbdy].row.length);c.cache[tbdy].row.push([$row[i]]);c.cache[tbdy].normalized.push(dat);dat=[];}
checkResort($this,resort,callback);}}).bind("sorton.tablesorter",function(e,list,callback,init){var c=table.config;e.stopPropagation();$this.trigger("sortStart",this);updateHeaderSortCount(table,list);setHeadersCss(table);if(c.delayInit&&isEmptyObject(c.cache)){buildCache(table);}
$this.trigger("sortBegin",this);multisort(table);appendToTable(table,init);if(typeof callback==="function"){callback(table);}}).bind("appendCache.tablesorter",function(e,callback,init){e.stopPropagation();appendToTable(table,init);if(typeof callback==="function"){callback(table);}}).bind("applyWidgetId.tablesorter",function(e,id){e.stopPropagation();ts.getWidgetById(id).format(table,c,c.widgetOptions);}).bind("applyWidgets.tablesorter",function(e,init){e.stopPropagation();ts.applyWidget(table,init);}).bind("refreshWidgets.tablesorter",function(e,all,dontapply){e.stopPropagation();ts.refreshWidgets(table,all,dontapply);}).bind("destroy.tablesorter",function(e,c,cb){e.stopPropagation();ts.destroy(table,c,cb);});}
ts.construct=function(settings){return this.each(function(){var table=this,c=$.extend(true,{},ts.defaults,settings);if(!table.hasInitialized&&ts.buildTable&&this.tagName!=='TABLE'){ts.buildTable(table,c);}
ts.setup(table,c);});};ts.setup=function(table,c){if(!table||!table.tHead||table.tBodies.length===0||table.hasInitialized===true){return c.debug?log('stopping initialization! No table, thead, tbody or tablesorter has already been initialized'):'';}
var k='',$this=$(table),m=$.metadata;table.hasInitialized=false;table.isProcessing=true;table.config=c;$.data(table,"tablesorter",c);if(c.debug){$.data(table,'startoveralltimer',new Date());}
c.supportsTextContent=$('<span>x</span>')[0].textContent==='x';c.supportsDataObject=(function(version){version[0]=parseInt(version[0],10);return(version[0]>1)||(version[0]===1&&parseInt(version[1],10)>=4);})($.fn.jquery.split("."));c.string={'max':1,'min':-1,'max+':1,'max-':-1,'zero':0,'none':0,'null':0,'top':true,'bottom':false};if(!/tablesorter\-/.test($this.attr('class'))){k=(c.theme!==''?' tablesorter-'+c.theme:'');}
c.$table=$this.addClass(ts.css.table+' '+c.tableClass+k);c.$tbodies=$this.children('tbody:not(.'+c.cssInfoBlock+')');c.widgetInit={};buildHeaders(table);fixColumnWidth(table);buildParserCache(table);if(!c.delayInit){buildCache(table);}
bindEvents(table);if(c.supportsDataObject&&typeof $this.data().sortlist!=='undefined'){c.sortList=$this.data().sortlist;}else if(m&&($this.metadata()&&$this.metadata().sortlist)){c.sortList=$this.metadata().sortlist;}
ts.applyWidget(table,true);if(c.sortList.length>0){$this.trigger("sorton",[c.sortList,{},!c.initWidgets]);}else if(c.initWidgets){ts.applyWidget(table);}
if(c.showProcessing){$this.unbind('sortBegin.tablesorter sortEnd.tablesorter').bind('sortBegin.tablesorter sortEnd.tablesorter',function(e){ts.isProcessing(table,e.type==='sortBegin');});}
table.hasInitialized=true;table.isProcessing=false;if(c.debug){ts.benchmark("Overall initialization time",$.data(table,'startoveralltimer'));}
$this.trigger('tablesorter-initialized',table);if(typeof c.initialized==='function'){c.initialized(table);}};ts.isProcessing=function(table,toggle,$ths){table=$(table);var c=table[0].config,$h=$ths||table.find('.'+ts.css.header);if(toggle){if(c.sortList.length>0){$h=$h.filter(function(){return this.sortDisabled?false:ts.isValueInArray(parseFloat($(this).attr('data-column')),c.sortList);});}
$h.addClass(ts.css.processing+' '+c.cssProcessing);}else{$h.removeClass(ts.css.processing+' '+c.cssProcessing);}};ts.processTbody=function(table,$tb,getIt){var holdr;if(getIt){table.isProcessing=true;$tb.before('<span class="tablesorter-savemyplace"/>');holdr=($.fn.detach)?$tb.detach():$tb.remove();return holdr;}
holdr=$(table).find('span.tablesorter-savemyplace');$tb.insertAfter(holdr);holdr.remove();table.isProcessing=false;};ts.clearTableBody=function(table){$(table)[0].config.$tbodies.empty();};ts.restoreHeaders=function(table){var c=table.config;c.$table.find(c.selectorHeaders).each(function(i){if($(this).find('.tablesorter-header-inner').length){$(this).html(c.headerContent[i]);}});};ts.destroy=function(table,removeClasses,callback){table=$(table)[0];if(!table.hasInitialized){return;}
ts.refreshWidgets(table,true,true);var $t=$(table),c=table.config,$h=$t.find('thead:first'),$r=$h.find('tr.'+ts.css.headerRow).removeClass(ts.css.headerRow+' '+c.cssHeaderRow),$f=$t.find('tfoot:first > tr').children('th, td');$h.find('tr').not($r).remove();$t.removeData('tablesorter').unbind('sortReset update updateAll updateRows updateCell addRows sorton appendCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd '.split(' ').join('.tablesorter '));c.$headers.add($f).removeClass([ts.css.header,c.cssHeader,c.cssAsc,c.cssDesc,ts.css.sortAsc,ts.css.sortDesc].join(' ')).removeAttr('data-column');$r.find(c.selectorSort).unbind('mousedown.tablesorter mouseup.tablesorter keypress.tablesorter');ts.restoreHeaders(table);if(removeClasses!==false){$t.removeClass(ts.css.table+' '+c.tableClass+' tablesorter-'+c.theme);}
table.hasInitialized=false;if(typeof callback==='function'){callback(table);}};ts.regex={chunk:/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,hex:/^0x[0-9a-f]+$/i};ts.sortNatural=function(a,b){if(a===b){return 0;}
var xN,xD,yN,yD,xF,yF,i,mx,r=ts.regex;if(r.hex.test(b)){xD=parseInt(a.match(r.hex),16);yD=parseInt(b.match(r.hex),16);if(xD<yD){return-1;}
if(xD>yD){return 1;}}
xN=a.replace(r.chunk,'\\0$1\\0').replace(/\\0$/,'').replace(/^\\0/,'').split('\\0');yN=b.replace(r.chunk,'\\0$1\\0').replace(/\\0$/,'').replace(/^\\0/,'').split('\\0');mx=Math.max(xN.length,yN.length);for(i=0;i<mx;i++){xF=isNaN(xN[i])?xN[i]||0:parseFloat(xN[i])||0;yF=isNaN(yN[i])?yN[i]||0:parseFloat(yN[i])||0;if(isNaN(xF)!==isNaN(yF)){return(isNaN(xF))?1:-1;}
if(typeof xF!==typeof yF){xF+='';yF+='';}
if(xF<yF){return-1;}
if(xF>yF){return 1;}}
return 0;};ts.sortNaturalAsc=function(a,b,col,table,c){if(a===b){return 0;}
var e=c.string[(c.empties[col]||c.emptyTo)];if(a===''&&e!==0){return typeof e==='boolean'?(e?-1:1):-e||-1;}
if(b===''&&e!==0){return typeof e==='boolean'?(e?1:-1):e||1;}
return ts.sortNatural(a,b);};ts.sortNaturalDesc=function(a,b,col,table,c){if(a===b){return 0;}
var e=c.string[(c.empties[col]||c.emptyTo)];if(a===''&&e!==0){return typeof e==='boolean'?(e?-1:1):e||1;}
if(b===''&&e!==0){return typeof e==='boolean'?(e?1:-1):-e||-1;}
return ts.sortNatural(b,a);};ts.sortText=function(a,b){return a>b?1:(a<b?-1:0);};ts.getTextValue=function(a,num,mx){if(mx){var i,l=a?a.length:0,n=mx+num;for(i=0;i<l;i++){n+=a.charCodeAt(i);}
return num*n;}
return 0;};ts.sortNumericAsc=function(a,b,num,mx,col,table){if(a===b){return 0;}
var c=table.config,e=c.string[(c.empties[col]||c.emptyTo)];if(a===''&&e!==0){return typeof e==='boolean'?(e?-1:1):-e||-1;}
if(b===''&&e!==0){return typeof e==='boolean'?(e?1:-1):e||1;}
if(isNaN(a)){a=ts.getTextValue(a,num,mx);}
if(isNaN(b)){b=ts.getTextValue(b,num,mx);}
return a-b;};ts.sortNumericDesc=function(a,b,num,mx,col,table){if(a===b){return 0;}
var c=table.config,e=c.string[(c.empties[col]||c.emptyTo)];if(a===''&&e!==0){return typeof e==='boolean'?(e?-1:1):e||1;}
if(b===''&&e!==0){return typeof e==='boolean'?(e?1:-1):-e||-1;}
if(isNaN(a)){a=ts.getTextValue(a,num,mx);}
if(isNaN(b)){b=ts.getTextValue(b,num,mx);}
return b-a;};ts.sortNumeric=function(a,b){return a-b;};ts.characterEquivalents={"a":"\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5","A":"\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5","c":"\u00e7\u0107\u010d","C":"\u00c7\u0106\u010c","e":"\u00e9\u00e8\u00ea\u00eb\u011b\u0119","E":"\u00c9\u00c8\u00ca\u00cb\u011a\u0118","i":"\u00ed\u00ec\u0130\u00ee\u00ef\u0131","I":"\u00cd\u00cc\u0130\u00ce\u00cf","o":"\u00f3\u00f2\u00f4\u00f5\u00f6","O":"\u00d3\u00d2\u00d4\u00d5\u00d6","ss":"\u00df","SS":"\u1e9e","u":"\u00fa\u00f9\u00fb\u00fc\u016f","U":"\u00da\u00d9\u00db\u00dc\u016e"};ts.replaceAccents=function(s){var a,acc='[',eq=ts.characterEquivalents;if(!ts.characterRegex){ts.characterRegexArray={};for(a in eq){if(typeof a==='string'){acc+=eq[a];ts.characterRegexArray[a]=new RegExp('['+eq[a]+']','g');}}
ts.characterRegex=new RegExp(acc+']');}
if(ts.characterRegex.test(s)){for(a in eq){if(typeof a==='string'){s=s.replace(ts.characterRegexArray[a],a);}}}
return s;};ts.isValueInArray=function(v,a){var i,l=a.length;for(i=0;i<l;i++){if(a[i][0]===v){return true;}}
return false;};ts.addParser=function(parser){var i,l=ts.parsers.length,a=true;for(i=0;i<l;i++){if(ts.parsers[i].id.toLowerCase()===parser.id.toLowerCase()){a=false;}}
if(a){ts.parsers.push(parser);}};ts.getParserById=function(name){var i,l=ts.parsers.length;for(i=0;i<l;i++){if(ts.parsers[i].id.toLowerCase()===(name.toString()).toLowerCase()){return ts.parsers[i];}}
return false;};ts.addWidget=function(widget){ts.widgets.push(widget);};ts.getWidgetById=function(name){var i,w,l=ts.widgets.length;for(i=0;i<l;i++){w=ts.widgets[i];if(w&&w.hasOwnProperty('id')&&w.id.toLowerCase()===name.toLowerCase()){return w;}}};ts.applyWidget=function(table,init){table=$(table)[0];var c=table.config,wo=c.widgetOptions,widgets=[],time,w,wd;if(c.debug){time=new Date();}
if(c.widgets.length){c.widgets=$.grep(c.widgets,function(v,k){return $.inArray(v,c.widgets)===k;});$.each(c.widgets||[],function(i,n){wd=ts.getWidgetById(n);if(wd&&wd.id){if(!wd.priority){wd.priority=10;}
widgets[i]=wd;}});widgets.sort(function(a,b){return a.priority<b.priority?-1:a.priority===b.priority?0:1;});$.each(widgets,function(i,w){if(w){if(init||!(c.widgetInit[w.id])){if(w.hasOwnProperty('options')){wo=table.config.widgetOptions=$.extend(true,{},w.options,wo);}
if(w.hasOwnProperty('init')){w.init(table,w,c,wo);}
c.widgetInit[w.id]=true;}
if(!init&&w.hasOwnProperty('format')){w.format(table,c,wo,false);}}});}
if(c.debug){w=c.widgets.length;benchmark("Completed "+(init===true?"initializing ":"applying ")+w+" widget"+(w!==1?"s":""),time);}};ts.refreshWidgets=function(table,doAll,dontapply){table=$(table)[0];var i,c=table.config,cw=c.widgets,w=ts.widgets,l=w.length;for(i=0;i<l;i++){if(w[i]&&w[i].id&&(doAll||$.inArray(w[i].id,cw)<0)){if(c.debug){log('Refeshing widgets: Removing '+w[i].id);}
if(w[i].hasOwnProperty('remove')&&c.widgetInit[w[i].id]){w[i].remove(table,c,c.widgetOptions);c.widgetInit[w[i].id]=false;}}}
if(dontapply!==true){ts.applyWidget(table,doAll);}};ts.getData=function(h,ch,key){var val='',$h=$(h),m,cl;if(!$h.length){return'';}
m=$.metadata?$h.metadata():false;cl=' '+($h.attr('class')||'');if(typeof $h.data(key)!=='undefined'||typeof $h.data(key.toLowerCase())!=='undefined'){val+=$h.data(key)||$h.data(key.toLowerCase());}else if(m&&typeof m[key]!=='undefined'){val+=m[key];}else if(ch&&typeof ch[key]!=='undefined'){val+=ch[key];}else if(cl!==' '&&cl.match(' '+key+'-')){val=cl.match(new RegExp('\\s'+key+'-([\\w-]+)'))[1]||'';}
return $.trim(val);};ts.formatFloat=function(s,table){if(typeof s!=='string'||s===''){return s;}
var i,t=table&&table.config?table.config.usNumberFormat!==false:typeof table!=="undefined"?table:true;if(t){s=s.replace(/,/g,'');}else{s=s.replace(/[\s|\.]/g,'').replace(/,/g,'.');}
if(/^\s*\([.\d]+\)/.test(s)){s=s.replace(/^\s*\(([.\d]+)\)/,'-$1');}
i=parseFloat(s);return isNaN(i)?$.trim(s):i;};ts.isDigit=function(s){return isNaN(s)?(/^[\-+(]?\d+[)]?$/).test(s.toString().replace(/[,.'"\s]/g,'')):true;};}()});var ts=$.tablesorter;$.fn.extend({tablesorter:ts.construct});ts.addParser({id:"text",is:function(){return true;},format:function(s,table){var c=table.config;if(s){s=$.trim(c.ignoreCase?s.toLocaleLowerCase():s);s=c.sortLocaleCompare?ts.replaceAccents(s):s;}
return s;},type:"text"});ts.addParser({id:"digit",is:function(s){return ts.isDigit(s);},format:function(s,table){var n=ts.formatFloat((s||'').replace(/[^\w,. \-()]/g,""),table);return s&&typeof n==='number'?n:s?$.trim(s&&table.config.ignoreCase?s.toLocaleLowerCase():s):s;},type:"numeric"});ts.addParser({id:"currency",is:function(s){return(/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/).test((s||'').replace(/[,. ]/g,''));},format:function(s,table){var n=ts.formatFloat((s||'').replace(/[^\w,. \-()]/g,""),table);return s&&typeof n==='number'?n:s?$.trim(s&&table.config.ignoreCase?s.toLocaleLowerCase():s):s;},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return(/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/).test(s);},format:function(s,table){var i,a=s?s.split("."):'',r="",l=a.length;for(i=0;i<l;i++){r+=("00"+a[i]).slice(-3);}
return s?ts.formatFloat(r,table):s;},type:"numeric"});ts.addParser({id:"url",is:function(s){return(/^(https?|ftp|file):\/\//).test(s);},format:function(s){return s?$.trim(s.replace(/(https?|ftp|file):\/\//,'')):s;},type:"text"});ts.addParser({id:"isoDate",is:function(s){return(/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/).test(s);},format:function(s,table){return s?ts.formatFloat((s!=="")?(new Date(s.replace(/-/g,"/")).getTime()||""):"",table):s;},type:"numeric"});ts.addParser({id:"percent",is:function(s){return(/(\d\s*?%|%\s*?\d)/).test(s)&&s.length<15;},format:function(s,table){return s?ts.formatFloat(s.replace(/%/g,""),table):s;},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return(/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i).test(s)||(/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i).test(s);},format:function(s,table){return s?ts.formatFloat((new Date(s.replace(/(\S)([AP]M)$/i,"$1 $2")).getTime()||''),table):s;},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return(/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/).test((s||'').replace(/\s+/g," ").replace(/[\-.,]/g,"/"));},format:function(s,table,cell,cellIndex){if(s){var c=table.config,ci=c.headerList[cellIndex],format=ci.dateFormat||ts.getData(ci,c.headers[cellIndex],'dateFormat')||c.dateFormat;s=s.replace(/\s+/g," ").replace(/[\-.,]/g,"/");if(format==="mmddyyyy"){s=s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/,"$3/$1/$2");}else if(format==="ddmmyyyy"){s=s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/,"$3/$2/$1");}else if(format==="yyyymmdd"){s=s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/,"$1/$2/$3");}}
return s?ts.formatFloat((new Date(s).getTime()||''),table):s;},type:"numeric"});ts.addParser({id:"time",is:function(s){return(/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i).test(s);},format:function(s,table){return s?ts.formatFloat((new Date("2000/01/01 "+s.replace(/(\S)([AP]M)$/i,"$1 $2")).getTime()||""),table):s;},type:"numeric"});ts.addParser({id:"metadata",is:function(){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",priority:90,format:function(table,c,wo){var $tb,$tv,$tr,row,even,time,k,l,child=new RegExp(c.cssChildRow,'i'),b=c.$tbodies;if(c.debug){time=new Date();}
for(k=0;k<b.length;k++){$tb=b.eq(k);l=$tb.children('tr').length;if(l>1){row=0;$tv=$tb.children('tr:visible').not(c.selectorRemove);$tv.each(function(){$tr=$(this);if(!child.test(this.className)){row++;}
even=(row%2===0);$tr.removeClass(wo.zebra[even?1:0]).addClass(wo.zebra[even?0:1]);});}}
if(c.debug){ts.benchmark("Applying Zebra widget",time);}},remove:function(table,c,wo){var k,$tb,b=c.$tbodies,rmv=(wo.zebra||["even","odd"]).join(' ');for(k=0;k<b.length;k++){$tb=$.tablesorter.processTbody(table,b.eq(k),true);$tb.children().removeClass(rmv);$.tablesorter.processTbody(table,$tb,false);}}});})(jQuery);(function(a,b,c){function g(a,c){var d=b.createElement(a||"div"),e;for(e in c)d[e]=c[e];return d}function h(a){for(var b=1,c=arguments.length;b<c;b++)a.appendChild(arguments[b]);return a}function j(a,b,c,d){var g=["opacity",b,~~(a*100),c,d].join("-"),h=.01+c/d*100,j=Math.max(1-(1-a)/b*(100-h),a),k=f.substring(0,f.indexOf("Animation")).toLowerCase(),l=k&&"-"+k+"-"||"";return e[g]||(i.insertRule("@"+l+"keyframes "+g+"{"+"0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}"+"100%{opacity:"+j+"}"+"}",0),e[g]=1),g}function k(a,b){var e=a.style,f,g;if(e[b]!==c)return b;b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g<d.length;g++){f=d[g]+b;if(e[f]!==c)return f}}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function m(a){for(var b=1;b<arguments.length;b++){var d=arguments[b];for(var e in d)a[e]===c&&(a[e]=d[e])}return a}function n(a){var b={x:a.offsetLeft,y:a.offsetTop};while(a=a.offsetParent)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}var d=["webkit","Moz","ms","O"],e={},f,i=function(){var a=g("style");return h(b.getElementsByTagName("head")[0],a),a.sheet||a.styleSheet}(),o={lines:12,length:7,width:5,radius:10,rotate:0,color:"#000",speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto"},p=function q(a){if(!this.spin)return new q(a);this.opts=m(a||{},q.defaults,o)};p.defaults={},m(p.prototype,{spin:function(a){this.stop();var b=this,c=b.opts,d=b.el=l(g(0,{className:c.className}),{position:"relative",zIndex:c.zIndex}),e=c.radius+c.length+c.width,h,i;a&&(a.insertBefore(d,a.firstChild||null),i=n(a),h=n(d),l(d,{left:(c.left=="auto"?i.x-h.x+(a.offsetWidth>>1):c.left+e)+"px",top:(c.top=="auto"?i.y-h.y+(a.offsetHeight>>1):c.top+e)+"px"})),d.setAttribute("aria-role","progressbar"),b.lines(d,b.opts);if(!f){var j=0,k=c.fps,m=k/c.speed,o=(1-c.opacity)/(m*c.trail/100),p=m/c.lines;!function q(){j++;for(var a=c.lines;a;a--){var e=Math.max(1-(j+a*p)%m*o,c.opacity);b.opacity(d,c.lines-a,e,c)}b.timeout=b.el&&setTimeout(q,~~(1e3/k))}()}return b},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=c),this},lines:function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c+b.rotate)+"deg) translate("+b.radius+"px"+",0)",borderRadius:(b.width>>1)+"px"})}var c=0,d;for(;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:b.hwaccel?"translate3d(0,0,0)":"",opacity:b.opacity,animation:f&&j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}}),!function(){function a(a,b){return g("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',b)}var b=l(g("group"),{behavior:"url(#default#VML)"});!k(b,"transform")&&b.adj?(i.addRule(".spin-vml","behavior:url(#default#VML)"),p.prototype.lines=function(b,c){function f(){return l(a("group",{coordsize:e+" "+e,coordorigin:-d+" "+-d}),{width:e,height:e})}function k(b,e,g){h(i,h(l(f(),{rotation:360/c.lines*b+"deg",left:~~e}),h(l(a("roundrect",{arcsize:1}),{width:d,height:c.width,left:c.radius,top:-c.width>>1,filter:g}),a("fill",{color:c.color,opacity:c.opacity}),a("stroke",{opacity:0}))))}var d=c.length+c.width,e=2*d,g=-(c.width+c.length)*2+"px",i=l(f(),{position:"absolute",top:g,left:g}),j;if(c.shadow)for(j=1;j<=c.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=c.lines;j++)k(j);return h(b,i)},p.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}):f=k(b,"animation")}(),a.Spinner=p})(window,document);$.fn.spin=function(opts){this.each(function(){var $this=$(this),data=$this.data();if(data.spinner){data.spinner.stop();delete data.spinner;}
if(opts!==false){data.spinner=new Spinner($.extend({color:$this.css('color')},opts)).spin(this);}});return this;};(function($,undefined){var uuid=0,runiqueId=/^ui-id-\d+$/;$.ui=$.ui||{};if($.ui.version){return;}
$.extend($.ui,{version:"1.9.2",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}});$.fn.extend({_focus:$.fn.focus,focus:function(delay,fn){return typeof delay==="number"?this.each(function(){var elem=this;setTimeout(function(){$(elem).focus();if(fn){fn.call(elem);}},delay);}):this._focus.apply(this,arguments);},scrollParent:function(){var scrollParent;if(($.ui.ie&&(/(static|relative)/).test(this.css('position')))||(/absolute/).test(this.css('position'))){scrollParent=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test($.css(this,'position'))&&(/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));}).eq(0);}else{scrollParent=this.parents().filter(function(){return(/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));}).eq(0);}
return(/fixed/).test(this.css('position'))||!scrollParent.length?$(document):scrollParent;},zIndex:function(zIndex){if(zIndex!==undefined){return this.css("zIndex",zIndex);}
if(this.length){var elem=$(this[0]),position,value;while(elem.length&&elem[0]!==document){position=elem.css("position");if(position==="absolute"||position==="relative"||position==="fixed"){value=parseInt(elem.css("zIndex"),10);if(!isNaN(value)&&value!==0){return value;}}
elem=elem.parent();}}
return 0;},uniqueId:function(){return this.each(function(){if(!this.id){this.id="ui-id-"+(++uuid);}});},removeUniqueId:function(){return this.each(function(){if(runiqueId.test(this.id)){$(this).removeAttr("id");}});}});function focusable(element,isTabIndexNotNaN){var map,mapName,img,nodeName=element.nodeName.toLowerCase();if("area"===nodeName){map=element.parentNode;mapName=map.name;if(!element.href||!mapName||map.nodeName.toLowerCase()!=="map"){return false;}
img=$("img[usemap=#"+mapName+"]")[0];return!!img&&visible(img);}
return(/input|select|textarea|button|object/.test(nodeName)?!element.disabled:"a"===nodeName?element.href||isTabIndexNotNaN:isTabIndexNotNaN)&&visible(element);}
function visible(element){return $.expr.filters.visible(element)&&!$(element).parents().andSelf().filter(function(){return $.css(this,"visibility")==="hidden";}).length;}
$.extend($.expr[":"],{data:$.expr.createPseudo?$.expr.createPseudo(function(dataName){return function(elem){return!!$.data(elem,dataName);};}):function(elem,i,match){return!!$.data(elem,match[3]);},focusable:function(element){return focusable(element,!isNaN($.attr(element,"tabindex")));},tabbable:function(element){var tabIndex=$.attr(element,"tabindex"),isTabIndexNaN=isNaN(tabIndex);return(isTabIndexNaN||tabIndex>=0)&&focusable(element,!isTabIndexNaN);}});$(function(){var body=document.body,div=body.appendChild(div=document.createElement("div"));div.offsetHeight;$.extend(div.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});$.support.minHeight=div.offsetHeight===100;$.support.selectstart="onselectstart"in div;body.removeChild(div).style.display="none";});if(!$("<a>").outerWidth(1).jquery){$.each(["Width","Height"],function(i,name){var side=name==="Width"?["Left","Right"]:["Top","Bottom"],type=name.toLowerCase(),orig={innerWidth:$.fn.innerWidth,innerHeight:$.fn.innerHeight,outerWidth:$.fn.outerWidth,outerHeight:$.fn.outerHeight};function reduce(elem,size,border,margin){$.each(side,function(){size-=parseFloat($.css(elem,"padding"+this))||0;if(border){size-=parseFloat($.css(elem,"border"+this+"Width"))||0;}
if(margin){size-=parseFloat($.css(elem,"margin"+this))||0;}});return size;}
$.fn["inner"+name]=function(size){if(size===undefined){return orig["inner"+name].call(this);}
return this.each(function(){$(this).css(type,reduce(this,size)+"px");});};$.fn["outer"+name]=function(size,margin){if(typeof size!=="number"){return orig["outer"+name].call(this,size);}
return this.each(function(){$(this).css(type,reduce(this,size,true,margin)+"px");});};});}
if($("<a>").data("a-b","a").removeData("a-b").data("a-b")){$.fn.removeData=(function(removeData){return function(key){if(arguments.length){return removeData.call(this,$.camelCase(key));}else{return removeData.call(this);}};})($.fn.removeData);}
(function(){var uaMatch=/msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||[];$.ui.ie=uaMatch.length?true:false;$.ui.ie6=parseFloat(uaMatch[1],10)===6;})();$.fn.extend({disableSelection:function(){return this.bind(($.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(event){event.preventDefault();});},enableSelection:function(){return this.unbind(".ui-disableSelection");}});$.extend($.ui,{plugin:{add:function(module,option,set){var i,proto=$.ui[module].prototype;for(i in set){proto.plugins[i]=proto.plugins[i]||[];proto.plugins[i].push([option,set[i]]);}},call:function(instance,name,args){var i,set=instance.plugins[name];if(!set||!instance.element[0].parentNode||instance.element[0].parentNode.nodeType===11){return;}
for(i=0;i<set.length;i++){if(instance.options[set[i][0]]){set[i][1].apply(instance.element,args);}}}},contains:$.contains,hasScroll:function(el,a){if($(el).css("overflow")==="hidden"){return false;}
var scroll=(a&&a==="left")?"scrollLeft":"scrollTop",has=false;if(el[scroll]>0){return true;}
el[scroll]=1;has=(el[scroll]>0);el[scroll]=0;return has;},isOverAxis:function(x,reference,size){return(x>reference)&&(x<(reference+size));},isOver:function(y,x,top,left,height,width){return $.ui.isOverAxis(y,top,height)&&$.ui.isOverAxis(x,left,width);}});})(jQuery);(function($,undefined){var uuid=0,slice=Array.prototype.slice,_cleanData=$.cleanData;$.cleanData=function(elems){for(var i=0,elem;(elem=elems[i])!=null;i++){try{$(elem).triggerHandler("remove");}catch(e){}}
_cleanData(elems);};$.widget=function(name,base,prototype){var fullName,existingConstructor,constructor,basePrototype,namespace=name.split(".")[0];name=name.split(".")[1];fullName=namespace+"-"+name;if(!prototype){prototype=base;base=$.Widget;}
$.expr[":"][fullName.toLowerCase()]=function(elem){return!!$.data(elem,fullName);};$[namespace]=$[namespace]||{};existingConstructor=$[namespace][name];constructor=$[namespace][name]=function(options,element){if(!this._createWidget){return new constructor(options,element);}
if(arguments.length){this._createWidget(options,element);}};$.extend(constructor,existingConstructor,{version:prototype.version,_proto:$.extend({},prototype),_childConstructors:[]});basePrototype=new base();basePrototype.options=$.widget.extend({},basePrototype.options);$.each(prototype,function(prop,value){if($.isFunction(value)){prototype[prop]=(function(){var _super=function(){return base.prototype[prop].apply(this,arguments);},_superApply=function(args){return base.prototype[prop].apply(this,args);};return function(){var __super=this._super,__superApply=this._superApply,returnValue;this._super=_super;this._superApply=_superApply;returnValue=value.apply(this,arguments);this._super=__super;this._superApply=__superApply;return returnValue;};})();}});constructor.prototype=$.widget.extend(basePrototype,{widgetEventPrefix:existingConstructor?basePrototype.widgetEventPrefix:name},prototype,{constructor:constructor,namespace:namespace,widgetName:name,widgetBaseClass:fullName,widgetFullName:fullName});if(existingConstructor){$.each(existingConstructor._childConstructors,function(i,child){var childPrototype=child.prototype;$.widget(childPrototype.namespace+"."+childPrototype.widgetName,constructor,child._proto);});delete existingConstructor._childConstructors;}else{base._childConstructors.push(constructor);}
$.widget.bridge(name,constructor);};$.widget.extend=function(target){var input=slice.call(arguments,1),inputIndex=0,inputLength=input.length,key,value;for(;inputIndex<inputLength;inputIndex++){for(key in input[inputIndex]){value=input[inputIndex][key];if(input[inputIndex].hasOwnProperty(key)&&value!==undefined){if($.isPlainObject(value)){target[key]=$.isPlainObject(target[key])?$.widget.extend({},target[key],value):$.widget.extend({},value);}else{target[key]=value;}}}}
return target;};$.widget.bridge=function(name,object){var fullName=object.prototype.widgetFullName||name;$.fn[name]=function(options){var isMethodCall=typeof options==="string",args=slice.call(arguments,1),returnValue=this;options=!isMethodCall&&args.length?$.widget.extend.apply(null,[options].concat(args)):options;if(isMethodCall){this.each(function(){var methodValue,instance=$.data(this,fullName);if(!instance){return $.error("cannot call methods on "+name+" prior to initialization; "+"attempted to call method '"+options+"'");}
if(!$.isFunction(instance[options])||options.charAt(0)==="_"){return $.error("no such method '"+options+"' for "+name+" widget instance");}
methodValue=instance[options].apply(instance,args);if(methodValue!==instance&&methodValue!==undefined){returnValue=methodValue&&methodValue.jquery?returnValue.pushStack(methodValue.get()):methodValue;return false;}});}else{this.each(function(){var instance=$.data(this,fullName);if(instance){instance.option(options||{})._init();}else{$.data(this,fullName,new object(options,this));}});}
return returnValue;};};$.Widget=function(){};$.Widget._childConstructors=[];$.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:false,create:null},_createWidget:function(options,element){element=$(element||this.defaultElement||this)[0];this.element=$(element);this.uuid=uuid++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=$.widget.extend({},this.options,this._getCreateOptions(),options);this.bindings=$();this.hoverable=$();this.focusable=$();if(element!==this){$.data(element,this.widgetName,this);$.data(element,this.widgetFullName,this);this._on(true,this.element,{remove:function(event){if(event.target===element){this.destroy();}}});this.document=$(element.style?element.ownerDocument:element.document||element);this.window=$(this.document[0].defaultView||this.document[0].parentWindow);}
this._create();this._trigger("create",null,this._getCreateEventData());this._init();},_getCreateOptions:$.noop,_getCreateEventData:$.noop,_create:$.noop,_init:$.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData($.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus");},_destroy:$.noop,widget:function(){return this.element;},option:function(key,value){var options=key,parts,curOption,i;if(arguments.length===0){return $.widget.extend({},this.options);}
if(typeof key==="string"){options={};parts=key.split(".");key=parts.shift();if(parts.length){curOption=options[key]=$.widget.extend({},this.options[key]);for(i=0;i<parts.length-1;i++){curOption[parts[i]]=curOption[parts[i]]||{};curOption=curOption[parts[i]];}
key=parts.pop();if(value===undefined){return curOption[key]===undefined?null:curOption[key];}
curOption[key]=value;}else{if(value===undefined){return this.options[key]===undefined?null:this.options[key];}
options[key]=value;}}
this._setOptions(options);return this;},_setOptions:function(options){var key;for(key in options){this._setOption(key,options[key]);}
return this;},_setOption:function(key,value){this.options[key]=value;if(key==="disabled"){this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!value).attr("aria-disabled",value);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus");}
return this;},enable:function(){return this._setOption("disabled",false);},disable:function(){return this._setOption("disabled",true);},_on:function(suppressDisabledCheck,element,handlers){var delegateElement,instance=this;if(typeof suppressDisabledCheck!=="boolean"){handlers=element;element=suppressDisabledCheck;suppressDisabledCheck=false;}
if(!handlers){handlers=element;element=this.element;delegateElement=this.widget();}else{element=delegateElement=$(element);this.bindings=this.bindings.add(element);}
$.each(handlers,function(event,handler){function handlerProxy(){if(!suppressDisabledCheck&&(instance.options.disabled===true||$(this).hasClass("ui-state-disabled"))){return;}
return(typeof handler==="string"?instance[handler]:handler).apply(instance,arguments);}
if(typeof handler!=="string"){handlerProxy.guid=handler.guid=handler.guid||handlerProxy.guid||$.guid++;}
var match=event.match(/^(\w+)\s*(.*)$/),eventName=match[1]+instance.eventNamespace,selector=match[2];if(selector){delegateElement.delegate(selector,eventName,handlerProxy);}else{element.bind(eventName,handlerProxy);}});},_off:function(element,eventName){eventName=(eventName||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;element.unbind(eventName).undelegate(eventName);},_delay:function(handler,delay){function handlerProxy(){return(typeof handler==="string"?instance[handler]:handler).apply(instance,arguments);}
var instance=this;return setTimeout(handlerProxy,delay||0);},_hoverable:function(element){this.hoverable=this.hoverable.add(element);this._on(element,{mouseenter:function(event){$(event.currentTarget).addClass("ui-state-hover");},mouseleave:function(event){$(event.currentTarget).removeClass("ui-state-hover");}});},_focusable:function(element){this.focusable=this.focusable.add(element);this._on(element,{focusin:function(event){$(event.currentTarget).addClass("ui-state-focus");},focusout:function(event){$(event.currentTarget).removeClass("ui-state-focus");}});},_trigger:function(type,event,data){var prop,orig,callback=this.options[type];data=data||{};event=$.Event(event);event.type=(type===this.widgetEventPrefix?type:this.widgetEventPrefix+type).toLowerCase();event.target=this.element[0];orig=event.originalEvent;if(orig){for(prop in orig){if(!(prop in event)){event[prop]=orig[prop];}}}
this.element.trigger(event,data);return!($.isFunction(callback)&&callback.apply(this.element[0],[event].concat(data))===false||event.isDefaultPrevented());}};$.each({show:"fadeIn",hide:"fadeOut"},function(method,defaultEffect){$.Widget.prototype["_"+method]=function(element,options,callback){if(typeof options==="string"){options={effect:options};}
var hasOptions,effectName=!options?method:options===true||typeof options==="number"?defaultEffect:options.effect||defaultEffect;options=options||{};if(typeof options==="number"){options={duration:options};}
hasOptions=!$.isEmptyObject(options);options.complete=callback;if(options.delay){element.delay(options.delay);}
if(hasOptions&&$.effects&&($.effects.effect[effectName]||$.uiBackCompat!==false&&$.effects[effectName])){element[method](options);}else if(effectName!==method&&element[effectName]){element[effectName](options.duration,options.easing,callback);}else{element.queue(function(next){$(this)[method]();if(callback){callback.call(element[0]);}
next();});}};});if($.uiBackCompat!==false){$.Widget.prototype._getCreateOptions=function(){return $.metadata&&$.metadata.get(this.element[0])[this.widgetName];};}})(jQuery);(function($,undefined){var mouseHandled=false;$(document).mouseup(function(e){mouseHandled=false;});$.widget("ui.mouse",{version:"1.9.2",options:{cancel:'input,textarea,button,select,option',distance:1,delay:0},_mouseInit:function(){var that=this;this.element.bind('mousedown.'+this.widgetName,function(event){return that._mouseDown(event);}).bind('click.'+this.widgetName,function(event){if(true===$.data(event.target,that.widgetName+'.preventClickEvent')){$.removeData(event.target,that.widgetName+'.preventClickEvent');event.stopImmediatePropagation();return false;}});this.started=false;},_mouseDestroy:function(){this.element.unbind('.'+this.widgetName);if(this._mouseMoveDelegate){$(document).unbind('mousemove.'+this.widgetName,this._mouseMoveDelegate).unbind('mouseup.'+this.widgetName,this._mouseUpDelegate);}},_mouseDown:function(event){if(mouseHandled){return;}
(this._mouseStarted&&this._mouseUp(event));this._mouseDownEvent=event;var that=this,btnIsLeft=(event.which===1),elIsCancel=(typeof this.options.cancel==="string"&&event.target.nodeName?$(event.target).closest(this.options.cancel).length:false);if(!btnIsLeft||elIsCancel||!this._mouseCapture(event)){return true;}
this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){that.mouseDelayMet=true;},this.options.delay);}
if(this._mouseDistanceMet(event)&&this._mouseDelayMet(event)){this._mouseStarted=(this._mouseStart(event)!==false);if(!this._mouseStarted){event.preventDefault();return true;}}
if(true===$.data(event.target,this.widgetName+'.preventClickEvent')){$.removeData(event.target,this.widgetName+'.preventClickEvent');}
this._mouseMoveDelegate=function(event){return that._mouseMove(event);};this._mouseUpDelegate=function(event){return that._mouseUp(event);};$(document).bind('mousemove.'+this.widgetName,this._mouseMoveDelegate).bind('mouseup.'+this.widgetName,this._mouseUpDelegate);event.preventDefault();mouseHandled=true;return true;},_mouseMove:function(event){if($.ui.ie&&!(document.documentMode>=9)&&!event.button){return this._mouseUp(event);}
if(this._mouseStarted){this._mouseDrag(event);return event.preventDefault();}
if(this._mouseDistanceMet(event)&&this._mouseDelayMet(event)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,event)!==false);(this._mouseStarted?this._mouseDrag(event):this._mouseUp(event));}
return!this._mouseStarted;},_mouseUp:function(event){$(document).unbind('mousemove.'+this.widgetName,this._mouseMoveDelegate).unbind('mouseup.'+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(event.target===this._mouseDownEvent.target){$.data(event.target,this.widgetName+'.preventClickEvent',true);}
this._mouseStop(event);}
return false;},_mouseDistanceMet:function(event){return(Math.max(Math.abs(this._mouseDownEvent.pageX-event.pageX),Math.abs(this._mouseDownEvent.pageY-event.pageY))>=this.options.distance);},_mouseDelayMet:function(event){return this.mouseDelayMet;},_mouseStart:function(event){},_mouseDrag:function(event){},_mouseStop:function(event){},_mouseCapture:function(event){return true;}});})(jQuery);(function($,undefined){$.ui=$.ui||{};var cachedScrollbarWidth,max=Math.max,abs=Math.abs,round=Math.round,rhorizontal=/left|center|right/,rvertical=/top|center|bottom/,roffset=/[\+\-]\d+%?/,rposition=/^\w+/,rpercent=/%$/,_position=$.fn.position;function getOffsets(offsets,width,height){return[parseInt(offsets[0],10)*(rpercent.test(offsets[0])?width/100:1),parseInt(offsets[1],10)*(rpercent.test(offsets[1])?height/100:1)];}
function parseCss(element,property){return parseInt($.css(element,property),10)||0;}
$.position={scrollbarWidth:function(){if(cachedScrollbarWidth!==undefined){return cachedScrollbarWidth;}
var w1,w2,div=$("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),innerDiv=div.children()[0];$("body").append(div);w1=innerDiv.offsetWidth;div.css("overflow","scroll");w2=innerDiv.offsetWidth;if(w1===w2){w2=div[0].clientWidth;}
div.remove();return(cachedScrollbarWidth=w1-w2);},getScrollInfo:function(within){var overflowX=within.isWindow?"":within.element.css("overflow-x"),overflowY=within.isWindow?"":within.element.css("overflow-y"),hasOverflowX=overflowX==="scroll"||(overflowX==="auto"&&within.width<within.element[0].scrollWidth),hasOverflowY=overflowY==="scroll"||(overflowY==="auto"&&within.height<within.element[0].scrollHeight);return{width:hasOverflowX?$.position.scrollbarWidth():0,height:hasOverflowY?$.position.scrollbarWidth():0};},getWithinInfo:function(element){var withinElement=$(element||window),isWindow=$.isWindow(withinElement[0]);return{element:withinElement,isWindow:isWindow,offset:withinElement.offset()||{left:0,top:0},scrollLeft:withinElement.scrollLeft(),scrollTop:withinElement.scrollTop(),width:isWindow?withinElement.width():withinElement.outerWidth(),height:isWindow?withinElement.height():withinElement.outerHeight()};}};$.fn.position=function(options){if(!options||!options.of){return _position.apply(this,arguments);}
options=$.extend({},options);var atOffset,targetWidth,targetHeight,targetOffset,basePosition,target=$(options.of),within=$.position.getWithinInfo(options.within),scrollInfo=$.position.getScrollInfo(within),targetElem=target[0],collision=(options.collision||"flip").split(" "),offsets={};if(targetElem.nodeType===9){targetWidth=target.width();targetHeight=target.height();targetOffset={top:0,left:0};}else if($.isWindow(targetElem)){targetWidth=target.width();targetHeight=target.height();targetOffset={top:target.scrollTop(),left:target.scrollLeft()};}else if(targetElem.preventDefault){options.at="left top";targetWidth=targetHeight=0;targetOffset={top:targetElem.pageY,left:targetElem.pageX};}else{targetWidth=target.outerWidth();targetHeight=target.outerHeight();targetOffset=target.offset();}
basePosition=$.extend({},targetOffset);$.each(["my","at"],function(){var pos=(options[this]||"").split(" "),horizontalOffset,verticalOffset;if(pos.length===1){pos=rhorizontal.test(pos[0])?pos.concat(["center"]):rvertical.test(pos[0])?["center"].concat(pos):["center","center"];}
pos[0]=rhorizontal.test(pos[0])?pos[0]:"center";pos[1]=rvertical.test(pos[1])?pos[1]:"center";horizontalOffset=roffset.exec(pos[0]);verticalOffset=roffset.exec(pos[1]);offsets[this]=[horizontalOffset?horizontalOffset[0]:0,verticalOffset?verticalOffset[0]:0];options[this]=[rposition.exec(pos[0])[0],rposition.exec(pos[1])[0]];});if(collision.length===1){collision[1]=collision[0];}
if(options.at[0]==="right"){basePosition.left+=targetWidth;}else if(options.at[0]==="center"){basePosition.left+=targetWidth/2;}
if(options.at[1]==="bottom"){basePosition.top+=targetHeight;}else if(options.at[1]==="center"){basePosition.top+=targetHeight/2;}
atOffset=getOffsets(offsets.at,targetWidth,targetHeight);basePosition.left+=atOffset[0];basePosition.top+=atOffset[1];return this.each(function(){var collisionPosition,using,elem=$(this),elemWidth=elem.outerWidth(),elemHeight=elem.outerHeight(),marginLeft=parseCss(this,"marginLeft"),marginTop=parseCss(this,"marginTop"),collisionWidth=elemWidth+marginLeft+parseCss(this,"marginRight")+scrollInfo.width,collisionHeight=elemHeight+marginTop+parseCss(this,"marginBottom")+scrollInfo.height,position=$.extend({},basePosition),myOffset=getOffsets(offsets.my,elem.outerWidth(),elem.outerHeight());if(options.my[0]==="right"){position.left-=elemWidth;}else if(options.my[0]==="center"){position.left-=elemWidth/2;}
if(options.my[1]==="bottom"){position.top-=elemHeight;}else if(options.my[1]==="center"){position.top-=elemHeight/2;}
position.left+=myOffset[0];position.top+=myOffset[1];if(!$.support.offsetFractions){position.left=round(position.left);position.top=round(position.top);}
collisionPosition={marginLeft:marginLeft,marginTop:marginTop};$.each(["left","top"],function(i,dir){if($.ui.position[collision[i]]){$.ui.position[collision[i]][dir](position,{targetWidth:targetWidth,targetHeight:targetHeight,elemWidth:elemWidth,elemHeight:elemHeight,collisionPosition:collisionPosition,collisionWidth:collisionWidth,collisionHeight:collisionHeight,offset:[atOffset[0]+myOffset[0],atOffset[1]+myOffset[1]],my:options.my,at:options.at,within:within,elem:elem});}});if($.fn.bgiframe){elem.bgiframe();}
if(options.using){using=function(props){var left=targetOffset.left-position.left,right=left+targetWidth-elemWidth,top=targetOffset.top-position.top,bottom=top+targetHeight-elemHeight,feedback={target:{element:target,left:targetOffset.left,top:targetOffset.top,width:targetWidth,height:targetHeight},element:{element:elem,left:position.left,top:position.top,width:elemWidth,height:elemHeight},horizontal:right<0?"left":left>0?"right":"center",vertical:bottom<0?"top":top>0?"bottom":"middle"};if(targetWidth<elemWidth&&abs(left+right)<targetWidth){feedback.horizontal="center";}
if(targetHeight<elemHeight&&abs(top+bottom)<targetHeight){feedback.vertical="middle";}
if(max(abs(left),abs(right))>max(abs(top),abs(bottom))){feedback.important="horizontal";}else{feedback.important="vertical";}
options.using.call(this,props,feedback);};}
elem.offset($.extend(position,{using:using}));});};$.ui.position={fit:{left:function(position,data){var within=data.within,withinOffset=within.isWindow?within.scrollLeft:within.offset.left,outerWidth=within.width,collisionPosLeft=position.left-data.collisionPosition.marginLeft,overLeft=withinOffset-collisionPosLeft,overRight=collisionPosLeft+data.collisionWidth-outerWidth-withinOffset,newOverRight;if(data.collisionWidth>outerWidth){if(overLeft>0&&overRight<=0){newOverRight=position.left+overLeft+data.collisionWidth-outerWidth-withinOffset;position.left+=overLeft-newOverRight;}else if(overRight>0&&overLeft<=0){position.left=withinOffset;}else{if(overLeft>overRight){position.left=withinOffset+outerWidth-data.collisionWidth;}else{position.left=withinOffset;}}}else if(overLeft>0){position.left+=overLeft;}else if(overRight>0){position.left-=overRight;}else{position.left=max(position.left-collisionPosLeft,position.left);}},top:function(position,data){var within=data.within,withinOffset=within.isWindow?within.scrollTop:within.offset.top,outerHeight=data.within.height,collisionPosTop=position.top-data.collisionPosition.marginTop,overTop=withinOffset-collisionPosTop,overBottom=collisionPosTop+data.collisionHeight-outerHeight-withinOffset,newOverBottom;if(data.collisionHeight>outerHeight){if(overTop>0&&overBottom<=0){newOverBottom=position.top+overTop+data.collisionHeight-outerHeight-withinOffset;position.top+=overTop-newOverBottom;}else if(overBottom>0&&overTop<=0){position.top=withinOffset;}else{if(overTop>overBottom){position.top=withinOffset+outerHeight-data.collisionHeight;}else{position.top=withinOffset;}}}else if(overTop>0){position.top+=overTop;}else if(overBottom>0){position.top-=overBottom;}else{position.top=max(position.top-collisionPosTop,position.top);}}},flip:{left:function(position,data){var within=data.within,withinOffset=within.offset.left+within.scrollLeft,outerWidth=within.width,offsetLeft=within.isWindow?within.scrollLeft:within.offset.left,collisionPosLeft=position.left-data.collisionPosition.marginLeft,overLeft=collisionPosLeft-offsetLeft,overRight=collisionPosLeft+data.collisionWidth-outerWidth-offsetLeft,myOffset=data.my[0]==="left"?-data.elemWidth:data.my[0]==="right"?data.elemWidth:0,atOffset=data.at[0]==="left"?data.targetWidth:data.at[0]==="right"?-data.targetWidth:0,offset=-2*data.offset[0],newOverRight,newOverLeft;if(overLeft<0){newOverRight=position.left+myOffset+atOffset+offset+data.collisionWidth-outerWidth-withinOffset;if(newOverRight<0||newOverRight<abs(overLeft)){position.left+=myOffset+atOffset+offset;}}
else if(overRight>0){newOverLeft=position.left-data.collisionPosition.marginLeft+myOffset+atOffset+offset-offsetLeft;if(newOverLeft>0||abs(newOverLeft)<overRight){position.left+=myOffset+atOffset+offset;}}},top:function(position,data){var within=data.within,withinOffset=within.offset.top+within.scrollTop,outerHeight=within.height,offsetTop=within.isWindow?within.scrollTop:within.offset.top,collisionPosTop=position.top-data.collisionPosition.marginTop,overTop=collisionPosTop-offsetTop,overBottom=collisionPosTop+data.collisionHeight-outerHeight-offsetTop,top=data.my[1]==="top",myOffset=top?-data.elemHeight:data.my[1]==="bottom"?data.elemHeight:0,atOffset=data.at[1]==="top"?data.targetHeight:data.at[1]==="bottom"?-data.targetHeight:0,offset=-2*data.offset[1],newOverTop,newOverBottom;if(overTop<0){newOverBottom=position.top+myOffset+atOffset+offset+data.collisionHeight-outerHeight-withinOffset;if((position.top+myOffset+atOffset+offset)>overTop&&(newOverBottom<0||newOverBottom<abs(overTop))){position.top+=myOffset+atOffset+offset;}}
else if(overBottom>0){newOverTop=position.top-data.collisionPosition.marginTop+myOffset+atOffset+offset-offsetTop;if((position.top+myOffset+atOffset+offset)>overBottom&&(newOverTop>0||abs(newOverTop)<overBottom)){position.top+=myOffset+atOffset+offset;}}}},flipfit:{left:function(){$.ui.position.flip.left.apply(this,arguments);$.ui.position.fit.left.apply(this,arguments);},top:function(){$.ui.position.flip.top.apply(this,arguments);$.ui.position.fit.top.apply(this,arguments);}}};(function(){var testElement,testElementParent,testElementStyle,offsetLeft,i,body=document.getElementsByTagName("body")[0],div=document.createElement("div");testElement=document.createElement(body?"div":"body");testElementStyle={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};if(body){$.extend(testElementStyle,{position:"absolute",left:"-1000px",top:"-1000px"});}
for(i in testElementStyle){testElement.style[i]=testElementStyle[i];}
testElement.appendChild(div);testElementParent=body||document.documentElement;testElementParent.insertBefore(testElement,testElementParent.firstChild);div.style.cssText="position: absolute; left: 10.7432222px;";offsetLeft=$(div).offset().left;$.support.offsetFractions=offsetLeft>10&&offsetLeft<11;testElement.innerHTML="";testElementParent.removeChild(testElement);})();if($.uiBackCompat!==false){(function($){var _position=$.fn.position;$.fn.position=function(options){if(!options||!options.offset){return _position.call(this,options);}
var offset=options.offset.split(" "),at=options.at.split(" ");if(offset.length===1){offset[1]=offset[0];}
if(/^\d/.test(offset[0])){offset[0]="+"+offset[0];}
if(/^\d/.test(offset[1])){offset[1]="+"+offset[1];}
if(at.length===1){if(/left|center|right/.test(at[0])){at[1]="center";}else{at[1]=at[0];at[0]="center";}}
return _position.call(this,$.extend(options,{at:at[0]+offset[0]+" "+at[1]+offset[1],offset:undefined}));};}(jQuery));}}(jQuery));(function($,undefined){$.widget("ui.draggable",$.ui.mouse,{version:"1.9.2",widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper=='original'&&!(/^(?:r|a|f)/).test(this.element.css("position")))
this.element[0].style.position='relative';(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit();},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();},_mouseCapture:function(event){var o=this.options;if(this.helper||o.disabled||$(event.target).is('.ui-resizable-handle'))
return false;this.handle=this._getHandle(event);if(!this.handle)
return false;$(o.iframeFix===true?"iframe":o.iframeFix).each(function(){$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css($(this).offset()).appendTo("body");});return true;},_mouseStart:function(event){var o=this.options;this.helper=this._createHelper(event);this.helper.addClass("ui-draggable-dragging");this._cacheHelperProportions();if($.ui.ddmanager)
$.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};$.extend(this.offset,{click:{left:event.pageX-this.offset.left,top:event.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(event);this.originalPageX=event.pageX;this.originalPageY=event.pageY;(o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt));if(o.containment)
this._setContainment();if(this._trigger("start",event)===false){this._clear();return false;}
this._cacheHelperProportions();if($.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this,event);this._mouseDrag(event,true);if($.ui.ddmanager)$.ui.ddmanager.dragStart(this,event);return true;},_mouseDrag:function(event,noPropagation){this.position=this._generatePosition(event);this.positionAbs=this._convertPositionTo("absolute");if(!noPropagation){var ui=this._uiHash();if(this._trigger('drag',event,ui)===false){this._mouseUp({});return false;}
this.position=ui.position;}
if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+'px';if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+'px';if($.ui.ddmanager)$.ui.ddmanager.drag(this,event);return false;},_mouseStop:function(event){var dropped=false;if($.ui.ddmanager&&!this.options.dropBehaviour)
dropped=$.ui.ddmanager.drop(this,event);if(this.dropped){dropped=this.dropped;this.dropped=false;}
var element=this.element[0],elementInDom=false;while(element&&(element=element.parentNode)){if(element==document){elementInDom=true;}}
if(!elementInDom&&this.options.helper==="original")
return false;if((this.options.revert=="invalid"&&!dropped)||(this.options.revert=="valid"&&dropped)||this.options.revert===true||($.isFunction(this.options.revert)&&this.options.revert.call(this.element,dropped))){var that=this;$(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(that._trigger("stop",event)!==false){that._clear();}});}else{if(this._trigger("stop",event)!==false){this._clear();}}
return false;},_mouseUp:function(event){$("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this);});if($.ui.ddmanager)$.ui.ddmanager.dragStop(this,event);return $.ui.mouse.prototype._mouseUp.call(this,event);},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp({});}else{this._clear();}
return this;},_getHandle:function(event){var handle=!this.options.handle||!$(this.options.handle,this.element).length?true:false;$(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==event.target)handle=true;});return handle;},_createHelper:function(event){var o=this.options;var helper=$.isFunction(o.helper)?$(o.helper.apply(this.element[0],[event])):(o.helper=='clone'?this.element.clone().removeAttr('id'):this.element);if(!helper.parents('body').length)
helper.appendTo((o.appendTo=='parent'?this.element[0].parentNode:o.appendTo));if(helper[0]!=this.element[0]&&!(/(fixed|absolute)/).test(helper.css("position")))
helper.css("position","absolute");return helper;},_adjustOffsetFromHelper:function(obj){if(typeof obj=='string'){obj=obj.split(' ');}
if($.isArray(obj)){obj={left:+obj[0],top:+obj[1]||0};}
if('left'in obj){this.offset.click.left=obj.left+this.margins.left;}
if('right'in obj){this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left;}
if('top'in obj){this.offset.click.top=obj.top+this.margins.top;}
if('bottom'in obj){this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top;}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var po=this.offsetParent.offset();if(this.cssPosition=='absolute'&&this.scrollParent[0]!=document&&$.contains(this.scrollParent[0],this.offsetParent[0])){po.left+=this.scrollParent.scrollLeft();po.top+=this.scrollParent.scrollTop();}
if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=='html'&&$.ui.ie))
po={top:0,left:0};return{top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var p=this.element.position();return{top:p.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:p.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()};}else{return{top:0,left:0};}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0),right:(parseInt(this.element.css("marginRight"),10)||0),bottom:(parseInt(this.element.css("marginBottom"),10)||0)};},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function(){var o=this.options;if(o.containment=='parent')o.containment=this.helper[0].parentNode;if(o.containment=='document'||o.containment=='window')this.containment=[o.containment=='document'?0:$(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,o.containment=='document'?0:$(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(o.containment=='document'?0:$(window).scrollLeft())+$(o.containment=='document'?document:window).width()-this.helperProportions.width-this.margins.left,(o.containment=='document'?0:$(window).scrollTop())+($(o.containment=='document'?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!(/^(document|window|parent)$/).test(o.containment)&&o.containment.constructor!=Array){var c=$(o.containment);var ce=c[0];if(!ce)return;var co=c.offset();var over=($(ce).css("overflow")!='hidden');this.containment=[(parseInt($(ce).css("borderLeftWidth"),10)||0)+(parseInt($(ce).css("paddingLeft"),10)||0),(parseInt($(ce).css("borderTopWidth"),10)||0)+(parseInt($(ce).css("paddingTop"),10)||0),(over?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt($(ce).css("borderLeftWidth"),10)||0)-(parseInt($(ce).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(over?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt($(ce).css("borderTopWidth"),10)||0)-(parseInt($(ce).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=c;}else if(o.containment.constructor==Array){this.containment=o.containment;}},_convertPositionTo:function(d,pos){if(!pos)pos=this.position;var mod=d=="absolute"?1:-1;var o=this.options,scroll=this.cssPosition=='absolute'&&!(this.scrollParent[0]!=document&&$.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=(/(html|body)/i).test(scroll[0].tagName);return{top:(pos.top
+this.offset.relative.top*mod
+this.offset.parent.top*mod
-((this.cssPosition=='fixed'?-this.scrollParent.scrollTop():(scrollIsRootNode?0:scroll.scrollTop()))*mod)),left:(pos.left
+this.offset.relative.left*mod
+this.offset.parent.left*mod
-((this.cssPosition=='fixed'?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())*mod))};},_generatePosition:function(event){var o=this.options,scroll=this.cssPosition=='absolute'&&!(this.scrollParent[0]!=document&&$.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=(/(html|body)/i).test(scroll[0].tagName);var pageX=event.pageX;var pageY=event.pageY;if(this.originalPosition){var containment;if(this.containment){if(this.relative_container){var co=this.relative_container.offset();containment=[this.containment[0]+co.left,this.containment[1]+co.top,this.containment[2]+co.left,this.containment[3]+co.top];}
else{containment=this.containment;}
if(event.pageX-this.offset.click.left<containment[0])pageX=containment[0]+this.offset.click.left;if(event.pageY-this.offset.click.top<containment[1])pageY=containment[1]+this.offset.click.top;if(event.pageX-this.offset.click.left>containment[2])pageX=containment[2]+this.offset.click.left;if(event.pageY-this.offset.click.top>containment[3])pageY=containment[3]+this.offset.click.top;}
if(o.grid){var top=o.grid[1]?this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY;pageY=containment?(!(top-this.offset.click.top<containment[1]||top-this.offset.click.top>containment[3])?top:(!(top-this.offset.click.top<containment[1])?top-o.grid[1]:top+o.grid[1])):top;var left=o.grid[0]?this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX;pageX=containment?(!(left-this.offset.click.left<containment[0]||left-this.offset.click.left>containment[2])?left:(!(left-this.offset.click.left<containment[0])?left-o.grid[0]:left+o.grid[0])):left;}}
return{top:(pageY
-this.offset.click.top
-this.offset.relative.top
-this.offset.parent.top
+((this.cssPosition=='fixed'?-this.scrollParent.scrollTop():(scrollIsRootNode?0:scroll.scrollTop())))),left:(pageX
-this.offset.click.left
-this.offset.relative.left
-this.offset.parent.left
+((this.cssPosition=='fixed'?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())))};},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval)this.helper.remove();this.helper=null;this.cancelHelperRemoval=false;},_trigger:function(type,event,ui){ui=ui||this._uiHash();$.ui.plugin.call(this,type,[event,ui]);if(type=="drag")this.positionAbs=this._convertPositionTo("absolute");return $.Widget.prototype._trigger.call(this,type,event,ui);},plugins:{},_uiHash:function(event){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs};}});$.ui.plugin.add("draggable","connectToSortable",{start:function(event,ui){var inst=$(this).data("draggable"),o=inst.options,uiSortable=$.extend({},ui,{item:inst.element});inst.sortables=[];$(o.connectToSortable).each(function(){var sortable=$.data(this,'sortable');if(sortable&&!sortable.options.disabled){inst.sortables.push({instance:sortable,shouldRevert:sortable.options.revert});sortable.refreshPositions();sortable._trigger("activate",event,uiSortable);}});},stop:function(event,ui){var inst=$(this).data("draggable"),uiSortable=$.extend({},ui,{item:inst.element});$.each(inst.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;inst.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(event);this.instance.options.helper=this.instance.options._helper;if(inst.options.helper=='original')
this.instance.currentItem.css({top:'auto',left:'auto'});}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",event,uiSortable);}});},drag:function(event,ui){var inst=$(this).data("draggable"),that=this;var checkPos=function(o){var dyClick=this.offset.click.top,dxClick=this.offset.click.left;var helperTop=this.positionAbs.top,helperLeft=this.positionAbs.left;var itemHeight=o.height,itemWidth=o.width;var itemTop=o.top,itemLeft=o.left;return $.ui.isOver(helperTop+dyClick,helperLeft+dxClick,itemTop,itemLeft,itemHeight,itemWidth);};$.each(inst.sortables,function(i){var innermostIntersecting=false;var thisSortable=this;this.instance.positionAbs=inst.positionAbs;this.instance.helperProportions=inst.helperProportions;this.instance.offset.click=inst.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){innermostIntersecting=true;$.each(inst.sortables,function(){this.instance.positionAbs=inst.positionAbs;this.instance.helperProportions=inst.helperProportions;this.instance.offset.click=inst.offset.click;if(this!=thisSortable&&this.instance._intersectsWith(this.instance.containerCache)&&$.ui.contains(thisSortable.instance.element[0],this.instance.element[0]))
innermostIntersecting=false;return innermostIntersecting;});}
if(innermostIntersecting){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=$(that).clone().removeAttr('id').appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return ui.helper[0];};event.target=this.instance.currentItem[0];this.instance._mouseCapture(event,true);this.instance._mouseStart(event,true,true);this.instance.offset.click.top=inst.offset.click.top;this.instance.offset.click.left=inst.offset.click.left;this.instance.offset.parent.left-=inst.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=inst.offset.parent.top-this.instance.offset.parent.top;inst._trigger("toSortable",event);inst.dropped=this.instance.element;inst.currentItem=inst.element;this.instance.fromOutside=inst;}
if(this.instance.currentItem)this.instance._mouseDrag(event);}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger('out',event,this.instance._uiHash(this.instance));this.instance._mouseStop(event,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder)this.instance.placeholder.remove();inst._trigger("fromSortable",event);inst.dropped=false;}};});}});$.ui.plugin.add("draggable","cursor",{start:function(event,ui){var t=$('body'),o=$(this).data('draggable').options;if(t.css("cursor"))o._cursor=t.css("cursor");t.css("cursor",o.cursor);},stop:function(event,ui){var o=$(this).data('draggable').options;if(o._cursor)$('body').css("cursor",o._cursor);}});$.ui.plugin.add("draggable","opacity",{start:function(event,ui){var t=$(ui.helper),o=$(this).data('draggable').options;if(t.css("opacity"))o._opacity=t.css("opacity");t.css('opacity',o.opacity);},stop:function(event,ui){var o=$(this).data('draggable').options;if(o._opacity)$(ui.helper).css('opacity',o._opacity);}});$.ui.plugin.add("draggable","scroll",{start:function(event,ui){var i=$(this).data("draggable");if(i.scrollParent[0]!=document&&i.scrollParent[0].tagName!='HTML')i.overflowOffset=i.scrollParent.offset();},drag:function(event,ui){var i=$(this).data("draggable"),o=i.options,scrolled=false;if(i.scrollParent[0]!=document&&i.scrollParent[0].tagName!='HTML'){if(!o.axis||o.axis!='x'){if((i.overflowOffset.top+i.scrollParent[0].offsetHeight)-event.pageY<o.scrollSensitivity)
i.scrollParent[0].scrollTop=scrolled=i.scrollParent[0].scrollTop+o.scrollSpeed;else if(event.pageY-i.overflowOffset.top<o.scrollSensitivity)
i.scrollParent[0].scrollTop=scrolled=i.scrollParent[0].scrollTop-o.scrollSpeed;}
if(!o.axis||o.axis!='y'){if((i.overflowOffset.left+i.scrollParent[0].offsetWidth)-event.pageX<o.scrollSensitivity)
i.scrollParent[0].scrollLeft=scrolled=i.scrollParent[0].scrollLeft+o.scrollSpeed;else if(event.pageX-i.overflowOffset.left<o.scrollSensitivity)
i.scrollParent[0].scrollLeft=scrolled=i.scrollParent[0].scrollLeft-o.scrollSpeed;}}else{if(!o.axis||o.axis!='x'){if(event.pageY-$(document).scrollTop()<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()-o.scrollSpeed);else if($(window).height()-(event.pageY-$(document).scrollTop())<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()+o.scrollSpeed);}
if(!o.axis||o.axis!='y'){if(event.pageX-$(document).scrollLeft()<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()-o.scrollSpeed);else if($(window).width()-(event.pageX-$(document).scrollLeft())<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()+o.scrollSpeed);}}
if(scrolled!==false&&$.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(i,event);}});$.ui.plugin.add("draggable","snap",{start:function(event,ui){var i=$(this).data("draggable"),o=i.options;i.snapElements=[];$(o.snap.constructor!=String?(o.snap.items||':data(draggable)'):o.snap).each(function(){var $t=$(this);var $o=$t.offset();if(this!=i.element[0])i.snapElements.push({item:this,width:$t.outerWidth(),height:$t.outerHeight(),top:$o.top,left:$o.left});});},drag:function(event,ui){var inst=$(this).data("draggable"),o=inst.options;var d=o.snapTolerance;var x1=ui.offset.left,x2=x1+inst.helperProportions.width,y1=ui.offset.top,y2=y1+inst.helperProportions.height;for(var i=inst.snapElements.length-1;i>=0;i--){var l=inst.snapElements[i].left,r=l+inst.snapElements[i].width,t=inst.snapElements[i].top,b=t+inst.snapElements[i].height;if(!((l-d<x1&&x1<r+d&&t-d<y1&&y1<b+d)||(l-d<x1&&x1<r+d&&t-d<y2&&y2<b+d)||(l-d<x2&&x2<r+d&&t-d<y1&&y1<b+d)||(l-d<x2&&x2<r+d&&t-d<y2&&y2<b+d))){if(inst.snapElements[i].snapping)(inst.options.snap.release&&inst.options.snap.release.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item})));inst.snapElements[i].snapping=false;continue;}
if(o.snapMode!='inner'){var ts=Math.abs(t-y2)<=d;var bs=Math.abs(b-y1)<=d;var ls=Math.abs(l-x2)<=d;var rs=Math.abs(r-x1)<=d;if(ts)ui.position.top=inst._convertPositionTo("relative",{top:t-inst.helperProportions.height,left:0}).top-inst.margins.top;if(bs)ui.position.top=inst._convertPositionTo("relative",{top:b,left:0}).top-inst.margins.top;if(ls)ui.position.left=inst._convertPositionTo("relative",{top:0,left:l-inst.helperProportions.width}).left-inst.margins.left;if(rs)ui.position.left=inst._convertPositionTo("relative",{top:0,left:r}).left-inst.margins.left;}
var first=(ts||bs||ls||rs);if(o.snapMode!='outer'){var ts=Math.abs(t-y1)<=d;var bs=Math.abs(b-y2)<=d;var ls=Math.abs(l-x1)<=d;var rs=Math.abs(r-x2)<=d;if(ts)ui.position.top=inst._convertPositionTo("relative",{top:t,left:0}).top-inst.margins.top;if(bs)ui.position.top=inst._convertPositionTo("relative",{top:b-inst.helperProportions.height,left:0}).top-inst.margins.top;if(ls)ui.position.left=inst._convertPositionTo("relative",{top:0,left:l}).left-inst.margins.left;if(rs)ui.position.left=inst._convertPositionTo("relative",{top:0,left:r-inst.helperProportions.width}).left-inst.margins.left;}
if(!inst.snapElements[i].snapping&&(ts||bs||ls||rs||first))
(inst.options.snap.snap&&inst.options.snap.snap.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item})));inst.snapElements[i].snapping=(ts||bs||ls||rs||first);};}});$.ui.plugin.add("draggable","stack",{start:function(event,ui){var o=$(this).data("draggable").options;var group=$.makeArray($(o.stack)).sort(function(a,b){return(parseInt($(a).css("zIndex"),10)||0)-(parseInt($(b).css("zIndex"),10)||0);});if(!group.length){return;}
var min=parseInt(group[0].style.zIndex)||0;$(group).each(function(i){this.style.zIndex=min+i;});this[0].style.zIndex=min+group.length;}});$.ui.plugin.add("draggable","zIndex",{start:function(event,ui){var t=$(ui.helper),o=$(this).data("draggable").options;if(t.css("zIndex"))o._zIndex=t.css("zIndex");t.css('zIndex',o.zIndex);},stop:function(event,ui){var o=$(this).data("draggable").options;if(o._zIndex)$(ui.helper).css('zIndex',o._zIndex);}});})(jQuery);(function($,undefined){$.widget("ui.droppable",{version:"1.9.2",widgetEventPrefix:"drop",options:{accept:'*',activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:'default',tolerance:'intersect'},_create:function(){var o=this.options,accept=o.accept;this.isover=0;this.isout=1;this.accept=$.isFunction(accept)?accept:function(d){return d.is(accept);};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};$.ui.ddmanager.droppables[o.scope]=$.ui.ddmanager.droppables[o.scope]||[];$.ui.ddmanager.droppables[o.scope].push(this);(o.addClasses&&this.element.addClass("ui-droppable"));},_destroy:function(){var drop=$.ui.ddmanager.droppables[this.options.scope];for(var i=0;i<drop.length;i++)
if(drop[i]==this)
drop.splice(i,1);this.element.removeClass("ui-droppable ui-droppable-disabled");},_setOption:function(key,value){if(key=='accept'){this.accept=$.isFunction(value)?value:function(d){return d.is(value);};}
$.Widget.prototype._setOption.apply(this,arguments);},_activate:function(event){var draggable=$.ui.ddmanager.current;if(this.options.activeClass)this.element.addClass(this.options.activeClass);(draggable&&this._trigger('activate',event,this.ui(draggable)));},_deactivate:function(event){var draggable=$.ui.ddmanager.current;if(this.options.activeClass)this.element.removeClass(this.options.activeClass);(draggable&&this._trigger('deactivate',event,this.ui(draggable)));},_over:function(event){var draggable=$.ui.ddmanager.current;if(!draggable||(draggable.currentItem||draggable.element)[0]==this.element[0])return;if(this.accept.call(this.element[0],(draggable.currentItem||draggable.element))){if(this.options.hoverClass)this.element.addClass(this.options.hoverClass);this._trigger('over',event,this.ui(draggable));}},_out:function(event){var draggable=$.ui.ddmanager.current;if(!draggable||(draggable.currentItem||draggable.element)[0]==this.element[0])return;if(this.accept.call(this.element[0],(draggable.currentItem||draggable.element))){if(this.options.hoverClass)this.element.removeClass(this.options.hoverClass);this._trigger('out',event,this.ui(draggable));}},_drop:function(event,custom){var draggable=custom||$.ui.ddmanager.current;if(!draggable||(draggable.currentItem||draggable.element)[0]==this.element[0])return false;var childrenIntersection=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var inst=$.data(this,'droppable');if(inst.options.greedy&&!inst.options.disabled&&inst.options.scope==draggable.options.scope&&inst.accept.call(inst.element[0],(draggable.currentItem||draggable.element))&&$.ui.intersect(draggable,$.extend(inst,{offset:inst.element.offset()}),inst.options.tolerance)){childrenIntersection=true;return false;}});if(childrenIntersection)return false;if(this.accept.call(this.element[0],(draggable.currentItem||draggable.element))){if(this.options.activeClass)this.element.removeClass(this.options.activeClass);if(this.options.hoverClass)this.element.removeClass(this.options.hoverClass);this._trigger('drop',event,this.ui(draggable));return this.element;}
return false;},ui:function(c){return{draggable:(c.currentItem||c.element),helper:c.helper,position:c.position,offset:c.positionAbs};}});$.ui.intersect=function(draggable,droppable,toleranceMode){if(!droppable.offset)return false;var x1=(draggable.positionAbs||draggable.position.absolute).left,x2=x1+draggable.helperProportions.width,y1=(draggable.positionAbs||draggable.position.absolute).top,y2=y1+draggable.helperProportions.height;var l=droppable.offset.left,r=l+droppable.proportions.width,t=droppable.offset.top,b=t+droppable.proportions.height;switch(toleranceMode){case'fit':return(l<=x1&&x2<=r&&t<=y1&&y2<=b);break;case'intersect':return(l<x1+(draggable.helperProportions.width/2)&&x2-(draggable.helperProportions.width/2)<r&&t<y1+(draggable.helperProportions.height/2)&&y2-(draggable.helperProportions.height/2)<b);break;case'pointer':var draggableLeft=((draggable.positionAbs||draggable.position.absolute).left+(draggable.clickOffset||draggable.offset.click).left),draggableTop=((draggable.positionAbs||draggable.position.absolute).top+(draggable.clickOffset||draggable.offset.click).top),isOver=$.ui.isOver(draggableTop,draggableLeft,t,l,droppable.proportions.height,droppable.proportions.width);return isOver;break;case'touch':return((y1>=t&&y1<=b)||(y2>=t&&y2<=b)||(y1<t&&y2>b))&&((x1>=l&&x1<=r)||(x2>=l&&x2<=r)||(x1<l&&x2>r));break;default:return false;break;}};$.ui.ddmanager={current:null,droppables:{'default':[]},prepareOffsets:function(t,event){var m=$.ui.ddmanager.droppables[t.options.scope]||[];var type=event?event.type:null;var list=(t.currentItem||t.element).find(":data(droppable)").andSelf();droppablesLoop:for(var i=0;i<m.length;i++){if(m[i].options.disabled||(t&&!m[i].accept.call(m[i].element[0],(t.currentItem||t.element))))continue;for(var j=0;j<list.length;j++){if(list[j]==m[i].element[0]){m[i].proportions.height=0;continue droppablesLoop;}};m[i].visible=m[i].element.css("display")!="none";if(!m[i].visible)continue;if(type=="mousedown")m[i]._activate.call(m[i],event);m[i].offset=m[i].element.offset();m[i].proportions={width:m[i].element[0].offsetWidth,height:m[i].element[0].offsetHeight};}},drop:function(draggable,event){var dropped=false;$.each($.ui.ddmanager.droppables[draggable.options.scope]||[],function(){if(!this.options)return;if(!this.options.disabled&&this.visible&&$.ui.intersect(draggable,this,this.options.tolerance))
dropped=this._drop.call(this,event)||dropped;if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],(draggable.currentItem||draggable.element))){this.isout=1;this.isover=0;this._deactivate.call(this,event);}});return dropped;},dragStart:function(draggable,event){draggable.element.parentsUntil("body").bind("scroll.droppable",function(){if(!draggable.options.refreshPositions)$.ui.ddmanager.prepareOffsets(draggable,event);});},drag:function(draggable,event){if(draggable.options.refreshPositions)$.ui.ddmanager.prepareOffsets(draggable,event);$.each($.ui.ddmanager.droppables[draggable.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var intersects=$.ui.intersect(draggable,this,this.options.tolerance);var c=!intersects&&this.isover==1?'isout':(intersects&&this.isover==0?'isover':null);if(!c)return;var parentInstance;if(this.options.greedy){var scope=this.options.scope;var parent=this.element.parents(':data(droppable)').filter(function(){return $.data(this,'droppable').options.scope===scope;});if(parent.length){parentInstance=$.data(parent[0],'droppable');parentInstance.greedyChild=(c=='isover'?1:0);}}
if(parentInstance&&c=='isover'){parentInstance['isover']=0;parentInstance['isout']=1;parentInstance._out.call(parentInstance,event);}
this[c]=1;this[c=='isout'?'isover':'isout']=0;this[c=="isover"?"_over":"_out"].call(this,event);if(parentInstance&&c=='isout'){parentInstance['isout']=0;parentInstance['isover']=1;parentInstance._over.call(parentInstance,event);}});},dragStop:function(draggable,event){draggable.element.parentsUntil("body").unbind("scroll.droppable");if(!draggable.options.refreshPositions)$.ui.ddmanager.prepareOffsets(draggable,event);}};})(jQuery);(function($,undefined){$.widget("ui.selectable",$.ui.mouse,{version:"1.9.2",options:{appendTo:'body',autoRefresh:true,distance:0,filter:'*',tolerance:'touch'},_create:function(){var that=this;this.element.addClass("ui-selectable");this.dragged=false;var selectees;this.refresh=function(){selectees=$(that.options.filter,that.element[0]);selectees.addClass("ui-selectee");selectees.each(function(){var $this=$(this);var pos=$this.offset();$.data(this,"selectable-item",{element:this,$element:$this,left:pos.left,top:pos.top,right:pos.left+$this.outerWidth(),bottom:pos.top+$this.outerHeight(),startselected:false,selected:$this.hasClass('ui-selected'),selecting:$this.hasClass('ui-selecting'),unselecting:$this.hasClass('ui-unselecting')});});};this.refresh();this.selectees=selectees.addClass("ui-selectee");this._mouseInit();this.helper=$("<div class='ui-selectable-helper'></div>");},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled");this._mouseDestroy();},_mouseStart:function(event){var that=this;this.opos=[event.pageX,event.pageY];if(this.options.disabled)
return;var options=this.options;this.selectees=$(options.filter,this.element[0]);this._trigger("start",event);$(options.appendTo).append(this.helper);this.helper.css({"left":event.clientX,"top":event.clientY,"width":0,"height":0});if(options.autoRefresh){this.refresh();}
this.selectees.filter('.ui-selected').each(function(){var selectee=$.data(this,"selectable-item");selectee.startselected=true;if(!event.metaKey&&!event.ctrlKey){selectee.$element.removeClass('ui-selected');selectee.selected=false;selectee.$element.addClass('ui-unselecting');selectee.unselecting=true;that._trigger("unselecting",event,{unselecting:selectee.element});}});$(event.target).parents().andSelf().each(function(){var selectee=$.data(this,"selectable-item");if(selectee){var doSelect=(!event.metaKey&&!event.ctrlKey)||!selectee.$element.hasClass('ui-selected');selectee.$element.removeClass(doSelect?"ui-unselecting":"ui-selected").addClass(doSelect?"ui-selecting":"ui-unselecting");selectee.unselecting=!doSelect;selectee.selecting=doSelect;selectee.selected=doSelect;if(doSelect){that._trigger("selecting",event,{selecting:selectee.element});}else{that._trigger("unselecting",event,{unselecting:selectee.element});}
return false;}});},_mouseDrag:function(event){var that=this;this.dragged=true;if(this.options.disabled)
return;var options=this.options;var x1=this.opos[0],y1=this.opos[1],x2=event.pageX,y2=event.pageY;if(x1>x2){var tmp=x2;x2=x1;x1=tmp;}
if(y1>y2){var tmp=y2;y2=y1;y1=tmp;}
this.helper.css({left:x1,top:y1,width:x2-x1,height:y2-y1});this.selectees.each(function(){var selectee=$.data(this,"selectable-item");if(!selectee||selectee.element==that.element[0])
return;var hit=false;if(options.tolerance=='touch'){hit=(!(selectee.left>x2||selectee.right<x1||selectee.top>y2||selectee.bottom<y1));}else if(options.tolerance=='fit'){hit=(selectee.left>x1&&selectee.right<x2&&selectee.top>y1&&selectee.bottom<y2);}
if(hit){if(selectee.selected){selectee.$element.removeClass('ui-selected');selectee.selected=false;}
if(selectee.unselecting){selectee.$element.removeClass('ui-unselecting');selectee.unselecting=false;}
if(!selectee.selecting){selectee.$element.addClass('ui-selecting');selectee.selecting=true;that._trigger("selecting",event,{selecting:selectee.element});}}else{if(selectee.selecting){if((event.metaKey||event.ctrlKey)&&selectee.startselected){selectee.$element.removeClass('ui-selecting');selectee.selecting=false;selectee.$element.addClass('ui-selected');selectee.selected=true;}else{selectee.$element.removeClass('ui-selecting');selectee.selecting=false;if(selectee.startselected){selectee.$element.addClass('ui-unselecting');selectee.unselecting=true;}
that._trigger("unselecting",event,{unselecting:selectee.element});}}
if(selectee.selected){if(!event.metaKey&&!event.ctrlKey&&!selectee.startselected){selectee.$element.removeClass('ui-selected');selectee.selected=false;selectee.$element.addClass('ui-unselecting');selectee.unselecting=true;that._trigger("unselecting",event,{unselecting:selectee.element});}}}});return false;},_mouseStop:function(event){var that=this;this.dragged=false;var options=this.options;$('.ui-unselecting',this.element[0]).each(function(){var selectee=$.data(this,"selectable-item");selectee.$element.removeClass('ui-unselecting');selectee.unselecting=false;selectee.startselected=false;that._trigger("unselected",event,{unselected:selectee.element});});$('.ui-selecting',this.element[0]).each(function(){var selectee=$.data(this,"selectable-item");selectee.$element.removeClass('ui-selecting').addClass('ui-selected');selectee.selecting=false;selectee.selected=true;selectee.startselected=true;that._trigger("selected",event,{selected:selectee.element});});this._trigger("stop",event);this.helper.remove();return false;}});})(jQuery);(function($,undefined){$.widget("ui.sortable",$.ui.mouse,{version:"1.9.2",widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:'auto',cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:'> *',opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000},_create:function(){var o=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?o.axis==='x'||(/left|right/).test(this.items[0].item.css('float'))||(/inline|table-cell/).test(this.items[0].item.css('display')):false;this.offset=this.element.offset();this._mouseInit();this.ready=true},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var i=this.items.length-1;i>=0;i--)
this.items[i].item.removeData(this.widgetName+"-item");return this;},_setOption:function(key,value){if(key==="disabled"){this.options[key]=value;this.widget().toggleClass("ui-sortable-disabled",!!value);}else{$.Widget.prototype._setOption.apply(this,arguments);}},_mouseCapture:function(event,overrideHandle){var that=this;if(this.reverting){return false;}
if(this.options.disabled||this.options.type=='static')return false;this._refreshItems(event);var currentItem=null,nodes=$(event.target).parents().each(function(){if($.data(this,that.widgetName+'-item')==that){currentItem=$(this);return false;}});if($.data(event.target,that.widgetName+'-item')==that)currentItem=$(event.target);if(!currentItem)return false;if(this.options.handle&&!overrideHandle){var validHandle=false;$(this.options.handle,currentItem).find("*").andSelf().each(function(){if(this==event.target)validHandle=true;});if(!validHandle)return false;}
this.currentItem=currentItem;this._removeCurrentsFromItems();return true;},_mouseStart:function(event,overrideHandle,noActivation){var o=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(event);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};$.extend(this.offset,{click:{left:event.pageX-this.offset.left,top:event.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(event);this.originalPageX=event.pageX;this.originalPageY=event.pageY;(o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt));this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide();}
this._createPlaceholder();if(o.containment)
this._setContainment();if(o.cursor){if($('body').css("cursor"))this._storedCursor=$('body').css("cursor");$('body').css("cursor",o.cursor);}
if(o.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",o.opacity);}
if(o.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",o.zIndex);}
if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!='HTML')
this.overflowOffset=this.scrollParent.offset();this._trigger("start",event,this._uiHash());if(!this._preserveHelperProportions)
this._cacheHelperProportions();if(!noActivation){for(var i=this.containers.length-1;i>=0;i--){this.containers[i]._trigger("activate",event,this._uiHash(this));}}
if($.ui.ddmanager)
$.ui.ddmanager.current=this;if($.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this,event);this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(event);return true;},_mouseDrag:function(event){this.position=this._generatePosition(event);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs;}
if(this.options.scroll){var o=this.options,scrolled=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!='HTML'){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-event.pageY<o.scrollSensitivity)
this.scrollParent[0].scrollTop=scrolled=this.scrollParent[0].scrollTop+o.scrollSpeed;else if(event.pageY-this.overflowOffset.top<o.scrollSensitivity)
this.scrollParent[0].scrollTop=scrolled=this.scrollParent[0].scrollTop-o.scrollSpeed;if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-event.pageX<o.scrollSensitivity)
this.scrollParent[0].scrollLeft=scrolled=this.scrollParent[0].scrollLeft+o.scrollSpeed;else if(event.pageX-this.overflowOffset.left<o.scrollSensitivity)
this.scrollParent[0].scrollLeft=scrolled=this.scrollParent[0].scrollLeft-o.scrollSpeed;}else{if(event.pageY-$(document).scrollTop()<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()-o.scrollSpeed);else if($(window).height()-(event.pageY-$(document).scrollTop())<o.scrollSensitivity)
scrolled=$(document).scrollTop($(document).scrollTop()+o.scrollSpeed);if(event.pageX-$(document).scrollLeft()<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()-o.scrollSpeed);else if($(window).width()-(event.pageX-$(document).scrollLeft())<o.scrollSensitivity)
scrolled=$(document).scrollLeft($(document).scrollLeft()+o.scrollSpeed);}
if(scrolled!==false&&$.ui.ddmanager&&!o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this,event);}
this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+'px';if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+'px';for(var i=this.items.length-1;i>=0;i--){var item=this.items[i],itemElement=item.item[0],intersection=this._intersectsWithPointer(item);if(!intersection)continue;if(item.instance!==this.currentContainer)continue;if(itemElement!=this.currentItem[0]&&this.placeholder[intersection==1?"next":"prev"]()[0]!=itemElement&&!$.contains(this.placeholder[0],itemElement)&&(this.options.type=='semi-dynamic'?!$.contains(this.element[0],itemElement):true)){this.direction=intersection==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(item)){this._rearrange(event,item);}else{break;}
this._trigger("change",event,this._uiHash());break;}}
this._contactContainers(event);if($.ui.ddmanager)$.ui.ddmanager.drag(this,event);this._trigger('sort',event,this._uiHash());this.lastPositionAbs=this.positionAbs;return false;},_mouseStop:function(event,noPropagation){if(!event)return;if($.ui.ddmanager&&!this.options.dropBehaviour)
$.ui.ddmanager.drop(this,event);if(this.options.revert){var that=this;var cur=this.placeholder.offset();this.reverting=true;$(this.helper).animate({left:cur.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:cur.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){that._clear(event);});}else{this._clear(event,noPropagation);}
return false;},cancel:function(){if(this.dragging){this._mouseUp({target:null});if(this.options.helper=="original")
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");else
this.currentItem.show();for(var i=this.containers.length-1;i>=0;i--){this.containers[i]._trigger("deactivate",null,this._uiHash(this));if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",null,this._uiHash(this));this.containers[i].containerCache.over=0;}}}
if(this.placeholder){if(this.placeholder[0].parentNode)this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode)this.helper.remove();$.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){$(this.domPosition.prev).after(this.currentItem);}else{$(this.domPosition.parent).prepend(this.currentItem);}}
return this;},serialize:function(o){var items=this._getItemsAsjQuery(o&&o.connected);var str=[];o=o||{};$(items).each(function(){var res=($(o.item||this).attr(o.attribute||'id')||'').match(o.expression||(/(.+)[-=_](.+)/));if(res)str.push((o.key||res[1]+'[]')+'='+(o.key&&o.expression?res[1]:res[2]));});if(!str.length&&o.key){str.push(o.key+'=');}
return str.join('&');},toArray:function(o){var items=this._getItemsAsjQuery(o&&o.connected);var ret=[];o=o||{};items.each(function(){ret.push($(o.item||this).attr(o.attribute||'id')||'');});return ret;},_intersectsWith:function(item){var x1=this.positionAbs.left,x2=x1+this.helperProportions.width,y1=this.positionAbs.top,y2=y1+this.helperProportions.height;var l=item.left,r=l+item.width,t=item.top,b=t+item.height;var dyClick=this.offset.click.top,dxClick=this.offset.click.left;var isOverElement=(y1+dyClick)>t&&(y1+dyClick)<b&&(x1+dxClick)>l&&(x1+dxClick)<r;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?'width':'height']>item[this.floating?'width':'height'])){return isOverElement;}else{return(l<x1+(this.helperProportions.width/2)&&x2-(this.helperProportions.width/2)<r&&t<y1+(this.helperProportions.height/2)&&y2-(this.helperProportions.height/2)<b);}},_intersectsWithPointer:function(item){var isOverElementHeight=(this.options.axis==='x')||$.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,item.top,item.height),isOverElementWidth=(this.options.axis==='y')||$.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,item.left,item.width),isOverElement=isOverElementHeight&&isOverElementWidth,verticalDirection=this._getDragVerticalDirection(),horizontalDirection=this._getDragHorizontalDirection();if(!isOverElement)
return false;return this.floating?(((horizontalDirection&&horizontalDirection=="right")||verticalDirection=="down")?2:1):(verticalDirection&&(verticalDirection=="down"?2:1));},_intersectsWithSides:function(item){var isOverBottomHalf=$.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,item.top+(item.height/2),item.height),isOverRightHalf=$.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,item.left+(item.width/2),item.width),verticalDirection=this._getDragVerticalDirection(),horizontalDirection=this._getDragHorizontalDirection();if(this.floating&&horizontalDirection){return((horizontalDirection=="right"&&isOverRightHalf)||(horizontalDirection=="left"&&!isOverRightHalf));}else{return verticalDirection&&((verticalDirection=="down"&&isOverBottomHalf)||(verticalDirection=="up"&&!isOverBottomHalf));}},_getDragVerticalDirection:function(){var delta=this.positionAbs.top-this.lastPositionAbs.top;return delta!=0&&(delta>0?"down":"up");},_getDragHorizontalDirection:function(){var delta=this.positionAbs.left-this.lastPositionAbs.left;return delta!=0&&(delta>0?"right":"left");},refresh:function(event){this._refreshItems(event);this.refreshPositions();return this;},_connectWith:function(){var options=this.options;return options.connectWith.constructor==String?[options.connectWith]:options.connectWith;},_getItemsAsjQuery:function(connected){var items=[];var queries=[];var connectWith=this._connectWith();if(connectWith&&connected){for(var i=connectWith.length-1;i>=0;i--){var cur=$(connectWith[i]);for(var j=cur.length-1;j>=0;j--){var inst=$.data(cur[j],this.widgetName);if(inst&&inst!=this&&!inst.options.disabled){queries.push([$.isFunction(inst.options.items)?inst.options.items.call(inst.element):$(inst.options.items,inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'),inst]);}};};}
queries.push([$.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):$(this.options.items,this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'),this]);for(var i=queries.length-1;i>=0;i--){queries[i][0].each(function(){items.push(this);});};return $(items);},_removeCurrentsFromItems:function(){var list=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=$.grep(this.items,function(item){for(var j=0;j<list.length;j++){if(list[j]==item.item[0])
return false;};return true;});},_refreshItems:function(event){this.items=[];this.containers=[this];var items=this.items;var queries=[[$.isFunction(this.options.items)?this.options.items.call(this.element[0],event,{item:this.currentItem}):$(this.options.items,this.element),this]];var connectWith=this._connectWith();if(connectWith&&this.ready){for(var i=connectWith.length-1;i>=0;i--){var cur=$(connectWith[i]);for(var j=cur.length-1;j>=0;j--){var inst=$.data(cur[j],this.widgetName);if(inst&&inst!=this&&!inst.options.disabled){queries.push([$.isFunction(inst.options.items)?inst.options.items.call(inst.element[0],event,{item:this.currentItem}):$(inst.options.items,inst.element),inst]);this.containers.push(inst);}};};}
for(var i=queries.length-1;i>=0;i--){var targetData=queries[i][1];var _queries=queries[i][0];for(var j=0,queriesLength=_queries.length;j<queriesLength;j++){var item=$(_queries[j]);item.data(this.widgetName+'-item',targetData);items.push({item:item,instance:targetData,width:0,height:0,left:0,top:0});};};},refreshPositions:function(fast){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset();}
for(var i=this.items.length-1;i>=0;i--){var item=this.items[i];if(item.instance!=this.currentContainer&&this.currentContainer&&item.item[0]!=this.currentItem[0])
continue;var t=this.options.toleranceElement?$(this.options.toleranceElement,item.item):item.item;if(!fast){item.width=t.outerWidth();item.height=t.outerHeight();}
var p=t.offset();item.left=p.left;item.top=p.top;};if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this);}else{for(var i=this.containers.length-1;i>=0;i--){var p=this.containers[i].element.offset();this.containers[i].containerCache.left=p.left;this.containers[i].containerCache.top=p.top;this.containers[i].containerCache.width=this.containers[i].element.outerWidth();this.containers[i].containerCache.height=this.containers[i].element.outerHeight();};}
return this;},_createPlaceholder:function(that){that=that||this;var o=that.options;if(!o.placeholder||o.placeholder.constructor==String){var className=o.placeholder;o.placeholder={element:function(){var el=$(document.createElement(that.currentItem[0].nodeName)).addClass(className||that.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!className)
el.style.visibility="hidden";return el;},update:function(container,p){if(className&&!o.forcePlaceholderSize)return;if(!p.height()){p.height(that.currentItem.innerHeight()-parseInt(that.currentItem.css('paddingTop')||0,10)-parseInt(that.currentItem.css('paddingBottom')||0,10));};if(!p.width()){p.width(that.currentItem.innerWidth()-parseInt(that.currentItem.css('paddingLeft')||0,10)-parseInt(that.currentItem.css('paddingRight')||0,10));};}};}
that.placeholder=$(o.placeholder.element.call(that.element,that.currentItem));that.currentItem.after(that.placeholder);o.placeholder.update(that,that.placeholder);},_contactContainers:function(event){var innermostContainer=null,innermostIndex=null;for(var i=this.containers.length-1;i>=0;i--){if($.contains(this.currentItem[0],this.containers[i].element[0]))
continue;if(this._intersectsWith(this.containers[i].containerCache)){if(innermostContainer&&$.contains(this.containers[i].element[0],innermostContainer.element[0]))
continue;innermostContainer=this.containers[i];innermostIndex=i;}else{if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",event,this._uiHash(this));this.containers[i].containerCache.over=0;}}}
if(!innermostContainer)return;if(this.containers.length===1){this.containers[innermostIndex]._trigger("over",event,this._uiHash(this));this.containers[innermostIndex].containerCache.over=1;}else{var dist=10000;var itemWithLeastDistance=null;var posProperty=this.containers[innermostIndex].floating?'left':'top';var sizeProperty=this.containers[innermostIndex].floating?'width':'height';var base=this.positionAbs[posProperty]+this.offset.click[posProperty];for(var j=this.items.length-1;j>=0;j--){if(!$.contains(this.containers[innermostIndex].element[0],this.items[j].item[0]))continue;if(this.items[j].item[0]==this.currentItem[0])continue;var cur=this.items[j].item.offset()[posProperty];var nearBottom=false;if(Math.abs(cur-base)>Math.abs(cur+this.items[j][sizeProperty]-base)){nearBottom=true;cur+=this.items[j][sizeProperty];}
if(Math.abs(cur-base)<dist){dist=Math.abs(cur-base);itemWithLeastDistance=this.items[j];this.direction=nearBottom?"up":"down";}}
if(!itemWithLeastDistance&&!this.options.dropOnEmpty)
return;this.currentContainer=this.containers[innermostIndex];itemWithLeastDistance?this._rearrange(event,itemWithLeastDistance,null,true):this._rearrange(event,null,this.containers[innermostIndex].element,true);this._trigger("change",event,this._uiHash());this.containers[innermostIndex]._trigger("change",event,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[innermostIndex]._trigger("over",event,this._uiHash(this));this.containers[innermostIndex].containerCache.over=1;}},_createHelper:function(event){var o=this.options;var helper=$.isFunction(o.helper)?$(o.helper.apply(this.element[0],[event,this.currentItem])):(o.helper=='clone'?this.currentItem.clone():this.currentItem);if(!helper.parents('body').length)
$(o.appendTo!='parent'?o.appendTo:this.currentItem[0].parentNode)[0].appendChild(helper[0]);if(helper[0]==this.currentItem[0])
this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};if(helper[0].style.width==''||o.forceHelperSize)helper.width(this.currentItem.width());if(helper[0].style.height==''||o.forceHelperSize)helper.height(this.currentItem.height());return helper;},_adjustOffsetFromHelper:function(obj){if(typeof obj=='string'){obj=obj.split(' ');}
if($.isArray(obj)){obj={left:+obj[0],top:+obj[1]||0};}
if('left'in obj){this.offset.click.left=obj.left+this.margins.left;}
if('right'in obj){this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left;}
if('top'in obj){this.offset.click.top=obj.top+this.margins.top;}
if('bottom'in obj){this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top;}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var po=this.offsetParent.offset();if(this.cssPosition=='absolute'&&this.scrollParent[0]!=document&&$.contains(this.scrollParent[0],this.offsetParent[0])){po.left+=this.scrollParent.scrollLeft();po.top+=this.scrollParent.scrollTop();}
if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=='html'&&$.ui.ie))
po={top:0,left:0};return{top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var p=this.currentItem.position();return{top:p.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:p.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()};}else{return{top:0,left:0};}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)};},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function(){var o=this.options;if(o.containment=='parent')o.containment=this.helper[0].parentNode;if(o.containment=='document'||o.containment=='window')this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,$(o.containment=='document'?document:window).width()-this.helperProportions.width-this.margins.left,($(o.containment=='document'?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!(/^(document|window|parent)$/).test(o.containment)){var ce=$(o.containment)[0];var co=$(o.containment).offset();var over=($(ce).css("overflow")!='hidden');this.containment=[co.left+(parseInt($(ce).css("borderLeftWidth"),10)||0)+(parseInt($(ce).css("paddingLeft"),10)||0)-this.margins.left,co.top+(parseInt($(ce).css("borderTopWidth"),10)||0)+(parseInt($(ce).css("paddingTop"),10)||0)-this.margins.top,co.left+(over?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt($(ce).css("borderLeftWidth"),10)||0)-(parseInt($(ce).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,co.top+(over?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt($(ce).css("borderTopWidth"),10)||0)-(parseInt($(ce).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top];}},_convertPositionTo:function(d,pos){if(!pos)pos=this.position;var mod=d=="absolute"?1:-1;var o=this.options,scroll=this.cssPosition=='absolute'&&!(this.scrollParent[0]!=document&&$.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=(/(html|body)/i).test(scroll[0].tagName);return{top:(pos.top
+this.offset.relative.top*mod
+this.offset.parent.top*mod
-((this.cssPosition=='fixed'?-this.scrollParent.scrollTop():(scrollIsRootNode?0:scroll.scrollTop()))*mod)),left:(pos.left
+this.offset.relative.left*mod
+this.offset.parent.left*mod
-((this.cssPosition=='fixed'?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())*mod))};},_generatePosition:function(event){var o=this.options,scroll=this.cssPosition=='absolute'&&!(this.scrollParent[0]!=document&&$.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=(/(html|body)/i).test(scroll[0].tagName);if(this.cssPosition=='relative'&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset();}
var pageX=event.pageX;var pageY=event.pageY;if(this.originalPosition){if(this.containment){if(event.pageX-this.offset.click.left<this.containment[0])pageX=this.containment[0]+this.offset.click.left;if(event.pageY-this.offset.click.top<this.containment[1])pageY=this.containment[1]+this.offset.click.top;if(event.pageX-this.offset.click.left>this.containment[2])pageX=this.containment[2]+this.offset.click.left;if(event.pageY-this.offset.click.top>this.containment[3])pageY=this.containment[3]+this.offset.click.top;}
if(o.grid){var top=this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1];pageY=this.containment?(!(top-this.offset.click.top<this.containment[1]||top-this.offset.click.top>this.containment[3])?top:(!(top-this.offset.click.top<this.containment[1])?top-o.grid[1]:top+o.grid[1])):top;var left=this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0];pageX=this.containment?(!(left-this.offset.click.left<this.containment[0]||left-this.offset.click.left>this.containment[2])?left:(!(left-this.offset.click.left<this.containment[0])?left-o.grid[0]:left+o.grid[0])):left;}}
return{top:(pageY
-this.offset.click.top
-this.offset.relative.top
-this.offset.parent.top
+((this.cssPosition=='fixed'?-this.scrollParent.scrollTop():(scrollIsRootNode?0:scroll.scrollTop())))),left:(pageX
-this.offset.click.left
-this.offset.relative.left
-this.offset.parent.left
+((this.cssPosition=='fixed'?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())))};},_rearrange:function(event,i,a,hardRefresh){a?a[0].appendChild(this.placeholder[0]):i.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=='down'?i.item[0]:i.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var counter=this.counter;this._delay(function(){if(counter==this.counter)this.refreshPositions(!hardRefresh);});},_clear:function(event,noPropagation){this.reverting=false;var delayedTriggers=[];if(!this._noFinalSort&&this.currentItem.parent().length)this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var i in this._storedCSS){if(this._storedCSS[i]=='auto'||this._storedCSS[i]=='static')this._storedCSS[i]='';}
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");}else{this.currentItem.show();}
if(this.fromOutside&&!noPropagation)delayedTriggers.push(function(event){this._trigger("receive",event,this._uiHash(this.fromOutside));});if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!noPropagation)delayedTriggers.push(function(event){this._trigger("update",event,this._uiHash());});if(this!==this.currentContainer){if(!noPropagation){delayedTriggers.push(function(event){this._trigger("remove",event,this._uiHash());});delayedTriggers.push((function(c){return function(event){c._trigger("receive",event,this._uiHash(this));};}).call(this,this.currentContainer));delayedTriggers.push((function(c){return function(event){c._trigger("update",event,this._uiHash(this));};}).call(this,this.currentContainer));}}
for(var i=this.containers.length-1;i>=0;i--){if(!noPropagation)delayedTriggers.push((function(c){return function(event){c._trigger("deactivate",event,this._uiHash(this));};}).call(this,this.containers[i]));if(this.containers[i].containerCache.over){delayedTriggers.push((function(c){return function(event){c._trigger("out",event,this._uiHash(this));};}).call(this,this.containers[i]));this.containers[i].containerCache.over=0;}}
if(this._storedCursor)$('body').css("cursor",this._storedCursor);if(this._storedOpacity)this.helper.css("opacity",this._storedOpacity);if(this._storedZIndex)this.helper.css("zIndex",this._storedZIndex=='auto'?'':this._storedZIndex);this.dragging=false;if(this.cancelHelperRemoval){if(!noPropagation){this._trigger("beforeStop",event,this._uiHash());for(var i=0;i<delayedTriggers.length;i++){delayedTriggers[i].call(this,event);};this._trigger("stop",event,this._uiHash());}
this.fromOutside=false;return false;}
if(!noPropagation)this._trigger("beforeStop",event,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0])this.helper.remove();this.helper=null;if(!noPropagation){for(var i=0;i<delayedTriggers.length;i++){delayedTriggers[i].call(this,event);};this._trigger("stop",event,this._uiHash());}
this.fromOutside=false;return true;},_trigger:function(){if($.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel();}},_uiHash:function(_inst){var inst=_inst||this;return{helper:inst.helper,placeholder:inst.placeholder||$([]),position:inst.position,originalPosition:inst.originalPosition,offset:inst.positionAbs,item:inst.currentItem,sender:_inst?_inst.element:null};}});})(jQuery);;(function($){var bootstrapWizardCreate=function(element,options){var element=$(element);var obj=this;var $settings=$.extend({},$.fn.bootstrapWizard.defaults,options);var $activeTab=null;var $navigation=null;this.rebindClick=function(selector,fn)
{selector.unbind('click',fn).bind('click',fn);}
this.fixNavigationButtons=function(){if(!$activeTab.length){$navigation.find('a:first').tab('show');$activeTab=$navigation.find('li:first');}
$($settings.previousSelector,element).toggleClass('disabled',(obj.firstIndex()>=obj.currentIndex()));$($settings.nextSelector,element).toggleClass('disabled',(obj.currentIndex()>=obj.navigationLength()));obj.rebindClick($($settings.nextSelector,element),obj.next);obj.rebindClick($($settings.previousSelector,element),obj.previous);obj.rebindClick($($settings.lastSelector,element),obj.last);obj.rebindClick($($settings.firstSelector,element),obj.first);if($settings.onTabShow&&typeof $settings.onTabShow==='function'&&$settings.onTabShow($activeTab,$navigation,obj.currentIndex())===false){return false;}};this.next=function(e){if(element.hasClass('last')){return false;}
if($settings.onNext&&typeof $settings.onNext==='function'&&$settings.onNext($activeTab,$navigation,obj.nextIndex())===false){return false;}
$index=obj.nextIndex();if($index>obj.navigationLength()){}else{$navigation.find('li:eq('+$index+') a').tab('show');}};this.previous=function(e){if(element.hasClass('first')){return false;}
if($settings.onPrevious&&typeof $settings.onPrevious==='function'&&$settings.onPrevious($activeTab,$navigation,obj.previousIndex())===false){return false;}
$index=obj.previousIndex();if($index<0){}else{$navigation.find('li:eq('+$index+') a').tab('show');}};this.first=function(e){if($settings.onFirst&&typeof $settings.onFirst==='function'&&$settings.onFirst($activeTab,$navigation,obj.firstIndex())===false){return false;}
if(element.hasClass('disabled')){return false;}
$navigation.find('li:eq(0) a').tab('show');};this.last=function(e){if($settings.onLast&&typeof $settings.onLast==='function'&&$settings.onLast($activeTab,$navigation,obj.lastIndex())===false){return false;}
if(element.hasClass('disabled')){return false;}
$navigation.find('li:eq('+obj.navigationLength()+') a').tab('show');};this.currentIndex=function(){return $navigation.find('li').index($activeTab);};this.firstIndex=function(){return 0;};this.lastIndex=function(){return obj.navigationLength();};this.getIndex=function(e){return $navigation.find('li').index(e);};this.nextIndex=function(){return $navigation.find('li').index($activeTab)+1;};this.previousIndex=function(){return $navigation.find('li').index($activeTab)-1;};this.navigationLength=function(){return $navigation.find('li').length-1;};this.activeTab=function(){return $activeTab;};this.nextTab=function(){return $navigation.find('li:eq('+(obj.currentIndex()+1)+')').length?$navigation.find('li:eq('+(obj.currentIndex()+1)+')'):null;};this.previousTab=function(){if(obj.currentIndex()<=0){return null;}
return $navigation.find('li:eq('+parseInt(obj.currentIndex()-1)+')');};this.show=function(index){return element.find('li:eq('+index+') a').tab('show');};this.disable=function(index){$navigation.find('li:eq('+index+')').addClass('disabled');};this.enable=function(index){$navigation.find('li:eq('+index+')').removeClass('disabled');};this.hide=function(index){$navigation.find('li:eq('+index+')').hide();};this.display=function(index){$navigation.find('li:eq('+index+')').show();};this.remove=function(args){var $index=args[0];var $removeTabPane=typeof args[1]!='undefined'?args[1]:false;var $item=$navigation.find('li:eq('+$index+')');if($removeTabPane){var $href=$item.find('a').attr('href');$($href).remove();}
$item.remove();};$navigation=element.find('ul:first',element);$activeTab=$navigation.find('li.active',element);if(!$navigation.hasClass($settings.tabClass)){$navigation.addClass($settings.tabClass);}
if($settings.onInit&&typeof $settings.onInit==='function'){$settings.onInit($activeTab,$navigation,0);}
if($settings.onShow&&typeof $settings.onShow==='function'){$settings.onShow($activeTab,$navigation,obj.nextIndex());}
obj.fixNavigationButtons();$('a[data-toggle="tab"]',$navigation).on('click',function(e){var clickedIndex=$navigation.find('li').index($(e.currentTarget).parent('li'));if($settings.onTabClick&&typeof $settings.onTabClick==='function'&&$settings.onTabClick($activeTab,$navigation,obj.currentIndex(),clickedIndex)===false){return false;}});$('a[data-toggle="tab"]',$navigation).on('shown',function(e){$element=$(e.target).parent();var nextTab=$navigation.find('li').index($element);if($element.hasClass('disabled')){return false;}
if($settings.onTabChange&&typeof $settings.onTabChange==='function'&&$settings.onTabChange($activeTab,$navigation,obj.currentIndex(),nextTab)===false){return false;}
$activeTab=$element;obj.fixNavigationButtons();});};$.fn.bootstrapWizard=function(options){if(typeof options=='string'){var args=Array.prototype.slice.call(arguments,1)
if(args.length===1){args.toString();}
return this.data('bootstrapWizard')[options](args);}
return this.each(function(index){var element=$(this);if(element.data('bootstrapWizard'))return;var wizard=new bootstrapWizardCreate(element,options);element.data('bootstrapWizard',wizard);});};$.fn.bootstrapWizard.defaults={tabClass:'nav nav-pills',nextSelector:'.wizard li.next',previousSelector:'.wizard li.previous',firstSelector:'.wizard li.first',lastSelector:'.wizard li.last',onShow:null,onInit:null,onNext:null,onPrevious:null,onLast:null,onFirst:null,onTabChange:null,onTabClick:null,onTabShow:null};})(jQuery);d3=function(){var d3={version:"3.1.6"};if(!Date.now)Date.now=function(){return+new Date();};var d3_document=document,d3_window=window;try{d3_document.createElement("div").style.setProperty("opacity",0,"");}catch(error){var d3_style_prototype=d3_window.CSSStyleDeclaration.prototype,d3_style_setProperty=d3_style_prototype.setProperty;d3_style_prototype.setProperty=function(name,value,priority){d3_style_setProperty.call(this,name,value+"",priority);};}
d3.ascending=function(a,b){return a<b?-1:a>b?1:a>=b?0:NaN;};d3.descending=function(a,b){return b<a?-1:b>a?1:b>=a?0:NaN;};d3.min=function(array,f){var i=-1,n=array.length,a,b;if(arguments.length===1){while(++i<n&&((a=array[i])==null||a!=a))a=undefined;while(++i<n)if((b=array[i])!=null&&a>b)a=b;}else{while(++i<n&&((a=f.call(array,array[i],i))==null||a!=a))a=undefined;while(++i<n)if((b=f.call(array,array[i],i))!=null&&a>b)a=b;}
return a;};d3.max=function(array,f){var i=-1,n=array.length,a,b;if(arguments.length===1){while(++i<n&&((a=array[i])==null||a!=a))a=undefined;while(++i<n)if((b=array[i])!=null&&b>a)a=b;}else{while(++i<n&&((a=f.call(array,array[i],i))==null||a!=a))a=undefined;while(++i<n)if((b=f.call(array,array[i],i))!=null&&b>a)a=b;}
return a;};d3.extent=function(array,f){var i=-1,n=array.length,a,b,c;if(arguments.length===1){while(++i<n&&((a=c=array[i])==null||a!=a))a=c=undefined;while(++i<n)if((b=array[i])!=null){if(a>b)a=b;if(c<b)c=b;}}else{while(++i<n&&((a=c=f.call(array,array[i],i))==null||a!=a))a=undefined;while(++i<n)if((b=f.call(array,array[i],i))!=null){if(a>b)a=b;if(c<b)c=b;}}
return[a,c];};d3.sum=function(array,f){var s=0,n=array.length,a,i=-1;if(arguments.length===1){while(++i<n)if(!isNaN(a=+array[i]))s+=a;}else{while(++i<n)if(!isNaN(a=+f.call(array,array[i],i)))s+=a;}
return s;};function d3_number(x){return x!=null&&!isNaN(x);}
d3.mean=function(array,f){var n=array.length,a,m=0,i=-1,j=0;if(arguments.length===1){while(++i<n)if(d3_number(a=array[i]))m+=(a-m)/++j;}else{while(++i<n)if(d3_number(a=f.call(array,array[i],i)))m+=(a-m)/++j;}
return j?m:undefined;};d3.quantile=function(values,p){var H=(values.length-1)*p+1,h=Math.floor(H),v=+values[h-1],e=H-h;return e?v+e*(values[h]-v):v;};d3.median=function(array,f){if(arguments.length>1)array=array.map(f);array=array.filter(d3_number);return array.length?d3.quantile(array.sort(d3.ascending),.5):undefined;};d3.bisector=function(f){return{left:function(a,x,lo,hi){if(arguments.length<3)lo=0;if(arguments.length<4)hi=a.length;while(lo<hi){var mid=lo+hi>>>1;if(f.call(a,a[mid],mid)<x)lo=mid+1;else hi=mid;}
return lo;},right:function(a,x,lo,hi){if(arguments.length<3)lo=0;if(arguments.length<4)hi=a.length;while(lo<hi){var mid=lo+hi>>>1;if(x<f.call(a,a[mid],mid))hi=mid;else lo=mid+1;}
return lo;}};};var d3_bisector=d3.bisector(function(d){return d;});d3.bisectLeft=d3_bisector.left;d3.bisect=d3.bisectRight=d3_bisector.right;d3.shuffle=function(array){var m=array.length,t,i;while(m){i=Math.random()*m--|0;t=array[m],array[m]=array[i],array[i]=t;}
return array;};d3.permute=function(array,indexes){var permutes=[],i=-1,n=indexes.length;while(++i<n)permutes[i]=array[indexes[i]];return permutes;};d3.zip=function(){if(!(n=arguments.length))return[];for(var i=-1,m=d3.min(arguments,d3_zipLength),zips=new Array(m);++i<m;){for(var j=-1,n,zip=zips[i]=new Array(n);++j<n;){zip[j]=arguments[j][i];}}
return zips;};function d3_zipLength(d){return d.length;}
d3.transpose=function(matrix){return d3.zip.apply(d3,matrix);};d3.keys=function(map){var keys=[];for(var key in map)keys.push(key);return keys;};d3.values=function(map){var values=[];for(var key in map)values.push(map[key]);return values;};d3.entries=function(map){var entries=[];for(var key in map)entries.push({key:key,value:map[key]});return entries;};d3.merge=function(arrays){return Array.prototype.concat.apply([],arrays);};d3.range=function(start,stop,step){if(arguments.length<3){step=1;if(arguments.length<2){stop=start;start=0;}}
if((stop-start)/step===Infinity)throw new Error("infinite range");var range=[],k=d3_range_integerScale(Math.abs(step)),i=-1,j;start*=k,stop*=k,step*=k;if(step<0)while((j=start+step*++i)>stop)range.push(j/k);else while((j=start+step*++i)<stop)range.push(j/k);return range;};function d3_range_integerScale(x){var k=1;while(x*k%1)k*=10;return k;}
function d3_class(ctor,properties){try{for(var key in properties){Object.defineProperty(ctor.prototype,key,{value:properties[key],enumerable:false});}}catch(e){ctor.prototype=properties;}}
d3.map=function(object){var map=new d3_Map();for(var key in object)map.set(key,object[key]);return map;};function d3_Map(){}
d3_class(d3_Map,{has:function(key){return d3_map_prefix+key in this;},get:function(key){return this[d3_map_prefix+key];},set:function(key,value){return this[d3_map_prefix+key]=value;},remove:function(key){key=d3_map_prefix+key;return key in this&&delete this[key];},keys:function(){var keys=[];this.forEach(function(key){keys.push(key);});return keys;},values:function(){var values=[];this.forEach(function(key,value){values.push(value);});return values;},entries:function(){var entries=[];this.forEach(function(key,value){entries.push({key:key,value:value});});return entries;},forEach:function(f){for(var key in this){if(key.charCodeAt(0)===d3_map_prefixCode){f.call(this,key.substring(1),this[key]);}}}});var d3_map_prefix="\0",d3_map_prefixCode=d3_map_prefix.charCodeAt(0);d3.nest=function(){var nest={},keys=[],sortKeys=[],sortValues,rollup;function map(mapType,array,depth){if(depth>=keys.length)return rollup?rollup.call(nest,array):sortValues?array.sort(sortValues):array;var i=-1,n=array.length,key=keys[depth++],keyValue,object,setter,valuesByKey=new d3_Map(),values;while(++i<n){if(values=valuesByKey.get(keyValue=key(object=array[i]))){values.push(object);}else{valuesByKey.set(keyValue,[object]);}}
if(mapType){object=mapType();setter=function(keyValue,values){object.set(keyValue,map(mapType,values,depth));};}else{object={};setter=function(keyValue,values){object[keyValue]=map(mapType,values,depth);};}
valuesByKey.forEach(setter);return object;}
function entries(map,depth){if(depth>=keys.length)return map;var array=[],sortKey=sortKeys[depth++];map.forEach(function(key,keyMap){array.push({key:key,values:entries(keyMap,depth)});});return sortKey?array.sort(function(a,b){return sortKey(a.key,b.key);}):array;}
nest.map=function(array,mapType){return map(mapType,array,0);};nest.entries=function(array){return entries(map(d3.map,array,0),0);};nest.key=function(d){keys.push(d);return nest;};nest.sortKeys=function(order){sortKeys[keys.length-1]=order;return nest;};nest.sortValues=function(order){sortValues=order;return nest;};nest.rollup=function(f){rollup=f;return nest;};return nest;};d3.set=function(array){var set=new d3_Set();if(array)for(var i=0;i<array.length;i++)set.add(array[i]);return set;};function d3_Set(){}
d3_class(d3_Set,{has:function(value){return d3_map_prefix+value in this;},add:function(value){this[d3_map_prefix+value]=true;return value;},remove:function(value){value=d3_map_prefix+value;return value in this&&delete this[value];},values:function(){var values=[];this.forEach(function(value){values.push(value);});return values;},forEach:function(f){for(var value in this){if(value.charCodeAt(0)===d3_map_prefixCode){f.call(this,value.substring(1));}}}});d3.behavior={};d3.rebind=function(target,source){var i=1,n=arguments.length,method;while(++i<n)target[method=arguments[i]]=d3_rebind(target,source,source[method]);return target;};function d3_rebind(target,source,method){return function(){var value=method.apply(source,arguments);return value===source?target:value;};}
d3.dispatch=function(){var dispatch=new d3_dispatch(),i=-1,n=arguments.length;while(++i<n)dispatch[arguments[i]]=d3_dispatch_event(dispatch);return dispatch;};function d3_dispatch(){}
d3_dispatch.prototype.on=function(type,listener){var i=type.indexOf("."),name="";if(i>=0){name=type.substring(i+1);type=type.substring(0,i);}
if(type)return arguments.length<2?this[type].on(name):this[type].on(name,listener);if(arguments.length===2){if(listener==null)for(type in this){if(this.hasOwnProperty(type))this[type].on(name,null);}
return this;}};function d3_dispatch_event(dispatch){var listeners=[],listenerByName=new d3_Map();function event(){var z=listeners,i=-1,n=z.length,l;while(++i<n)if(l=z[i].on)l.apply(this,arguments);return dispatch;}
event.on=function(name,listener){var l=listenerByName.get(name),i;if(arguments.length<2)return l&&l.on;if(l){l.on=null;listeners=listeners.slice(0,i=listeners.indexOf(l)).concat(listeners.slice(i+1));listenerByName.remove(name);}
if(listener)listeners.push(listenerByName.set(name,{on:listener}));return dispatch;};return event;}
d3.event=null;function d3_eventCancel(){d3.event.stopPropagation();d3.event.preventDefault();}
function d3_eventSource(){var e=d3.event,s;while(s=e.sourceEvent)e=s;return e;}
function d3_eventSuppress(target,type){function off(){target.on(type,null);}
target.on(type,function(){d3_eventCancel();off();},true);setTimeout(off,0);}
function d3_eventDispatch(target){var dispatch=new d3_dispatch(),i=0,n=arguments.length;while(++i<n)dispatch[arguments[i]]=d3_dispatch_event(dispatch);dispatch.of=function(thiz,argumentz){return function(e1){try{var e0=e1.sourceEvent=d3.event;e1.target=target;d3.event=e1;dispatch[e1.type].apply(thiz,argumentz);}finally{d3.event=e0;}};};return dispatch;}
d3.mouse=function(container){return d3_mousePoint(container,d3_eventSource());};var d3_mouse_bug44083=/WebKit/.test(d3_window.navigator.userAgent)?-1:0;function d3_mousePoint(container,e){var svg=container.ownerSVGElement||container;if(svg.createSVGPoint){var point=svg.createSVGPoint();if(d3_mouse_bug44083<0&&(d3_window.scrollX||d3_window.scrollY)){svg=d3.select(d3_document.body).append("svg").style("position","absolute").style("top",0).style("left",0);var ctm=svg[0][0].getScreenCTM();d3_mouse_bug44083=!(ctm.f||ctm.e);svg.remove();}
if(d3_mouse_bug44083){point.x=e.pageX;point.y=e.pageY;}else{point.x=e.clientX;point.y=e.clientY;}
point=point.matrixTransform(container.getScreenCTM().inverse());return[point.x,point.y];}
var rect=container.getBoundingClientRect();return[e.clientX-rect.left-container.clientLeft,e.clientY-rect.top-container.clientTop];}
var d3_array=d3_arraySlice;function d3_arrayCopy(pseudoarray){var i=-1,n=pseudoarray.length,array=[];while(++i<n)array.push(pseudoarray[i]);return array;}
function d3_arraySlice(pseudoarray){return Array.prototype.slice.call(pseudoarray);}
try{d3_array(d3_document.documentElement.childNodes)[0].nodeType;}catch(e){d3_array=d3_arrayCopy;}
var d3_arraySubclass=[].__proto__?function(array,prototype){array.__proto__=prototype;}:function(array,prototype){for(var property in prototype)array[property]=prototype[property];};d3.touches=function(container,touches){if(arguments.length<2)touches=d3_eventSource().touches;return touches?d3_array(touches).map(function(touch){var point=d3_mousePoint(container,touch);point.identifier=touch.identifier;return point;}):[];};d3.behavior.drag=function(){var event=d3_eventDispatch(drag,"drag","dragstart","dragend"),origin=null;function drag(){this.on("mousedown.drag",mousedown).on("touchstart.drag",mousedown);}
function mousedown(){var target=this,event_=event.of(target,arguments),eventTarget=d3.event.target,touchId=d3.event.touches?d3.event.changedTouches[0].identifier:null,offset,origin_=point(),moved=0;var w=d3.select(d3_window).on(touchId!=null?"touchmove.drag-"+touchId:"mousemove.drag",dragmove).on(touchId!=null?"touchend.drag-"+touchId:"mouseup.drag",dragend,true);if(origin){offset=origin.apply(target,arguments);offset=[offset.x-origin_[0],offset.y-origin_[1]];}else{offset=[0,0];}
if(touchId==null)d3_eventCancel();event_({type:"dragstart"});function point(){var p=target.parentNode;return touchId!=null?d3.touches(p).filter(function(p){return p.identifier===touchId;})[0]:d3.mouse(p);}
function dragmove(){if(!target.parentNode)return dragend();var p=point(),dx=p[0]-origin_[0],dy=p[1]-origin_[1];moved|=dx|dy;origin_=p;d3_eventCancel();event_({type:"drag",x:p[0]+offset[0],y:p[1]+offset[1],dx:dx,dy:dy});}
function dragend(){event_({type:"dragend"});if(moved){d3_eventCancel();if(d3.event.target===eventTarget)d3_eventSuppress(w,"click");}
w.on(touchId!=null?"touchmove.drag-"+touchId:"mousemove.drag",null).on(touchId!=null?"touchend.drag-"+touchId:"mouseup.drag",null);}}
drag.origin=function(x){if(!arguments.length)return origin;origin=x;return drag;};return d3.rebind(drag,event,"on");};function d3_selection(groups){d3_arraySubclass(groups,d3_selectionPrototype);return groups;}
var d3_select=function(s,n){return n.querySelector(s);},d3_selectAll=function(s,n){return n.querySelectorAll(s);},d3_selectRoot=d3_document.documentElement,d3_selectMatcher=d3_selectRoot.matchesSelector||d3_selectRoot.webkitMatchesSelector||d3_selectRoot.mozMatchesSelector||d3_selectRoot.msMatchesSelector||d3_selectRoot.oMatchesSelector,d3_selectMatches=function(n,s){return d3_selectMatcher.call(n,s);};if(typeof Sizzle==="function"){d3_select=function(s,n){return Sizzle(s,n)[0]||null;};d3_selectAll=function(s,n){return Sizzle.uniqueSort(Sizzle(s,n));};d3_selectMatches=Sizzle.matchesSelector;}
d3.selection=function(){return d3_selectionRoot;};var d3_selectionPrototype=d3.selection.prototype=[];d3_selectionPrototype.select=function(selector){var subgroups=[],subgroup,subnode,group,node;if(typeof selector!=="function")selector=d3_selection_selector(selector);for(var j=-1,m=this.length;++j<m;){subgroups.push(subgroup=[]);subgroup.parentNode=(group=this[j]).parentNode;for(var i=-1,n=group.length;++i<n;){if(node=group[i]){subgroup.push(subnode=selector.call(node,node.__data__,i));if(subnode&&"__data__"in node)subnode.__data__=node.__data__;}else{subgroup.push(null);}}}
return d3_selection(subgroups);};function d3_selection_selector(selector){return function(){return d3_select(selector,this);};}
d3_selectionPrototype.selectAll=function(selector){var subgroups=[],subgroup,node;if(typeof selector!=="function")selector=d3_selection_selectorAll(selector);for(var j=-1,m=this.length;++j<m;){for(var group=this[j],i=-1,n=group.length;++i<n;){if(node=group[i]){subgroups.push(subgroup=d3_array(selector.call(node,node.__data__,i)));subgroup.parentNode=node;}}}
return d3_selection(subgroups);};function d3_selection_selectorAll(selector){return function(){return d3_selectAll(selector,this);};}
var d3_nsPrefix={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};d3.ns={prefix:d3_nsPrefix,qualify:function(name){var i=name.indexOf(":"),prefix=name;if(i>=0){prefix=name.substring(0,i);name=name.substring(i+1);}
return d3_nsPrefix.hasOwnProperty(prefix)?{space:d3_nsPrefix[prefix],local:name}:name;}};d3_selectionPrototype.attr=function(name,value){if(arguments.length<2){if(typeof name==="string"){var node=this.node();name=d3.ns.qualify(name);return name.local?node.getAttributeNS(name.space,name.local):node.getAttribute(name);}
for(value in name)this.each(d3_selection_attr(value,name[value]));return this;}
return this.each(d3_selection_attr(name,value));};function d3_selection_attr(name,value){name=d3.ns.qualify(name);function attrNull(){this.removeAttribute(name);}
function attrNullNS(){this.removeAttributeNS(name.space,name.local);}
function attrConstant(){this.setAttribute(name,value);}
function attrConstantNS(){this.setAttributeNS(name.space,name.local,value);}
function attrFunction(){var x=value.apply(this,arguments);if(x==null)this.removeAttribute(name);else this.setAttribute(name,x);}
function attrFunctionNS(){var x=value.apply(this,arguments);if(x==null)this.removeAttributeNS(name.space,name.local);else this.setAttributeNS(name.space,name.local,x);}
return value==null?name.local?attrNullNS:attrNull:typeof value==="function"?name.local?attrFunctionNS:attrFunction:name.local?attrConstantNS:attrConstant;}
function d3_collapse(s){return s.trim().replace(/\s+/g," ");}
d3.requote=function(s){return s.replace(d3_requote_re,"\\$&");};var d3_requote_re=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;d3_selectionPrototype.classed=function(name,value){if(arguments.length<2){if(typeof name==="string"){var node=this.node(),n=(name=name.trim().split(/^|\s+/g)).length,i=-1;if(value=node.classList){while(++i<n)if(!value.contains(name[i]))return false;}else{value=node.getAttribute("class");while(++i<n)if(!d3_selection_classedRe(name[i]).test(value))return false;}
return true;}
for(value in name)this.each(d3_selection_classed(value,name[value]));return this;}
return this.each(d3_selection_classed(name,value));};function d3_selection_classedRe(name){return new RegExp("(?:^|\\s+)"+d3.requote(name)+"(?:\\s+|$)","g");}
function d3_selection_classed(name,value){name=name.trim().split(/\s+/).map(d3_selection_classedName);var n=name.length;function classedConstant(){var i=-1;while(++i<n)name[i](this,value);}
function classedFunction(){var i=-1,x=value.apply(this,arguments);while(++i<n)name[i](this,x);}
return typeof value==="function"?classedFunction:classedConstant;}
function d3_selection_classedName(name){var re=d3_selection_classedRe(name);return function(node,value){if(c=node.classList)return value?c.add(name):c.remove(name);var c=node.getAttribute("class")||"";if(value){re.lastIndex=0;if(!re.test(c))node.setAttribute("class",d3_collapse(c+" "+name));}else{node.setAttribute("class",d3_collapse(c.replace(re," ")));}};}
d3_selectionPrototype.style=function(name,value,priority){var n=arguments.length;if(n<3){if(typeof name!=="string"){if(n<2)value="";for(priority in name)this.each(d3_selection_style(priority,name[priority],value));return this;}
if(n<2)return d3_window.getComputedStyle(this.node(),null).getPropertyValue(name);priority="";}
return this.each(d3_selection_style(name,value,priority));};function d3_selection_style(name,value,priority){function styleNull(){this.style.removeProperty(name);}
function styleConstant(){this.style.setProperty(name,value,priority);}
function styleFunction(){var x=value.apply(this,arguments);if(x==null)this.style.removeProperty(name);else this.style.setProperty(name,x,priority);}
return value==null?styleNull:typeof value==="function"?styleFunction:styleConstant;}
d3_selectionPrototype.property=function(name,value){if(arguments.length<2){if(typeof name==="string")return this.node()[name];for(value in name)this.each(d3_selection_property(value,name[value]));return this;}
return this.each(d3_selection_property(name,value));};function d3_selection_property(name,value){function propertyNull(){delete this[name];}
function propertyConstant(){this[name]=value;}
function propertyFunction(){var x=value.apply(this,arguments);if(x==null)delete this[name];else this[name]=x;}
return value==null?propertyNull:typeof value==="function"?propertyFunction:propertyConstant;}
d3_selectionPrototype.text=function(value){return arguments.length?this.each(typeof value==="function"?function(){var v=value.apply(this,arguments);this.textContent=v==null?"":v;}:value==null?function(){this.textContent="";}:function(){this.textContent=value;}):this.node().textContent;};d3_selectionPrototype.html=function(value){return arguments.length?this.each(typeof value==="function"?function(){var v=value.apply(this,arguments);this.innerHTML=v==null?"":v;}:value==null?function(){this.innerHTML="";}:function(){this.innerHTML=value;}):this.node().innerHTML;};d3_selectionPrototype.append=function(name){name=d3.ns.qualify(name);function append(){return this.appendChild(d3_document.createElementNS(this.namespaceURI,name));}
function appendNS(){return this.appendChild(d3_document.createElementNS(name.space,name.local));}
return this.select(name.local?appendNS:append);};d3_selectionPrototype.insert=function(name,before){name=d3.ns.qualify(name);if(typeof before!=="function")before=d3_selection_selector(before);function insert(d,i){return this.insertBefore(d3_document.createElementNS(this.namespaceURI,name),before.call(this,d,i));}
function insertNS(d,i){return this.insertBefore(d3_document.createElementNS(name.space,name.local),before.call(this,d,i));}
return this.select(name.local?insertNS:insert);};d3_selectionPrototype.remove=function(){return this.each(function(){var parent=this.parentNode;if(parent)parent.removeChild(this);});};d3_selectionPrototype.data=function(value,key){var i=-1,n=this.length,group,node;if(!arguments.length){value=new Array(n=(group=this[0]).length);while(++i<n){if(node=group[i]){value[i]=node.__data__;}}
return value;}
function bind(group,groupData){var i,n=group.length,m=groupData.length,n0=Math.min(n,m),updateNodes=new Array(m),enterNodes=new Array(m),exitNodes=new Array(n),node,nodeData;if(key){var nodeByKeyValue=new d3_Map(),dataByKeyValue=new d3_Map(),keyValues=[],keyValue;for(i=-1;++i<n;){keyValue=key.call(node=group[i],node.__data__,i);if(nodeByKeyValue.has(keyValue)){exitNodes[i]=node;}else{nodeByKeyValue.set(keyValue,node);}
keyValues.push(keyValue);}
for(i=-1;++i<m;){keyValue=key.call(groupData,nodeData=groupData[i],i);if(node=nodeByKeyValue.get(keyValue)){updateNodes[i]=node;node.__data__=nodeData;}else if(!dataByKeyValue.has(keyValue)){enterNodes[i]=d3_selection_dataNode(nodeData);}
dataByKeyValue.set(keyValue,nodeData);nodeByKeyValue.remove(keyValue);}
for(i=-1;++i<n;){if(nodeByKeyValue.has(keyValues[i])){exitNodes[i]=group[i];}}}else{for(i=-1;++i<n0;){node=group[i];nodeData=groupData[i];if(node){node.__data__=nodeData;updateNodes[i]=node;}else{enterNodes[i]=d3_selection_dataNode(nodeData);}}
for(;i<m;++i){enterNodes[i]=d3_selection_dataNode(groupData[i]);}
for(;i<n;++i){exitNodes[i]=group[i];}}
enterNodes.update=updateNodes;enterNodes.parentNode=updateNodes.parentNode=exitNodes.parentNode=group.parentNode;enter.push(enterNodes);update.push(updateNodes);exit.push(exitNodes);}
var enter=d3_selection_enter([]),update=d3_selection([]),exit=d3_selection([]);if(typeof value==="function"){while(++i<n){bind(group=this[i],value.call(group,group.parentNode.__data__,i));}}else{while(++i<n){bind(group=this[i],value);}}
update.enter=function(){return enter;};update.exit=function(){return exit;};return update;};function d3_selection_dataNode(data){return{__data__:data};}
d3_selectionPrototype.datum=function(value){return arguments.length?this.property("__data__",value):this.property("__data__");};d3_selectionPrototype.filter=function(filter){var subgroups=[],subgroup,group,node;if(typeof filter!=="function")filter=d3_selection_filter(filter);for(var j=0,m=this.length;j<m;j++){subgroups.push(subgroup=[]);subgroup.parentNode=(group=this[j]).parentNode;for(var i=0,n=group.length;i<n;i++){if((node=group[i])&&filter.call(node,node.__data__,i)){subgroup.push(node);}}}
return d3_selection(subgroups);};function d3_selection_filter(selector){return function(){return d3_selectMatches(this,selector);};}
d3_selectionPrototype.order=function(){for(var j=-1,m=this.length;++j<m;){for(var group=this[j],i=group.length-1,next=group[i],node;--i>=0;){if(node=group[i]){if(next&&next!==node.nextSibling)next.parentNode.insertBefore(node,next);next=node;}}}
return this;};d3_selectionPrototype.sort=function(comparator){comparator=d3_selection_sortComparator.apply(this,arguments);for(var j=-1,m=this.length;++j<m;)this[j].sort(comparator);return this.order();};function d3_selection_sortComparator(comparator){if(!arguments.length)comparator=d3.ascending;return function(a,b){return!a-!b||comparator(a.__data__,b.__data__);};}
function d3_noop(){}
d3_selectionPrototype.on=function(type,listener,capture){var n=arguments.length;if(n<3){if(typeof type!=="string"){if(n<2)listener=false;for(capture in type)this.each(d3_selection_on(capture,type[capture],listener));return this;}
if(n<2)return(n=this.node()["__on"+type])&&n._;capture=false;}
return this.each(d3_selection_on(type,listener,capture));};function d3_selection_on(type,listener,capture){var name="__on"+type,i=type.indexOf("."),wrap=d3_selection_onListener;if(i>0)type=type.substring(0,i);var filter=d3_selection_onFilters.get(type);if(filter)type=filter,wrap=d3_selection_onFilter;function onRemove(){var l=this[name];if(l){this.removeEventListener(type,l,l.$);delete this[name];}}
function onAdd(){var l=wrap(listener,d3_array(arguments));onRemove.call(this);this.addEventListener(type,this[name]=l,l.$=capture);l._=listener;}
function removeAll(){var re=new RegExp("^__on([^.]+)"+d3.requote(type)+"$"),match;for(var name in this){if(match=name.match(re)){var l=this[name];this.removeEventListener(match[1],l,l.$);delete this[name];}}}
return i?listener?onAdd:onRemove:listener?d3_noop:removeAll;}
var d3_selection_onFilters=d3.map({mouseenter:"mouseover",mouseleave:"mouseout"});d3_selection_onFilters.forEach(function(k){if("on"+k in d3_document)d3_selection_onFilters.remove(k);});function d3_selection_onListener(listener,argumentz){return function(e){var o=d3.event;d3.event=e;argumentz[0]=this.__data__;try{listener.apply(this,argumentz);}finally{d3.event=o;}};}
function d3_selection_onFilter(listener,argumentz){var l=d3_selection_onListener(listener,argumentz);return function(e){var target=this,related=e.relatedTarget;if(!related||related!==target&&!(related.compareDocumentPosition(target)&8)){l.call(target,e);}};}
d3_selectionPrototype.each=function(callback){return d3_selection_each(this,function(node,i,j){callback.call(node,node.__data__,i,j);});};function d3_selection_each(groups,callback){for(var j=0,m=groups.length;j<m;j++){for(var group=groups[j],i=0,n=group.length,node;i<n;i++){if(node=group[i])callback(node,i,j);}}
return groups;}
d3_selectionPrototype.call=function(callback){var args=d3_array(arguments);callback.apply(args[0]=this,args);return this;};d3_selectionPrototype.empty=function(){return!this.node();};d3_selectionPrototype.node=function(){for(var j=0,m=this.length;j<m;j++){for(var group=this[j],i=0,n=group.length;i<n;i++){var node=group[i];if(node)return node;}}
return null;};function d3_selection_enter(selection){d3_arraySubclass(selection,d3_selection_enterPrototype);return selection;}
var d3_selection_enterPrototype=[];d3.selection.enter=d3_selection_enter;d3.selection.enter.prototype=d3_selection_enterPrototype;d3_selection_enterPrototype.append=d3_selectionPrototype.append;d3_selection_enterPrototype.insert=d3_selectionPrototype.insert;d3_selection_enterPrototype.empty=d3_selectionPrototype.empty;d3_selection_enterPrototype.node=d3_selectionPrototype.node;d3_selection_enterPrototype.select=function(selector){var subgroups=[],subgroup,subnode,upgroup,group,node;for(var j=-1,m=this.length;++j<m;){upgroup=(group=this[j]).update;subgroups.push(subgroup=[]);subgroup.parentNode=group.parentNode;for(var i=-1,n=group.length;++i<n;){if(node=group[i]){subgroup.push(upgroup[i]=subnode=selector.call(group.parentNode,node.__data__,i));subnode.__data__=node.__data__;}else{subgroup.push(null);}}}
return d3_selection(subgroups);};d3_selectionPrototype.transition=function(){var id=d3_transitionInheritId||++d3_transitionId,subgroups=[],subgroup,node,transition=Object.create(d3_transitionInherit);transition.time=Date.now();for(var j=-1,m=this.length;++j<m;){subgroups.push(subgroup=[]);for(var group=this[j],i=-1,n=group.length;++i<n;){if(node=group[i])d3_transitionNode(node,i,id,transition);subgroup.push(node);}}
return d3_transition(subgroups,id);};d3.select=function(node){var group=[typeof node==="string"?d3_select(node,d3_document):node];group.parentNode=d3_selectRoot;return d3_selection([group]);};d3.selectAll=function(nodes){var group=d3_array(typeof nodes==="string"?d3_selectAll(nodes,d3_document):nodes);group.parentNode=d3_selectRoot;return d3_selection([group]);};var d3_selectionRoot=d3.select(d3_selectRoot);d3.behavior.zoom=function(){var translate=[0,0],translate0,scale=1,scale0,scaleExtent=d3_behavior_zoomInfinity,event=d3_eventDispatch(zoom,"zoom"),x0,x1,y0,y1,touchtime;function zoom(){this.on("mousedown.zoom",mousedown).on("mousemove.zoom",mousemove).on(d3_behavior_zoomWheel+".zoom",mousewheel).on("dblclick.zoom",dblclick).on("touchstart.zoom",touchstart).on("touchmove.zoom",touchmove).on("touchend.zoom",touchstart);}
zoom.translate=function(x){if(!arguments.length)return translate;translate=x.map(Number);rescale();return zoom;};zoom.scale=function(x){if(!arguments.length)return scale;scale=+x;rescale();return zoom;};zoom.scaleExtent=function(x){if(!arguments.length)return scaleExtent;scaleExtent=x==null?d3_behavior_zoomInfinity:x.map(Number);return zoom;};zoom.x=function(z){if(!arguments.length)return x1;x1=z;x0=z.copy();translate=[0,0];scale=1;return zoom;};zoom.y=function(z){if(!arguments.length)return y1;y1=z;y0=z.copy();translate=[0,0];scale=1;return zoom;};function location(p){return[(p[0]-translate[0])/scale,(p[1]-translate[1])/scale];}
function point(l){return[l[0]*scale+translate[0],l[1]*scale+translate[1]];}
function scaleTo(s){scale=Math.max(scaleExtent[0],Math.min(scaleExtent[1],s));}
function translateTo(p,l){l=point(l);translate[0]+=p[0]-l[0];translate[1]+=p[1]-l[1];}
function rescale(){if(x1)x1.domain(x0.range().map(function(x){return(x-translate[0])/scale;}).map(x0.invert));if(y1)y1.domain(y0.range().map(function(y){return(y-translate[1])/scale;}).map(y0.invert));}
function dispatch(event){rescale();d3.event.preventDefault();event({type:"zoom",scale:scale,translate:translate});}
function mousedown(){var target=this,event_=event.of(target,arguments),eventTarget=d3.event.target,moved=0,w=d3.select(d3_window).on("mousemove.zoom",mousemove).on("mouseup.zoom",mouseup),l=location(d3.mouse(target));d3_window.focus();d3_eventCancel();function mousemove(){moved=1;translateTo(d3.mouse(target),l);dispatch(event_);}
function mouseup(){if(moved)d3_eventCancel();w.on("mousemove.zoom",null).on("mouseup.zoom",null);if(moved&&d3.event.target===eventTarget)d3_eventSuppress(w,"click.zoom");}}
function mousewheel(){if(!translate0)translate0=location(d3.mouse(this));scaleTo(Math.pow(2,d3_behavior_zoomDelta()*.002)*scale);translateTo(d3.mouse(this),translate0);dispatch(event.of(this,arguments));}
function mousemove(){translate0=null;}
function dblclick(){var p=d3.mouse(this),l=location(p),k=Math.log(scale)/Math.LN2;scaleTo(Math.pow(2,d3.event.shiftKey?Math.ceil(k)-1:Math.floor(k)+1));translateTo(p,l);dispatch(event.of(this,arguments));}
function touchstart(){var touches=d3.touches(this),now=Date.now();scale0=scale;translate0={};touches.forEach(function(t){translate0[t.identifier]=location(t);});d3_eventCancel();if(touches.length===1){if(now-touchtime<500){var p=touches[0],l=location(touches[0]);scaleTo(scale*2);translateTo(p,l);dispatch(event.of(this,arguments));}
touchtime=now;}}
function touchmove(){var touches=d3.touches(this),p0=touches[0],l0=translate0[p0.identifier];if(p1=touches[1]){var p1,l1=translate0[p1.identifier];p0=[(p0[0]+p1[0])/2,(p0[1]+p1[1])/2];l0=[(l0[0]+l1[0])/2,(l0[1]+l1[1])/2];scaleTo(d3.event.scale*scale0);}
translateTo(p0,l0);touchtime=null;dispatch(event.of(this,arguments));}
return d3.rebind(zoom,event,"on");};var d3_behavior_zoomInfinity=[0,Infinity];var d3_behavior_zoomDelta,d3_behavior_zoomWheel="onwheel"in d3_document?(d3_behavior_zoomDelta=function(){return-d3.event.deltaY*(d3.event.deltaMode?120:1);},"wheel"):"onmousewheel"in d3_document?(d3_behavior_zoomDelta=function(){return d3.event.wheelDelta;},"mousewheel"):(d3_behavior_zoomDelta=function(){return-d3.event.detail;},"MozMousePixelScroll");function d3_Color(){}
d3_Color.prototype.toString=function(){return this.rgb()+"";};d3.hsl=function(h,s,l){return arguments.length===1?h instanceof d3_Hsl?d3_hsl(h.h,h.s,h.l):d3_rgb_parse(""+h,d3_rgb_hsl,d3_hsl):d3_hsl(+h,+s,+l);};function d3_hsl(h,s,l){return new d3_Hsl(h,s,l);}
function d3_Hsl(h,s,l){this.h=h;this.s=s;this.l=l;}
var d3_hslPrototype=d3_Hsl.prototype=new d3_Color();d3_hslPrototype.brighter=function(k){k=Math.pow(.7,arguments.length?k:1);return d3_hsl(this.h,this.s,this.l/k);};d3_hslPrototype.darker=function(k){k=Math.pow(.7,arguments.length?k:1);return d3_hsl(this.h,this.s,k*this.l);};d3_hslPrototype.rgb=function(){return d3_hsl_rgb(this.h,this.s,this.l);};function d3_hsl_rgb(h,s,l){var m1,m2;h=isNaN(h)?0:(h%=360)<0?h+360:h;s=isNaN(s)?0:s<0?0:s>1?1:s;l=l<0?0:l>1?1:l;m2=l<=.5?l*(1+s):l+s-l*s;m1=2*l-m2;function v(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return m1+(m2-m1)*h/60;if(h<180)return m2;if(h<240)return m1+(m2-m1)*(240-h)/60;return m1;}
function vv(h){return Math.round(v(h)*255);}
return d3_rgb(vv(h+120),vv(h),vv(h-120));}
var π=Math.PI,ε=1e-6,d3_radians=π/180,d3_degrees=180/π;function d3_sgn(x){return x>0?1:x<0?-1:0;}
function d3_acos(x){return Math.acos(Math.max(-1,Math.min(1,x)));}
function d3_asin(x){return x>1?π/2:x<-1?-π/2:Math.asin(x);}
function d3_sinh(x){return(Math.exp(x)-Math.exp(-x))/2;}
function d3_cosh(x){return(Math.exp(x)+Math.exp(-x))/2;}
function d3_haversin(x){return(x=Math.sin(x/2))*x;}
d3.hcl=function(h,c,l){return arguments.length===1?h instanceof d3_Hcl?d3_hcl(h.h,h.c,h.l):h instanceof d3_Lab?d3_lab_hcl(h.l,h.a,h.b):d3_lab_hcl((h=d3_rgb_lab((h=d3.rgb(h)).r,h.g,h.b)).l,h.a,h.b):d3_hcl(+h,+c,+l);};function d3_hcl(h,c,l){return new d3_Hcl(h,c,l);}
function d3_Hcl(h,c,l){this.h=h;this.c=c;this.l=l;}
var d3_hclPrototype=d3_Hcl.prototype=new d3_Color();d3_hclPrototype.brighter=function(k){return d3_hcl(this.h,this.c,Math.min(100,this.l+d3_lab_K*(arguments.length?k:1)));};d3_hclPrototype.darker=function(k){return d3_hcl(this.h,this.c,Math.max(0,this.l-d3_lab_K*(arguments.length?k:1)));};d3_hclPrototype.rgb=function(){return d3_hcl_lab(this.h,this.c,this.l).rgb();};function d3_hcl_lab(h,c,l){if(isNaN(h))h=0;if(isNaN(c))c=0;return d3_lab(l,Math.cos(h*=d3_radians)*c,Math.sin(h)*c);}
d3.lab=function(l,a,b){return arguments.length===1?l instanceof d3_Lab?d3_lab(l.l,l.a,l.b):l instanceof d3_Hcl?d3_hcl_lab(l.l,l.c,l.h):d3_rgb_lab((l=d3.rgb(l)).r,l.g,l.b):d3_lab(+l,+a,+b);};function d3_lab(l,a,b){return new d3_Lab(l,a,b);}
function d3_Lab(l,a,b){this.l=l;this.a=a;this.b=b;}
var d3_lab_K=18;var d3_lab_X=.95047,d3_lab_Y=1,d3_lab_Z=1.08883;var d3_labPrototype=d3_Lab.prototype=new d3_Color();d3_labPrototype.brighter=function(k){return d3_lab(Math.min(100,this.l+d3_lab_K*(arguments.length?k:1)),this.a,this.b);};d3_labPrototype.darker=function(k){return d3_lab(Math.max(0,this.l-d3_lab_K*(arguments.length?k:1)),this.a,this.b);};d3_labPrototype.rgb=function(){return d3_lab_rgb(this.l,this.a,this.b);};function d3_lab_rgb(l,a,b){var y=(l+16)/116,x=y+a/500,z=y-b/200;x=d3_lab_xyz(x)*d3_lab_X;y=d3_lab_xyz(y)*d3_lab_Y;z=d3_lab_xyz(z)*d3_lab_Z;return d3_rgb(d3_xyz_rgb(3.2404542*x-1.5371385*y-.4985314*z),d3_xyz_rgb(-.969266*x+1.8760108*y+.041556*z),d3_xyz_rgb(.0556434*x-.2040259*y+1.0572252*z));}
function d3_lab_hcl(l,a,b){return l>0?d3_hcl(Math.atan2(b,a)*d3_degrees,Math.sqrt(a*a+b*b),l):d3_hcl(NaN,NaN,l);}
function d3_lab_xyz(x){return x>.206893034?x*x*x:(x-4/29)/7.787037;}
function d3_xyz_lab(x){return x>.008856?Math.pow(x,1/3):7.787037*x+4/29;}
function d3_xyz_rgb(r){return Math.round(255*(r<=.00304?12.92*r:1.055*Math.pow(r,1/2.4)-.055));}
d3.rgb=function(r,g,b){return arguments.length===1?r instanceof d3_Rgb?d3_rgb(r.r,r.g,r.b):d3_rgb_parse(""+r,d3_rgb,d3_hsl_rgb):d3_rgb(~~r,~~g,~~b);};function d3_rgb(r,g,b){return new d3_Rgb(r,g,b);}
function d3_Rgb(r,g,b){this.r=r;this.g=g;this.b=b;}
var d3_rgbPrototype=d3_Rgb.prototype=new d3_Color();d3_rgbPrototype.brighter=function(k){k=Math.pow(.7,arguments.length?k:1);var r=this.r,g=this.g,b=this.b,i=30;if(!r&&!g&&!b)return d3_rgb(i,i,i);if(r&&r<i)r=i;if(g&&g<i)g=i;if(b&&b<i)b=i;return d3_rgb(Math.min(255,Math.floor(r/k)),Math.min(255,Math.floor(g/k)),Math.min(255,Math.floor(b/k)));};d3_rgbPrototype.darker=function(k){k=Math.pow(.7,arguments.length?k:1);return d3_rgb(Math.floor(k*this.r),Math.floor(k*this.g),Math.floor(k*this.b));};d3_rgbPrototype.hsl=function(){return d3_rgb_hsl(this.r,this.g,this.b);};d3_rgbPrototype.toString=function(){return"#"+d3_rgb_hex(this.r)+d3_rgb_hex(this.g)+d3_rgb_hex(this.b);};function d3_rgb_hex(v){return v<16?"0"+Math.max(0,v).toString(16):Math.min(255,v).toString(16);}
function d3_rgb_parse(format,rgb,hsl){var r=0,g=0,b=0,m1,m2,name;m1=/([a-z]+)\((.*)\)/i.exec(format);if(m1){m2=m1[2].split(",");switch(m1[1]){case"hsl":{return hsl(parseFloat(m2[0]),parseFloat(m2[1])/100,parseFloat(m2[2])/100);}
case"rgb":{return rgb(d3_rgb_parseNumber(m2[0]),d3_rgb_parseNumber(m2[1]),d3_rgb_parseNumber(m2[2]));}}}
if(name=d3_rgb_names.get(format))return rgb(name.r,name.g,name.b);if(format!=null&&format.charAt(0)==="#"){if(format.length===4){r=format.charAt(1);r+=r;g=format.charAt(2);g+=g;b=format.charAt(3);b+=b;}else if(format.length===7){r=format.substring(1,3);g=format.substring(3,5);b=format.substring(5,7);}
r=parseInt(r,16);g=parseInt(g,16);b=parseInt(b,16);}
return rgb(r,g,b);}
function d3_rgb_hsl(r,g,b){var min=Math.min(r/=255,g/=255,b/=255),max=Math.max(r,g,b),d=max-min,h,s,l=(max+min)/2;if(d){s=l<.5?d/(max+min):d/(2-max-min);if(r==max)h=(g-b)/d+(g<b?6:0);else if(g==max)h=(b-r)/d+2;else h=(r-g)/d+4;h*=60;}else{h=NaN;s=l>0&&l<1?0:h;}
return d3_hsl(h,s,l);}
function d3_rgb_lab(r,g,b){r=d3_rgb_xyz(r);g=d3_rgb_xyz(g);b=d3_rgb_xyz(b);var x=d3_xyz_lab((.4124564*r+.3575761*g+.1804375*b)/d3_lab_X),y=d3_xyz_lab((.2126729*r+.7151522*g+.072175*b)/d3_lab_Y),z=d3_xyz_lab((.0193339*r+.119192*g+.9503041*b)/d3_lab_Z);return d3_lab(116*y-16,500*(x-y),200*(y-z));}
function d3_rgb_xyz(r){return(r/=255)<=.04045?r/12.92:Math.pow((r+.055)/1.055,2.4);}
function d3_rgb_parseNumber(c){var f=parseFloat(c);return c.charAt(c.length-1)==="%"?Math.round(f*2.55):f;}
var d3_rgb_names=d3.map({aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"});d3_rgb_names.forEach(function(key,value){d3_rgb_names.set(key,d3_rgb_parse(value,d3_rgb,d3_hsl_rgb));});function d3_functor(v){return typeof v==="function"?v:function(){return v;};}
d3.functor=d3_functor;function d3_identity(d){return d;}
d3.xhr=function(url,mimeType,callback){var xhr={},dispatch=d3.dispatch("progress","load","error"),headers={},response=d3_identity,request=new(d3_window.XDomainRequest&&/^(http(s)?:)?\/\//.test(url)?XDomainRequest:XMLHttpRequest)();"onload"in request?request.onload=request.onerror=respond:request.onreadystatechange=function(){request.readyState>3&&respond();};function respond(){var s=request.status;!s&&request.responseText||s>=200&&s<300||s===304?dispatch.load.call(xhr,response.call(xhr,request)):dispatch.error.call(xhr,request);}
request.onprogress=function(event){var o=d3.event;d3.event=event;try{dispatch.progress.call(xhr,request);}finally{d3.event=o;}};xhr.header=function(name,value){name=(name+"").toLowerCase();if(arguments.length<2)return headers[name];if(value==null)delete headers[name];else headers[name]=value+"";return xhr;};xhr.mimeType=function(value){if(!arguments.length)return mimeType;mimeType=value==null?null:value+"";return xhr;};xhr.response=function(value){response=value;return xhr;};["get","post"].forEach(function(method){xhr[method]=function(){return xhr.send.apply(xhr,[method].concat(d3_array(arguments)));};});xhr.send=function(method,data,callback){if(arguments.length===2&&typeof data==="function")callback=data,data=null;request.open(method,url,true);if(mimeType!=null&&!("accept"in headers))headers["accept"]=mimeType+",*/*";if(request.setRequestHeader)for(var name in headers)request.setRequestHeader(name,headers[name]);if(mimeType!=null&&request.overrideMimeType)request.overrideMimeType(mimeType);if(callback!=null)xhr.on("error",callback).on("load",function(request){callback(null,request);});request.send(data==null?null:data);return xhr;};xhr.abort=function(){request.abort();return xhr;};d3.rebind(xhr,dispatch,"on");if(arguments.length===2&&typeof mimeType==="function")callback=mimeType,mimeType=null;return callback==null?xhr:xhr.get(d3_xhr_fixCallback(callback));};function d3_xhr_fixCallback(callback){return callback.length===1?function(error,request){callback(error==null?request:null);}:callback;}
function d3_dsv(delimiter,mimeType){var reFormat=new RegExp('["'+delimiter+"\n]"),delimiterCode=delimiter.charCodeAt(0);function dsv(url,row,callback){if(arguments.length<3)callback=row,row=null;var xhr=d3.xhr(url,mimeType,callback);xhr.row=function(_){return arguments.length?xhr.response((row=_)==null?response:typedResponse(_)):row;};return xhr.row(row);}
function response(request){return dsv.parse(request.responseText);}
function typedResponse(f){return function(request){return dsv.parse(request.responseText,f);};}
dsv.parse=function(text,f){var o;return dsv.parseRows(text,function(row,i){if(o)return o(row,i-1);var a=new Function("d","return {"+row.map(function(name,i){return JSON.stringify(name)+": d["+i+"]";}).join(",")+"}");o=f?function(row,i){return f(a(row),i);}:a;});};dsv.parseRows=function(text,f){var EOL={},EOF={},rows=[],N=text.length,I=0,n=0,t,eol;function token(){if(I>=N)return EOF;if(eol)return eol=false,EOL;var j=I;if(text.charCodeAt(j)===34){var i=j;while(i++<N){if(text.charCodeAt(i)===34){if(text.charCodeAt(i+1)!==34)break;++i;}}
I=i+2;var c=text.charCodeAt(i+1);if(c===13){eol=true;if(text.charCodeAt(i+2)===10)++I;}else if(c===10){eol=true;}
return text.substring(j+1,i).replace(/""/g,'"');}
while(I<N){var c=text.charCodeAt(I++),k=1;if(c===10)eol=true;else if(c===13){eol=true;if(text.charCodeAt(I)===10)++I,++k;}else if(c!==delimiterCode)continue;return text.substring(j,I-k);}
return text.substring(j);}
while((t=token())!==EOF){var a=[];while(t!==EOL&&t!==EOF){a.push(t);t=token();}
if(f&&!(a=f(a,n++)))continue;rows.push(a);}
return rows;};dsv.format=function(rows){if(Array.isArray(rows[0]))return dsv.formatRows(rows);var fieldSet=new d3_Set(),fields=[];rows.forEach(function(row){for(var field in row){if(!fieldSet.has(field)){fields.push(fieldSet.add(field));}}});return[fields.map(formatValue).join(delimiter)].concat(rows.map(function(row){return fields.map(function(field){return formatValue(row[field]);}).join(delimiter);})).join("\n");};dsv.formatRows=function(rows){return rows.map(formatRow).join("\n");};function formatRow(row){return row.map(formatValue).join(delimiter);}
function formatValue(text){return reFormat.test(text)?'"'+text.replace(/\"/g,'""')+'"':text;}
return dsv;}
d3.csv=d3_dsv(",","text/csv");d3.tsv=d3_dsv("	","text/tab-separated-values");var d3_timer_id=0,d3_timer_byId={},d3_timer_queue=null,d3_timer_interval,d3_timer_timeout;d3.timer=function(callback,delay,then){if(arguments.length<3){if(arguments.length<2)delay=0;else if(!isFinite(delay))return;then=Date.now();}
var timer=d3_timer_byId[callback.id];if(timer&&timer.callback===callback){timer.then=then;timer.delay=delay;}else d3_timer_byId[callback.id=++d3_timer_id]=d3_timer_queue={callback:callback,then:then,delay:delay,next:d3_timer_queue};if(!d3_timer_interval){d3_timer_timeout=clearTimeout(d3_timer_timeout);d3_timer_interval=1;d3_timer_frame(d3_timer_step);}};function d3_timer_step(){var elapsed,now=Date.now(),t1=d3_timer_queue;while(t1){elapsed=now-t1.then;if(elapsed>=t1.delay)t1.flush=t1.callback(elapsed);t1=t1.next;}
var delay=d3_timer_flush()-now;if(delay>24){if(isFinite(delay)){clearTimeout(d3_timer_timeout);d3_timer_timeout=setTimeout(d3_timer_step,delay);}
d3_timer_interval=0;}else{d3_timer_interval=1;d3_timer_frame(d3_timer_step);}}
d3.timer.flush=function(){var elapsed,now=Date.now(),t1=d3_timer_queue;while(t1){elapsed=now-t1.then;if(!t1.delay)t1.flush=t1.callback(elapsed);t1=t1.next;}
d3_timer_flush();};function d3_timer_flush(){var t0=null,t1=d3_timer_queue,then=Infinity;while(t1){if(t1.flush){delete d3_timer_byId[t1.callback.id];t1=t0?t0.next=t1.next:d3_timer_queue=t1.next;}else{then=Math.min(then,t1.then+t1.delay);t1=(t0=t1).next;}}
return then;}
var d3_timer_frame=d3_window.requestAnimationFrame||d3_window.webkitRequestAnimationFrame||d3_window.mozRequestAnimationFrame||d3_window.oRequestAnimationFrame||d3_window.msRequestAnimationFrame||function(callback){setTimeout(callback,17);};var d3_format_decimalPoint=".",d3_format_thousandsSeparator=",",d3_format_grouping=[3,3];var d3_formatPrefixes=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(d3_formatPrefix);d3.formatPrefix=function(value,precision){var i=0;if(value){if(value<0)value*=-1;if(precision)value=d3.round(value,d3_format_precision(value,precision));i=1+Math.floor(1e-12+Math.log(value)/Math.LN10);i=Math.max(-24,Math.min(24,Math.floor((i<=0?i+1:i-1)/3)*3));}
return d3_formatPrefixes[8+i/3];};function d3_formatPrefix(d,i){var k=Math.pow(10,Math.abs(8-i)*3);return{scale:i>8?function(d){return d/k;}:function(d){return d*k;},symbol:d};}
d3.round=function(x,n){return n?Math.round(x*(n=Math.pow(10,n)))/n:Math.round(x);};d3.format=function(specifier){var match=d3_format_re.exec(specifier),fill=match[1]||" ",align=match[2]||">",sign=match[3]||"",basePrefix=match[4]||"",zfill=match[5],width=+match[6],comma=match[7],precision=match[8],type=match[9],scale=1,suffix="",integer=false;if(precision)precision=+precision.substring(1);if(zfill||fill==="0"&&align==="="){zfill=fill="0";align="=";if(comma)width-=Math.floor((width-1)/4);}
switch(type){case"n":comma=true;type="g";break;case"%":scale=100;suffix="%";type="f";break;case"p":scale=100;suffix="%";type="r";break;case"b":case"o":case"x":case"X":if(basePrefix)basePrefix="0"+type.toLowerCase();case"c":case"d":integer=true;precision=0;break;case"s":scale=-1;type="r";break;}
if(basePrefix==="#")basePrefix="";if(type=="r"&&!precision)type="g";if(precision!=null){if(type=="g")precision=Math.max(1,Math.min(21,precision));else if(type=="e"||type=="f")precision=Math.max(0,Math.min(20,precision));}
type=d3_format_types.get(type)||d3_format_typeDefault;var zcomma=zfill&&comma;return function(value){if(integer&&value%1)return"";var negative=value<0||value===0&&1/value<0?(value=-value,"-"):sign;if(scale<0){var prefix=d3.formatPrefix(value,precision);value=prefix.scale(value);suffix=prefix.symbol;}else{value*=scale;}
value=type(value,precision);if(!zfill&&comma)value=d3_format_group(value);var length=basePrefix.length+value.length+(zcomma?0:negative.length),padding=length<width?new Array(length=width-length+1).join(fill):"";if(zcomma)value=d3_format_group(padding+value);if(d3_format_decimalPoint)value.replace(".",d3_format_decimalPoint);negative+=basePrefix;return(align==="<"?negative+value+padding:align===">"?padding+negative+value:align==="^"?padding.substring(0,length>>=1)+negative+value+padding.substring(length):negative+(zcomma?value:padding+value))+suffix;};};var d3_format_re=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;var d3_format_types=d3.map({b:function(x){return x.toString(2);},c:function(x){return String.fromCharCode(x);},o:function(x){return x.toString(8);},x:function(x){return x.toString(16);},X:function(x){return x.toString(16).toUpperCase();},g:function(x,p){return x.toPrecision(p);},e:function(x,p){return x.toExponential(p);},f:function(x,p){return x.toFixed(p);},r:function(x,p){return(x=d3.round(x,d3_format_precision(x,p))).toFixed(Math.max(0,Math.min(20,d3_format_precision(x*(1+1e-15),p))));}});function d3_format_precision(x,p){return p-(x?Math.ceil(Math.log(x)/Math.LN10):1);}
function d3_format_typeDefault(x){return x+"";}
var d3_format_group=d3_identity;if(d3_format_grouping){var d3_format_groupingLength=d3_format_grouping.length;d3_format_group=function(value){var i=value.lastIndexOf("."),f=i>=0?"."+value.substring(i+1):(i=value.length,""),t=[],j=0,g=d3_format_grouping[0];while(i>0&&g>0){t.push(value.substring(i-=g,i+g));g=d3_format_grouping[j=(j+1)%d3_format_groupingLength];}
return t.reverse().join(d3_format_thousandsSeparator||"")+f;};}
d3.geo={};d3.geo.stream=function(object,listener){if(object&&d3_geo_streamObjectType.hasOwnProperty(object.type)){d3_geo_streamObjectType[object.type](object,listener);}else{d3_geo_streamGeometry(object,listener);}};function d3_geo_streamGeometry(geometry,listener){if(geometry&&d3_geo_streamGeometryType.hasOwnProperty(geometry.type)){d3_geo_streamGeometryType[geometry.type](geometry,listener);}}
var d3_geo_streamObjectType={Feature:function(feature,listener){d3_geo_streamGeometry(feature.geometry,listener);},FeatureCollection:function(object,listener){var features=object.features,i=-1,n=features.length;while(++i<n)d3_geo_streamGeometry(features[i].geometry,listener);}};var d3_geo_streamGeometryType={Sphere:function(object,listener){listener.sphere();},Point:function(object,listener){var coordinate=object.coordinates;listener.point(coordinate[0],coordinate[1]);},MultiPoint:function(object,listener){var coordinates=object.coordinates,i=-1,n=coordinates.length,coordinate;while(++i<n)coordinate=coordinates[i],listener.point(coordinate[0],coordinate[1]);},LineString:function(object,listener){d3_geo_streamLine(object.coordinates,listener,0);},MultiLineString:function(object,listener){var coordinates=object.coordinates,i=-1,n=coordinates.length;while(++i<n)d3_geo_streamLine(coordinates[i],listener,0);},Polygon:function(object,listener){d3_geo_streamPolygon(object.coordinates,listener);},MultiPolygon:function(object,listener){var coordinates=object.coordinates,i=-1,n=coordinates.length;while(++i<n)d3_geo_streamPolygon(coordinates[i],listener);},GeometryCollection:function(object,listener){var geometries=object.geometries,i=-1,n=geometries.length;while(++i<n)d3_geo_streamGeometry(geometries[i],listener);}};function d3_geo_streamLine(coordinates,listener,closed){var i=-1,n=coordinates.length-closed,coordinate;listener.lineStart();while(++i<n)coordinate=coordinates[i],listener.point(coordinate[0],coordinate[1]);listener.lineEnd();}
function d3_geo_streamPolygon(coordinates,listener){var i=-1,n=coordinates.length;listener.polygonStart();while(++i<n)d3_geo_streamLine(coordinates[i],listener,1);listener.polygonEnd();}
d3.geo.area=function(object){d3_geo_areaSum=0;d3.geo.stream(object,d3_geo_area);return d3_geo_areaSum;};var d3_geo_areaSum,d3_geo_areaRingU,d3_geo_areaRingV;var d3_geo_area={sphere:function(){d3_geo_areaSum+=4*π;},point:d3_noop,lineStart:d3_noop,lineEnd:d3_noop,polygonStart:function(){d3_geo_areaRingU=1,d3_geo_areaRingV=0;d3_geo_area.lineStart=d3_geo_areaRingStart;},polygonEnd:function(){var area=2*Math.atan2(d3_geo_areaRingV,d3_geo_areaRingU);d3_geo_areaSum+=area<0?4*π+area:area;d3_geo_area.lineStart=d3_geo_area.lineEnd=d3_geo_area.point=d3_noop;}};function d3_geo_areaRingStart(){var λ00,φ00,λ0,cosφ0,sinφ0;d3_geo_area.point=function(λ,φ){d3_geo_area.point=nextPoint;λ0=(λ00=λ)*d3_radians,cosφ0=Math.cos(φ=(φ00=φ)*d3_radians/2+π/4),sinφ0=Math.sin(φ);};function nextPoint(λ,φ){λ*=d3_radians;φ=φ*d3_radians/2+π/4;var dλ=λ-λ0,cosφ=Math.cos(φ),sinφ=Math.sin(φ),k=sinφ0*sinφ,u0=d3_geo_areaRingU,v0=d3_geo_areaRingV,u=cosφ0*cosφ+k*Math.cos(dλ),v=k*Math.sin(dλ);d3_geo_areaRingU=u0*u-v0*v;d3_geo_areaRingV=v0*u+u0*v;λ0=λ,cosφ0=cosφ,sinφ0=sinφ;}
d3_geo_area.lineEnd=function(){nextPoint(λ00,φ00);};}
d3.geo.bounds=d3_geo_bounds(d3_identity);function d3_geo_bounds(projectStream){var x0,y0,x1,y1;var bound={point:boundPoint,lineStart:d3_noop,lineEnd:d3_noop,polygonStart:function(){bound.lineEnd=boundPolygonLineEnd;},polygonEnd:function(){bound.point=boundPoint;}};function boundPoint(x,y){if(x<x0)x0=x;if(x>x1)x1=x;if(y<y0)y0=y;if(y>y1)y1=y;}
function boundPolygonLineEnd(){bound.point=bound.lineEnd=d3_noop;}
return function(feature){y1=x1=-(x0=y0=Infinity);d3.geo.stream(feature,projectStream(bound));return[[x0,y0],[x1,y1]];};}
d3.geo.centroid=function(object){d3_geo_centroidDimension=d3_geo_centroidW=d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;d3.geo.stream(object,d3_geo_centroid);var m;if(d3_geo_centroidW&&Math.abs(m=Math.sqrt(d3_geo_centroidX*d3_geo_centroidX+d3_geo_centroidY*d3_geo_centroidY+d3_geo_centroidZ*d3_geo_centroidZ))>ε){return[Math.atan2(d3_geo_centroidY,d3_geo_centroidX)*d3_degrees,Math.asin(Math.max(-1,Math.min(1,d3_geo_centroidZ/m)))*d3_degrees];}};var d3_geo_centroidDimension,d3_geo_centroidW,d3_geo_centroidX,d3_geo_centroidY,d3_geo_centroidZ;var d3_geo_centroid={sphere:function(){if(d3_geo_centroidDimension<2){d3_geo_centroidDimension=2;d3_geo_centroidW=d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;}},point:d3_geo_centroidPoint,lineStart:d3_geo_centroidLineStart,lineEnd:d3_geo_centroidLineEnd,polygonStart:function(){if(d3_geo_centroidDimension<2){d3_geo_centroidDimension=2;d3_geo_centroidW=d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;}
d3_geo_centroid.lineStart=d3_geo_centroidRingStart;},polygonEnd:function(){d3_geo_centroid.lineStart=d3_geo_centroidLineStart;}};function d3_geo_centroidPoint(λ,φ){if(d3_geo_centroidDimension)return;++d3_geo_centroidW;λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians);d3_geo_centroidX+=(cosφ*Math.cos(λ)-d3_geo_centroidX)/d3_geo_centroidW;d3_geo_centroidY+=(cosφ*Math.sin(λ)-d3_geo_centroidY)/d3_geo_centroidW;d3_geo_centroidZ+=(Math.sin(φ)-d3_geo_centroidZ)/d3_geo_centroidW;}
function d3_geo_centroidRingStart(){var λ00,φ00;d3_geo_centroidDimension=1;d3_geo_centroidLineStart();d3_geo_centroidDimension=2;var linePoint=d3_geo_centroid.point;d3_geo_centroid.point=function(λ,φ){linePoint(λ00=λ,φ00=φ);};d3_geo_centroid.lineEnd=function(){d3_geo_centroid.point(λ00,φ00);d3_geo_centroidLineEnd();d3_geo_centroid.lineEnd=d3_geo_centroidLineEnd;};}
function d3_geo_centroidLineStart(){var x0,y0,z0;if(d3_geo_centroidDimension>1)return;if(d3_geo_centroidDimension<1){d3_geo_centroidDimension=1;d3_geo_centroidW=d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;}
d3_geo_centroid.point=function(λ,φ){λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians);x0=cosφ*Math.cos(λ);y0=cosφ*Math.sin(λ);z0=Math.sin(φ);d3_geo_centroid.point=nextPoint;};function nextPoint(λ,φ){λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians),x=cosφ*Math.cos(λ),y=cosφ*Math.sin(λ),z=Math.sin(φ),w=Math.atan2(Math.sqrt((w=y0*z-z0*y)*w+(w=z0*x-x0*z)*w+(w=x0*y-y0*x)*w),x0*x+y0*y+z0*z);d3_geo_centroidW+=w;d3_geo_centroidX+=w*(x0+(x0=x));d3_geo_centroidY+=w*(y0+(y0=y));d3_geo_centroidZ+=w*(z0+(z0=z));}}
function d3_geo_centroidLineEnd(){d3_geo_centroid.point=d3_geo_centroidPoint;}
function d3_geo_cartesian(spherical){var λ=spherical[0],φ=spherical[1],cosφ=Math.cos(φ);return[cosφ*Math.cos(λ),cosφ*Math.sin(λ),Math.sin(φ)];}
function d3_geo_cartesianDot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2];}
function d3_geo_cartesianCross(a,b){return[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];}
function d3_geo_cartesianAdd(a,b){a[0]+=b[0];a[1]+=b[1];a[2]+=b[2];}
function d3_geo_cartesianScale(vector,k){return[vector[0]*k,vector[1]*k,vector[2]*k];}
function d3_geo_cartesianNormalize(d){var l=Math.sqrt(d[0]*d[0]+d[1]*d[1]+d[2]*d[2]);d[0]/=l;d[1]/=l;d[2]/=l;}
function d3_true(){return true;}
function d3_geo_spherical(cartesian){return[Math.atan2(cartesian[1],cartesian[0]),Math.asin(Math.max(-1,Math.min(1,cartesian[2])))];}
function d3_geo_sphericalEqual(a,b){return Math.abs(a[0]-b[0])<ε&&Math.abs(a[1]-b[1])<ε;}
function d3_geo_clipPolygon(segments,compare,inside,interpolate,listener){var subject=[],clip=[];segments.forEach(function(segment){if((n=segment.length-1)<=0)return;var n,p0=segment[0],p1=segment[n];if(d3_geo_sphericalEqual(p0,p1)){listener.lineStart();for(var i=0;i<n;++i)listener.point((p0=segment[i])[0],p0[1]);listener.lineEnd();return;}
var a={point:p0,points:segment,other:null,visited:false,entry:true,subject:true},b={point:p0,points:[p0],other:a,visited:false,entry:false,subject:false};a.other=b;subject.push(a);clip.push(b);a={point:p1,points:[p1],other:null,visited:false,entry:false,subject:true};b={point:p1,points:[p1],other:a,visited:false,entry:true,subject:false};a.other=b;subject.push(a);clip.push(b);});clip.sort(compare);d3_geo_clipPolygonLinkCircular(subject);d3_geo_clipPolygonLinkCircular(clip);if(!subject.length)return;if(inside)for(var i=1,e=!inside(clip[0].point),n=clip.length;i<n;++i){clip[i].entry=e=!e;}
var start=subject[0],current,points,point;while(1){current=start;while(current.visited)if((current=current.next)===start)return;points=current.points;listener.lineStart();do{current.visited=current.other.visited=true;if(current.entry){if(current.subject){for(var i=0;i<points.length;i++)listener.point((point=points[i])[0],point[1]);}else{interpolate(current.point,current.next.point,1,listener);}
current=current.next;}else{if(current.subject){points=current.prev.points;for(var i=points.length;--i>=0;)listener.point((point=points[i])[0],point[1]);}else{interpolate(current.point,current.prev.point,-1,listener);}
current=current.prev;}
current=current.other;points=current.points;}while(!current.visited);listener.lineEnd();}}
function d3_geo_clipPolygonLinkCircular(array){if(!(n=array.length))return;var n,i=0,a=array[0],b;while(++i<n){a.next=b=array[i];b.prev=a;a=b;}
a.next=b=array[0];b.prev=a;}
function d3_geo_clip(pointVisible,clipLine,interpolate){return function(listener){var line=clipLine(listener);var clip={point:point,lineStart:lineStart,lineEnd:lineEnd,polygonStart:function(){clip.point=pointRing;clip.lineStart=ringStart;clip.lineEnd=ringEnd;invisible=false;invisibleArea=visibleArea=0;segments=[];listener.polygonStart();},polygonEnd:function(){clip.point=point;clip.lineStart=lineStart;clip.lineEnd=lineEnd;segments=d3.merge(segments);if(segments.length){d3_geo_clipPolygon(segments,d3_geo_clipSort,null,interpolate,listener);}else if(visibleArea<-ε||invisible&&invisibleArea<-ε){listener.lineStart();interpolate(null,null,1,listener);listener.lineEnd();}
listener.polygonEnd();segments=null;},sphere:function(){listener.polygonStart();listener.lineStart();interpolate(null,null,1,listener);listener.lineEnd();listener.polygonEnd();}};function point(λ,φ){if(pointVisible(λ,φ))listener.point(λ,φ);}
function pointLine(λ,φ){line.point(λ,φ);}
function lineStart(){clip.point=pointLine;line.lineStart();}
function lineEnd(){clip.point=point;line.lineEnd();}
var segments,visibleArea,invisibleArea,invisible;var buffer=d3_geo_clipBufferListener(),ringListener=clipLine(buffer),ring;function pointRing(λ,φ){ringListener.point(λ,φ);ring.push([λ,φ]);}
function ringStart(){ringListener.lineStart();ring=[];}
function ringEnd(){pointRing(ring[0][0],ring[0][1]);ringListener.lineEnd();var clean=ringListener.clean(),ringSegments=buffer.buffer(),segment,n=ringSegments.length;if(!n){invisible=true;invisibleArea+=d3_geo_clipAreaRing(ring,-1);ring=null;return;}
ring=null;if(clean&1){segment=ringSegments[0];visibleArea+=d3_geo_clipAreaRing(segment,1);var n=segment.length-1,i=-1,point;listener.lineStart();while(++i<n)listener.point((point=segment[i])[0],point[1]);listener.lineEnd();return;}
if(n>1&&clean&2)ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));}
return clip;};}
function d3_geo_clipSegmentLength1(segment){return segment.length>1;}
function d3_geo_clipBufferListener(){var lines=[],line;return{lineStart:function(){lines.push(line=[]);},point:function(λ,φ){line.push([λ,φ]);},lineEnd:d3_noop,buffer:function(){var buffer=lines;lines=[];line=null;return buffer;},rejoin:function(){if(lines.length>1)lines.push(lines.pop().concat(lines.shift()));}};}
function d3_geo_clipAreaRing(ring,invisible){if(!(n=ring.length))return 0;var n,i=0,area=0,p=ring[0],λ=p[0],φ=p[1],cosφ=Math.cos(φ),x0=Math.atan2(invisible*Math.sin(λ)*cosφ,Math.sin(φ)),y0=1-invisible*Math.cos(λ)*cosφ,x1=x0,x,y;while(++i<n){p=ring[i];cosφ=Math.cos(φ=p[1]);x=Math.atan2(invisible*Math.sin(λ=p[0])*cosφ,Math.sin(φ));y=1-invisible*Math.cos(λ)*cosφ;if(Math.abs(y0-2)<ε&&Math.abs(y-2)<ε)continue;if(Math.abs(y)<ε||Math.abs(y0)<ε){}else if(Math.abs(Math.abs(x-x0)-π)<ε){if(y+y0>2)area+=4*(x-x0);}else if(Math.abs(y0-2)<ε)area+=4*(x-x1);else area+=((3*π+x-x0)%(2*π)-π)*(y0+y);x1=x0,x0=x,y0=y;}
return area;}
function d3_geo_clipSort(a,b){return((a=a.point)[0]<0?a[1]-π/2-ε:π/2-a[1])-((b=b.point)[0]<0?b[1]-π/2-ε:π/2-b[1]);}
var d3_geo_clipAntimeridian=d3_geo_clip(d3_true,d3_geo_clipAntimeridianLine,d3_geo_clipAntimeridianInterpolate);function d3_geo_clipAntimeridianLine(listener){var λ0=NaN,φ0=NaN,sλ0=NaN,clean;return{lineStart:function(){listener.lineStart();clean=1;},point:function(λ1,φ1){var sλ1=λ1>0?π:-π,dλ=Math.abs(λ1-λ0);if(Math.abs(dλ-π)<ε){listener.point(λ0,φ0=(φ0+φ1)/2>0?π/2:-π/2);listener.point(sλ0,φ0);listener.lineEnd();listener.lineStart();listener.point(sλ1,φ0);listener.point(λ1,φ0);clean=0;}else if(sλ0!==sλ1&&dλ>=π){if(Math.abs(λ0-sλ0)<ε)λ0-=sλ0*ε;if(Math.abs(λ1-sλ1)<ε)λ1-=sλ1*ε;φ0=d3_geo_clipAntimeridianIntersect(λ0,φ0,λ1,φ1);listener.point(sλ0,φ0);listener.lineEnd();listener.lineStart();listener.point(sλ1,φ0);clean=0;}
listener.point(λ0=λ1,φ0=φ1);sλ0=sλ1;},lineEnd:function(){listener.lineEnd();λ0=φ0=NaN;},clean:function(){return 2-clean;}};}
function d3_geo_clipAntimeridianIntersect(λ0,φ0,λ1,φ1){var cosφ0,cosφ1,sinλ0_λ1=Math.sin(λ0-λ1);return Math.abs(sinλ0_λ1)>ε?Math.atan((Math.sin(φ0)*(cosφ1=Math.cos(φ1))*Math.sin(λ1)-Math.sin(φ1)*(cosφ0=Math.cos(φ0))*Math.sin(λ0))/(cosφ0*cosφ1*sinλ0_λ1)):(φ0+φ1)/2;}
function d3_geo_clipAntimeridianInterpolate(from,to,direction,listener){var φ;if(from==null){φ=direction*π/2;listener.point(-π,φ);listener.point(0,φ);listener.point(π,φ);listener.point(π,0);listener.point(π,-φ);listener.point(0,-φ);listener.point(-π,-φ);listener.point(-π,0);listener.point(-π,φ);}else if(Math.abs(from[0]-to[0])>ε){var s=(from[0]<to[0]?1:-1)*π;φ=direction*s/2;listener.point(-s,φ);listener.point(0,φ);listener.point(s,φ);}else{listener.point(to[0],to[1]);}}
function d3_geo_clipCircle(radius){var cr=Math.cos(radius),smallRadius=cr>0,notHemisphere=Math.abs(cr)>ε,interpolate=d3_geo_circleInterpolate(radius,6*d3_radians);return d3_geo_clip(visible,clipLine,interpolate);function visible(λ,φ){return Math.cos(λ)*Math.cos(φ)>cr;}
function clipLine(listener){var point0,c0,v0,v00,clean;return{lineStart:function(){v00=v0=false;clean=1;},point:function(λ,φ){var point1=[λ,φ],point2,v=visible(λ,φ),c=smallRadius?v?0:code(λ,φ):v?code(λ+(λ<0?π:-π),φ):0;if(!point0&&(v00=v0=v))listener.lineStart();if(v!==v0){point2=intersect(point0,point1);if(d3_geo_sphericalEqual(point0,point2)||d3_geo_sphericalEqual(point1,point2)){point1[0]+=ε;point1[1]+=ε;v=visible(point1[0],point1[1]);}}
if(v!==v0){clean=0;if(v){listener.lineStart();point2=intersect(point1,point0);listener.point(point2[0],point2[1]);}else{point2=intersect(point0,point1);listener.point(point2[0],point2[1]);listener.lineEnd();}
point0=point2;}else if(notHemisphere&&point0&&smallRadius^v){var t;if(!(c&c0)&&(t=intersect(point1,point0,true))){clean=0;if(smallRadius){listener.lineStart();listener.point(t[0][0],t[0][1]);listener.point(t[1][0],t[1][1]);listener.lineEnd();}else{listener.point(t[1][0],t[1][1]);listener.lineEnd();listener.lineStart();listener.point(t[0][0],t[0][1]);}}}
if(v&&(!point0||!d3_geo_sphericalEqual(point0,point1))){listener.point(point1[0],point1[1]);}
point0=point1,v0=v,c0=c;},lineEnd:function(){if(v0)listener.lineEnd();point0=null;},clean:function(){return clean|(v00&&v0)<<1;}};}
function intersect(a,b,two){var pa=d3_geo_cartesian(a),pb=d3_geo_cartesian(b);var n1=[1,0,0],n2=d3_geo_cartesianCross(pa,pb),n2n2=d3_geo_cartesianDot(n2,n2),n1n2=n2[0],determinant=n2n2-n1n2*n1n2;if(!determinant)return!two&&a;var c1=cr*n2n2/determinant,c2=-cr*n1n2/determinant,n1xn2=d3_geo_cartesianCross(n1,n2),A=d3_geo_cartesianScale(n1,c1),B=d3_geo_cartesianScale(n2,c2);d3_geo_cartesianAdd(A,B);var u=n1xn2,w=d3_geo_cartesianDot(A,u),uu=d3_geo_cartesianDot(u,u),t2=w*w-uu*(d3_geo_cartesianDot(A,A)-1);if(t2<0)return;var t=Math.sqrt(t2),q=d3_geo_cartesianScale(u,(-w-t)/uu);d3_geo_cartesianAdd(q,A);q=d3_geo_spherical(q);if(!two)return q;var λ0=a[0],λ1=b[0],φ0=a[1],φ1=b[1],z;if(λ1<λ0)z=λ0,λ0=λ1,λ1=z;var δλ=λ1-λ0,polar=Math.abs(δλ-π)<ε,meridian=polar||δλ<ε;if(!polar&&φ1<φ0)z=φ0,φ0=φ1,φ1=z;if(meridian?polar?φ0+φ1>0^q[1]<(Math.abs(q[0]-λ0)<ε?φ0:φ1):φ0<=q[1]&&q[1]<=φ1:δλ>π^(λ0<=q[0]&&q[0]<=λ1)){var q1=d3_geo_cartesianScale(u,(-w+t)/uu);d3_geo_cartesianAdd(q1,A);return[q,d3_geo_spherical(q1)];}}
function code(λ,φ){var r=smallRadius?radius:π-radius,code=0;if(λ<-r)code|=1;else if(λ>r)code|=2;if(φ<-r)code|=4;else if(φ>r)code|=8;return code;}}
var d3_geo_clipViewMAX=1e9;function d3_geo_clipView(x0,y0,x1,y1){return function(listener){var listener_=listener,bufferListener=d3_geo_clipBufferListener(),segments,polygon,ring;var clip={point:point,lineStart:lineStart,lineEnd:lineEnd,polygonStart:function(){listener=bufferListener;segments=[];polygon=[];},polygonEnd:function(){listener=listener_;if((segments=d3.merge(segments)).length){listener.polygonStart();d3_geo_clipPolygon(segments,compare,inside,interpolate,listener);listener.polygonEnd();}else if(insidePolygon([x0,y0])){listener.polygonStart(),listener.lineStart();interpolate(null,null,1,listener);listener.lineEnd(),listener.polygonEnd();}
segments=polygon=ring=null;}};function inside(point){var a=corner(point,-1),i=insidePolygon([a===0||a===3?x0:x1,a>1?y1:y0]);return i;}
function insidePolygon(p){var wn=0,n=polygon.length,y=p[1];for(var i=0;i<n;++i){for(var j=1,v=polygon[i],m=v.length,a=v[0];j<m;++j){b=v[j];if(a[1]<=y){if(b[1]>y&&isLeft(a,b,p)>0)++wn;}else{if(b[1]<=y&&isLeft(a,b,p)<0)--wn;}
a=b;}}
return wn!==0;}
function isLeft(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]);}
function interpolate(from,to,direction,listener){var a=0,a1=0;if(from==null||(a=corner(from,direction))!==(a1=corner(to,direction))||comparePoints(from,to)<0^direction>0){do{listener.point(a===0||a===3?x0:x1,a>1?y1:y0);}while((a=(a+direction+4)%4)!==a1);}else{listener.point(to[0],to[1]);}}
function visible(x,y){return x0<=x&&x<=x1&&y0<=y&&y<=y1;}
function point(x,y){if(visible(x,y))listener.point(x,y);}
var x__,y__,v__,x_,y_,v_,first;function lineStart(){clip.point=linePoint;if(polygon)polygon.push(ring=[]);first=true;v_=false;x_=y_=NaN;}
function lineEnd(){if(segments){linePoint(x__,y__);if(v__&&v_)bufferListener.rejoin();segments.push(bufferListener.buffer());}
clip.point=point;if(v_)listener.lineEnd();}
function linePoint(x,y){x=Math.max(-d3_geo_clipViewMAX,Math.min(d3_geo_clipViewMAX,x));y=Math.max(-d3_geo_clipViewMAX,Math.min(d3_geo_clipViewMAX,y));var v=visible(x,y);if(polygon)ring.push([x,y]);if(first){x__=x,y__=y,v__=v;first=false;if(v){listener.lineStart();listener.point(x,y);}}else{if(v&&v_)listener.point(x,y);else{var a=[x_,y_],b=[x,y];if(clipLine(a,b)){if(!v_){listener.lineStart();listener.point(a[0],a[1]);}
listener.point(b[0],b[1]);if(!v)listener.lineEnd();}else{listener.lineStart();listener.point(x,y);}}}
x_=x,y_=y,v_=v;}
return clip;};function corner(p,direction){return Math.abs(p[0]-x0)<ε?direction>0?0:3:Math.abs(p[0]-x1)<ε?direction>0?2:1:Math.abs(p[1]-y0)<ε?direction>0?1:0:direction>0?3:2;}
function compare(a,b){return comparePoints(a.point,b.point);}
function comparePoints(a,b){var ca=corner(a,1),cb=corner(b,1);return ca!==cb?ca-cb:ca===0?b[1]-a[1]:ca===1?a[0]-b[0]:ca===2?a[1]-b[1]:b[0]-a[0];}
function clipLine(a,b){var dx=b[0]-a[0],dy=b[1]-a[1],t=[0,1];if(Math.abs(dx)<ε&&Math.abs(dy)<ε)return x0<=a[0]&&a[0]<=x1&&y0<=a[1]&&a[1]<=y1;if(d3_geo_clipViewT(x0-a[0],dx,t)&&d3_geo_clipViewT(a[0]-x1,-dx,t)&&d3_geo_clipViewT(y0-a[1],dy,t)&&d3_geo_clipViewT(a[1]-y1,-dy,t)){if(t[1]<1){b[0]=a[0]+t[1]*dx;b[1]=a[1]+t[1]*dy;}
if(t[0]>0){a[0]+=t[0]*dx;a[1]+=t[0]*dy;}
return true;}
return false;}}
function d3_geo_clipViewT(num,denominator,t){if(Math.abs(denominator)<ε)return num<=0;var u=num/denominator;if(denominator>0){if(u>t[1])return false;if(u>t[0])t[0]=u;}else{if(u<t[0])return false;if(u<t[1])t[1]=u;}
return true;}
function d3_geo_compose(a,b){function compose(x,y){return x=a(x,y),b(x[0],x[1]);}
if(a.invert&&b.invert)compose.invert=function(x,y){return x=b.invert(x,y),x&&a.invert(x[0],x[1]);};return compose;}
function d3_geo_resample(project){var δ2=.5,maxDepth=16;function resample(stream){var λ0,x0,y0,a0,b0,c0;var resample={point:point,lineStart:lineStart,lineEnd:lineEnd,polygonStart:function(){stream.polygonStart();resample.lineStart=polygonLineStart;},polygonEnd:function(){stream.polygonEnd();resample.lineStart=lineStart;}};function point(x,y){x=project(x,y);stream.point(x[0],x[1]);}
function lineStart(){x0=NaN;resample.point=linePoint;stream.lineStart();}
function linePoint(λ,φ){var c=d3_geo_cartesian([λ,φ]),p=project(λ,φ);resampleLineTo(x0,y0,λ0,a0,b0,c0,x0=p[0],y0=p[1],λ0=λ,a0=c[0],b0=c[1],c0=c[2],maxDepth,stream);stream.point(x0,y0);}
function lineEnd(){resample.point=point;stream.lineEnd();}
function polygonLineStart(){var λ00,φ00,x00,y00,a00,b00,c00;lineStart();resample.point=function(λ,φ){linePoint(λ00=λ,φ00=φ),x00=x0,y00=y0,a00=a0,b00=b0,c00=c0;resample.point=linePoint;};resample.lineEnd=function(){resampleLineTo(x0,y0,λ0,a0,b0,c0,x00,y00,λ00,a00,b00,c00,maxDepth,stream);resample.lineEnd=lineEnd;lineEnd();};}
return resample;}
function resampleLineTo(x0,y0,λ0,a0,b0,c0,x1,y1,λ1,a1,b1,c1,depth,stream){var dx=x1-x0,dy=y1-y0,d2=dx*dx+dy*dy;if(d2>4*δ2&&depth--){var a=a0+a1,b=b0+b1,c=c0+c1,m=Math.sqrt(a*a+b*b+c*c),φ2=Math.asin(c/=m),λ2=Math.abs(Math.abs(c)-1)<ε?(λ0+λ1)/2:Math.atan2(b,a),p=project(λ2,φ2),x2=p[0],y2=p[1],dx2=x2-x0,dy2=y2-y0,dz=dy*dx2-dx*dy2;if(dz*dz/d2>δ2||Math.abs((dx*dx2+dy*dy2)/d2-.5)>.3){resampleLineTo(x0,y0,λ0,a0,b0,c0,x2,y2,λ2,a/=m,b/=m,c,depth,stream);stream.point(x2,y2);resampleLineTo(x2,y2,λ2,a,b,c,x1,y1,λ1,a1,b1,c1,depth,stream);}}}
resample.precision=function(_){if(!arguments.length)return Math.sqrt(δ2);maxDepth=(δ2=_*_)>0&&16;return resample;};return resample;}
d3.geo.projection=d3_geo_projection;d3.geo.projectionMutator=d3_geo_projectionMutator;function d3_geo_projection(project){return d3_geo_projectionMutator(function(){return project;})();}
function d3_geo_projectionMutator(projectAt){var project,rotate,projectRotate,projectResample=d3_geo_resample(function(x,y){x=project(x,y);return[x[0]*k+δx,δy-x[1]*k];}),k=150,x=480,y=250,λ=0,φ=0,δλ=0,δφ=0,δγ=0,δx,δy,preclip=d3_geo_clipAntimeridian,postclip=d3_identity,clipAngle=null,clipExtent=null;function projection(point){point=projectRotate(point[0]*d3_radians,point[1]*d3_radians);return[point[0]*k+δx,δy-point[1]*k];}
function invert(point){point=projectRotate.invert((point[0]-δx)/k,(δy-point[1])/k);return point&&[point[0]*d3_degrees,point[1]*d3_degrees];}
projection.stream=function(stream){return d3_geo_projectionRadiansRotate(rotate,preclip(projectResample(postclip(stream))));};projection.clipAngle=function(_){if(!arguments.length)return clipAngle;preclip=_==null?(clipAngle=_,d3_geo_clipAntimeridian):d3_geo_clipCircle((clipAngle=+_)*d3_radians);return projection;};projection.clipExtent=function(_){if(!arguments.length)return clipExtent;clipExtent=_;postclip=_==null?d3_identity:d3_geo_clipView(_[0][0],_[0][1],_[1][0],_[1][1]);return projection;};projection.scale=function(_){if(!arguments.length)return k;k=+_;return reset();};projection.translate=function(_){if(!arguments.length)return[x,y];x=+_[0];y=+_[1];return reset();};projection.center=function(_){if(!arguments.length)return[λ*d3_degrees,φ*d3_degrees];λ=_[0]%360*d3_radians;φ=_[1]%360*d3_radians;return reset();};projection.rotate=function(_){if(!arguments.length)return[δλ*d3_degrees,δφ*d3_degrees,δγ*d3_degrees];δλ=_[0]%360*d3_radians;δφ=_[1]%360*d3_radians;δγ=_.length>2?_[2]%360*d3_radians:0;return reset();};d3.rebind(projection,projectResample,"precision");function reset(){projectRotate=d3_geo_compose(rotate=d3_geo_rotation(δλ,δφ,δγ),project);var center=project(λ,φ);δx=x-center[0]*k;δy=y+center[1]*k;return projection;}
return function(){project=projectAt.apply(this,arguments);projection.invert=project.invert&&invert;return reset();};}
function d3_geo_projectionRadiansRotate(rotate,stream){return{point:function(x,y){y=rotate(x*d3_radians,y*d3_radians),x=y[0];stream.point(x>π?x-2*π:x<-π?x+2*π:x,y[1]);},sphere:function(){stream.sphere();},lineStart:function(){stream.lineStart();},lineEnd:function(){stream.lineEnd();},polygonStart:function(){stream.polygonStart();},polygonEnd:function(){stream.polygonEnd();}};}
function d3_geo_equirectangular(λ,φ){return[λ,φ];}
(d3.geo.equirectangular=function(){return d3_geo_projection(d3_geo_equirectangular);}).raw=d3_geo_equirectangular.invert=d3_geo_equirectangular;d3.geo.rotation=function(rotate){rotate=d3_geo_rotation(rotate[0]%360*d3_radians,rotate[1]*d3_radians,rotate.length>2?rotate[2]*d3_radians:0);function forward(coordinates){coordinates=rotate(coordinates[0]*d3_radians,coordinates[1]*d3_radians);return coordinates[0]*=d3_degrees,coordinates[1]*=d3_degrees,coordinates;}
forward.invert=function(coordinates){coordinates=rotate.invert(coordinates[0]*d3_radians,coordinates[1]*d3_radians);return coordinates[0]*=d3_degrees,coordinates[1]*=d3_degrees,coordinates;};return forward;};function d3_geo_rotation(δλ,δφ,δγ){return δλ?δφ||δγ?d3_geo_compose(d3_geo_rotationλ(δλ),d3_geo_rotationφγ(δφ,δγ)):d3_geo_rotationλ(δλ):δφ||δγ?d3_geo_rotationφγ(δφ,δγ):d3_geo_equirectangular;}
function d3_geo_forwardRotationλ(δλ){return function(λ,φ){return λ+=δλ,[λ>π?λ-2*π:λ<-π?λ+2*π:λ,φ];};}
function d3_geo_rotationλ(δλ){var rotation=d3_geo_forwardRotationλ(δλ);rotation.invert=d3_geo_forwardRotationλ(-δλ);return rotation;}
function d3_geo_rotationφγ(δφ,δγ){var cosδφ=Math.cos(δφ),sinδφ=Math.sin(δφ),cosδγ=Math.cos(δγ),sinδγ=Math.sin(δγ);function rotation(λ,φ){var cosφ=Math.cos(φ),x=Math.cos(λ)*cosφ,y=Math.sin(λ)*cosφ,z=Math.sin(φ),k=z*cosδφ+x*sinδφ;return[Math.atan2(y*cosδγ-k*sinδγ,x*cosδφ-z*sinδφ),Math.asin(Math.max(-1,Math.min(1,k*cosδγ+y*sinδγ)))];}
rotation.invert=function(λ,φ){var cosφ=Math.cos(φ),x=Math.cos(λ)*cosφ,y=Math.sin(λ)*cosφ,z=Math.sin(φ),k=z*cosδγ-y*sinδγ;return[Math.atan2(y*cosδγ+z*sinδγ,x*cosδφ+k*sinδφ),Math.asin(Math.max(-1,Math.min(1,k*cosδφ-x*sinδφ)))];};return rotation;}
d3.geo.circle=function(){var origin=[0,0],angle,precision=6,interpolate;function circle(){var center=typeof origin==="function"?origin.apply(this,arguments):origin,rotate=d3_geo_rotation(-center[0]*d3_radians,-center[1]*d3_radians,0).invert,ring=[];interpolate(null,null,1,{point:function(x,y){ring.push(x=rotate(x,y));x[0]*=d3_degrees,x[1]*=d3_degrees;}});return{type:"Polygon",coordinates:[ring]};}
circle.origin=function(x){if(!arguments.length)return origin;origin=x;return circle;};circle.angle=function(x){if(!arguments.length)return angle;interpolate=d3_geo_circleInterpolate((angle=+x)*d3_radians,precision*d3_radians);return circle;};circle.precision=function(_){if(!arguments.length)return precision;interpolate=d3_geo_circleInterpolate(angle*d3_radians,(precision=+_)*d3_radians);return circle;};return circle.angle(90);};function d3_geo_circleInterpolate(radius,precision){var cr=Math.cos(radius),sr=Math.sin(radius);return function(from,to,direction,listener){if(from!=null){from=d3_geo_circleAngle(cr,from);to=d3_geo_circleAngle(cr,to);if(direction>0?from<to:from>to)from+=direction*2*π;}else{from=radius+direction*2*π;to=radius;}
var point;for(var step=direction*precision,t=from;direction>0?t>to:t<to;t-=step){listener.point((point=d3_geo_spherical([cr,-sr*Math.cos(t),-sr*Math.sin(t)]))[0],point[1]);}};}
function d3_geo_circleAngle(cr,point){var a=d3_geo_cartesian(point);a[0]-=cr;d3_geo_cartesianNormalize(a);var angle=d3_acos(-a[1]);return((-a[2]<0?-angle:angle)+2*Math.PI-ε)%(2*Math.PI);}
d3.geo.distance=function(a,b){var Δλ=(b[0]-a[0])*d3_radians,φ0=a[1]*d3_radians,φ1=b[1]*d3_radians,sinΔλ=Math.sin(Δλ),cosΔλ=Math.cos(Δλ),sinφ0=Math.sin(φ0),cosφ0=Math.cos(φ0),sinφ1=Math.sin(φ1),cosφ1=Math.cos(φ1),t;return Math.atan2(Math.sqrt((t=cosφ1*sinΔλ)*t+(t=cosφ0*sinφ1-sinφ0*cosφ1*cosΔλ)*t),sinφ0*sinφ1+cosφ0*cosφ1*cosΔλ);};d3.geo.graticule=function(){var x1,x0,X1,X0,y1,y0,Y1,Y0,dx=10,dy=dx,DX=90,DY=360,x,y,X,Y,precision=2.5;function graticule(){return{type:"MultiLineString",coordinates:lines()};}
function lines(){return d3.range(Math.ceil(X0/DX)*DX,X1,DX).map(X).concat(d3.range(Math.ceil(Y0/DY)*DY,Y1,DY).map(Y)).concat(d3.range(Math.ceil(x0/dx)*dx,x1,dx).filter(function(x){return Math.abs(x%DX)>ε;}).map(x)).concat(d3.range(Math.ceil(y0/dy)*dy,y1,dy).filter(function(y){return Math.abs(y%DY)>ε;}).map(y));}
graticule.lines=function(){return lines().map(function(coordinates){return{type:"LineString",coordinates:coordinates};});};graticule.outline=function(){return{type:"Polygon",coordinates:[X(X0).concat(Y(Y1).slice(1),X(X1).reverse().slice(1),Y(Y0).reverse().slice(1))]};};graticule.extent=function(_){if(!arguments.length)return graticule.minorExtent();return graticule.majorExtent(_).minorExtent(_);};graticule.majorExtent=function(_){if(!arguments.length)return[[X0,Y0],[X1,Y1]];X0=+_[0][0],X1=+_[1][0];Y0=+_[0][1],Y1=+_[1][1];if(X0>X1)_=X0,X0=X1,X1=_;if(Y0>Y1)_=Y0,Y0=Y1,Y1=_;return graticule.precision(precision);};graticule.minorExtent=function(_){if(!arguments.length)return[[x0,y0],[x1,y1]];x0=+_[0][0],x1=+_[1][0];y0=+_[0][1],y1=+_[1][1];if(x0>x1)_=x0,x0=x1,x1=_;if(y0>y1)_=y0,y0=y1,y1=_;return graticule.precision(precision);};graticule.step=function(_){if(!arguments.length)return graticule.minorStep();return graticule.majorStep(_).minorStep(_);};graticule.majorStep=function(_){if(!arguments.length)return[DX,DY];DX=+_[0],DY=+_[1];return graticule;};graticule.minorStep=function(_){if(!arguments.length)return[dx,dy];dx=+_[0],dy=+_[1];return graticule;};graticule.precision=function(_){if(!arguments.length)return precision;precision=+_;x=d3_geo_graticuleX(y0,y1,90);y=d3_geo_graticuleY(x0,x1,precision);X=d3_geo_graticuleX(Y0,Y1,90);Y=d3_geo_graticuleY(X0,X1,precision);return graticule;};return graticule.majorExtent([[-180,-90+ε],[180,90-ε]]).minorExtent([[-180,-80-ε],[180,80+ε]]);};function d3_geo_graticuleX(y0,y1,dy){var y=d3.range(y0,y1-ε,dy).concat(y1);return function(x){return y.map(function(y){return[x,y];});};}
function d3_geo_graticuleY(x0,x1,dx){var x=d3.range(x0,x1-ε,dx).concat(x1);return function(y){return x.map(function(x){return[x,y];});};}
function d3_source(d){return d.source;}
function d3_target(d){return d.target;}
d3.geo.greatArc=function(){var source=d3_source,source_,target=d3_target,target_;function greatArc(){return{type:"LineString",coordinates:[source_||source.apply(this,arguments),target_||target.apply(this,arguments)]};}
greatArc.distance=function(){return d3.geo.distance(source_||source.apply(this,arguments),target_||target.apply(this,arguments));};greatArc.source=function(_){if(!arguments.length)return source;source=_,source_=typeof _==="function"?null:_;return greatArc;};greatArc.target=function(_){if(!arguments.length)return target;target=_,target_=typeof _==="function"?null:_;return greatArc;};greatArc.precision=function(){return arguments.length?greatArc:0;};return greatArc;};d3.geo.interpolate=function(source,target){return d3_geo_interpolate(source[0]*d3_radians,source[1]*d3_radians,target[0]*d3_radians,target[1]*d3_radians);};function d3_geo_interpolate(x0,y0,x1,y1){var cy0=Math.cos(y0),sy0=Math.sin(y0),cy1=Math.cos(y1),sy1=Math.sin(y1),kx0=cy0*Math.cos(x0),ky0=cy0*Math.sin(x0),kx1=cy1*Math.cos(x1),ky1=cy1*Math.sin(x1),d=2*Math.asin(Math.sqrt(d3_haversin(y1-y0)+cy0*cy1*d3_haversin(x1-x0))),k=1/Math.sin(d);var interpolate=d?function(t){var B=Math.sin(t*=d)*k,A=Math.sin(d-t)*k,x=A*kx0+B*kx1,y=A*ky0+B*ky1,z=A*sy0+B*sy1;return[Math.atan2(y,x)*d3_degrees,Math.atan2(z,Math.sqrt(x*x+y*y))*d3_degrees];}:function(){return[x0*d3_degrees,y0*d3_degrees];};interpolate.distance=d;return interpolate;}
d3.geo.length=function(object){d3_geo_lengthSum=0;d3.geo.stream(object,d3_geo_length);return d3_geo_lengthSum;};var d3_geo_lengthSum;var d3_geo_length={sphere:d3_noop,point:d3_noop,lineStart:d3_geo_lengthLineStart,lineEnd:d3_noop,polygonStart:d3_noop,polygonEnd:d3_noop};function d3_geo_lengthLineStart(){var λ0,sinφ0,cosφ0;d3_geo_length.point=function(λ,φ){λ0=λ*d3_radians,sinφ0=Math.sin(φ*=d3_radians),cosφ0=Math.cos(φ);d3_geo_length.point=nextPoint;};d3_geo_length.lineEnd=function(){d3_geo_length.point=d3_geo_length.lineEnd=d3_noop;};function nextPoint(λ,φ){var sinφ=Math.sin(φ*=d3_radians),cosφ=Math.cos(φ),t=Math.abs((λ*=d3_radians)-λ0),cosΔλ=Math.cos(t);d3_geo_lengthSum+=Math.atan2(Math.sqrt((t=cosφ*Math.sin(t))*t+(t=cosφ0*sinφ-sinφ0*cosφ*cosΔλ)*t),sinφ0*sinφ+cosφ0*cosφ*cosΔλ);λ0=λ,sinφ0=sinφ,cosφ0=cosφ;}}
function d3_geo_conic(projectAt){var φ0=0,φ1=π/3,m=d3_geo_projectionMutator(projectAt),p=m(φ0,φ1);p.parallels=function(_){if(!arguments.length)return[φ0/π*180,φ1/π*180];return m(φ0=_[0]*π/180,φ1=_[1]*π/180);};return p;}
function d3_geo_conicEqualArea(φ0,φ1){var sinφ0=Math.sin(φ0),n=(sinφ0+Math.sin(φ1))/2,C=1+sinφ0*(2*n-sinφ0),ρ0=Math.sqrt(C)/n;function forward(λ,φ){var ρ=Math.sqrt(C-2*n*Math.sin(φ))/n;return[ρ*Math.sin(λ*=n),ρ0-ρ*Math.cos(λ)];}
forward.invert=function(x,y){var ρ0_y=ρ0-y;return[Math.atan2(x,ρ0_y)/n,Math.asin((C-(x*x+ρ0_y*ρ0_y)*n*n)/(2*n))];};return forward;}
(d3.geo.conicEqualArea=function(){return d3_geo_conic(d3_geo_conicEqualArea);}).raw=d3_geo_conicEqualArea;d3.geo.albersUsa=function(){var lower48=d3.geo.conicEqualArea().rotate([98,0]).center([0,38]).parallels([29.5,45.5]);var alaska=d3.geo.conicEqualArea().rotate([160,0]).center([0,60]).parallels([55,65]);var hawaii=d3.geo.conicEqualArea().rotate([160,0]).center([0,20]).parallels([8,18]);var puertoRico=d3.geo.conicEqualArea().rotate([60,0]).center([0,10]).parallels([8,18]);var alaskaInvert,hawaiiInvert,puertoRicoInvert;function albersUsa(coordinates){return projection(coordinates)(coordinates);}
function projection(point){var lon=point[0],lat=point[1];return lat>50?alaska:lon<-140?hawaii:lat<21?puertoRico:lower48;}
albersUsa.invert=function(coordinates){return alaskaInvert(coordinates)||hawaiiInvert(coordinates)||puertoRicoInvert(coordinates)||lower48.invert(coordinates);};albersUsa.scale=function(x){if(!arguments.length)return lower48.scale();lower48.scale(x);alaska.scale(x*.6);hawaii.scale(x);puertoRico.scale(x*1.5);return albersUsa.translate(lower48.translate());};albersUsa.translate=function(x){if(!arguments.length)return lower48.translate();var dz=lower48.scale(),dx=x[0],dy=x[1];lower48.translate(x);alaska.translate([dx-.4*dz,dy+.17*dz]);hawaii.translate([dx-.19*dz,dy+.2*dz]);puertoRico.translate([dx+.58*dz,dy+.43*dz]);alaskaInvert=d3_geo_albersUsaInvert(alaska,[[-180,50],[-130,72]]);hawaiiInvert=d3_geo_albersUsaInvert(hawaii,[[-164,18],[-154,24]]);puertoRicoInvert=d3_geo_albersUsaInvert(puertoRico,[[-67.5,17.5],[-65,19]]);return albersUsa;};return albersUsa.scale(1e3);};function d3_geo_albersUsaInvert(projection,extent){var a=projection(extent[0]),b=projection([.5*(extent[0][0]+extent[1][0]),extent[0][1]]),c=projection([extent[1][0],extent[0][1]]),d=projection(extent[1]);var dya=b[1]-a[1],dxa=b[0]-a[0],dyb=c[1]-b[1],dxb=c[0]-b[0];var ma=dya/dxa,mb=dyb/dxb;var cx=.5*(ma*mb*(a[1]-c[1])+mb*(a[0]+b[0])-ma*(b[0]+c[0]))/(mb-ma),cy=(.5*(a[0]+b[0])-cx)/ma+.5*(a[1]+b[1]);var dx0=d[0]-cx,dy0=d[1]-cy,dx1=a[0]-cx,dy1=a[1]-cy,r0=dx0*dx0+dy0*dy0,r1=dx1*dx1+dy1*dy1;var a0=Math.atan2(dy0,dx0),a1=Math.atan2(dy1,dx1);return function(coordinates){var dx=coordinates[0]-cx,dy=coordinates[1]-cy,r=dx*dx+dy*dy,a=Math.atan2(dy,dx);if(r0<r&&r<r1&&a0<a&&a<a1)return projection.invert(coordinates);};}
var d3_geo_pathAreaSum,d3_geo_pathAreaPolygon,d3_geo_pathArea={point:d3_noop,lineStart:d3_noop,lineEnd:d3_noop,polygonStart:function(){d3_geo_pathAreaPolygon=0;d3_geo_pathArea.lineStart=d3_geo_pathAreaRingStart;},polygonEnd:function(){d3_geo_pathArea.lineStart=d3_geo_pathArea.lineEnd=d3_geo_pathArea.point=d3_noop;d3_geo_pathAreaSum+=Math.abs(d3_geo_pathAreaPolygon/2);}};function d3_geo_pathAreaRingStart(){var x00,y00,x0,y0;d3_geo_pathArea.point=function(x,y){d3_geo_pathArea.point=nextPoint;x00=x0=x,y00=y0=y;};function nextPoint(x,y){d3_geo_pathAreaPolygon+=y0*x-x0*y;x0=x,y0=y;}
d3_geo_pathArea.lineEnd=function(){nextPoint(x00,y00);};}
function d3_geo_pathBuffer(){var pointCircle=d3_geo_pathCircle(4.5),buffer=[];var stream={point:point,lineStart:function(){stream.point=pointLineStart;},lineEnd:lineEnd,polygonStart:function(){stream.lineEnd=lineEndPolygon;},polygonEnd:function(){stream.lineEnd=lineEnd;stream.point=point;},pointRadius:function(_){pointCircle=d3_geo_pathCircle(_);return stream;},result:function(){if(buffer.length){var result=buffer.join("");buffer=[];return result;}}};function point(x,y){buffer.push("M",x,",",y,pointCircle);}
function pointLineStart(x,y){buffer.push("M",x,",",y);stream.point=pointLine;}
function pointLine(x,y){buffer.push("L",x,",",y);}
function lineEnd(){stream.point=point;}
function lineEndPolygon(){buffer.push("Z");}
return stream;}
var d3_geo_pathCentroid={point:d3_geo_pathCentroidPoint,lineStart:d3_geo_pathCentroidLineStart,lineEnd:d3_geo_pathCentroidLineEnd,polygonStart:function(){d3_geo_pathCentroid.lineStart=d3_geo_pathCentroidRingStart;},polygonEnd:function(){d3_geo_pathCentroid.point=d3_geo_pathCentroidPoint;d3_geo_pathCentroid.lineStart=d3_geo_pathCentroidLineStart;d3_geo_pathCentroid.lineEnd=d3_geo_pathCentroidLineEnd;}};function d3_geo_pathCentroidPoint(x,y){if(d3_geo_centroidDimension)return;d3_geo_centroidX+=x;d3_geo_centroidY+=y;++d3_geo_centroidZ;}
function d3_geo_pathCentroidLineStart(){var x0,y0;if(d3_geo_centroidDimension!==1){if(d3_geo_centroidDimension<1){d3_geo_centroidDimension=1;d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;}else return;}
d3_geo_pathCentroid.point=function(x,y){d3_geo_pathCentroid.point=nextPoint;x0=x,y0=y;};function nextPoint(x,y){var dx=x-x0,dy=y-y0,z=Math.sqrt(dx*dx+dy*dy);d3_geo_centroidX+=z*(x0+x)/2;d3_geo_centroidY+=z*(y0+y)/2;d3_geo_centroidZ+=z;x0=x,y0=y;}}
function d3_geo_pathCentroidLineEnd(){d3_geo_pathCentroid.point=d3_geo_pathCentroidPoint;}
function d3_geo_pathCentroidRingStart(){var x00,y00,x0,y0;if(d3_geo_centroidDimension<2){d3_geo_centroidDimension=2;d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;}
d3_geo_pathCentroid.point=function(x,y){d3_geo_pathCentroid.point=nextPoint;x00=x0=x,y00=y0=y;};function nextPoint(x,y){var z=y0*x-x0*y;d3_geo_centroidX+=z*(x0+x);d3_geo_centroidY+=z*(y0+y);d3_geo_centroidZ+=z*3;x0=x,y0=y;}
d3_geo_pathCentroid.lineEnd=function(){nextPoint(x00,y00);};}
function d3_geo_pathContext(context){var pointRadius=4.5;var stream={point:point,lineStart:function(){stream.point=pointLineStart;},lineEnd:lineEnd,polygonStart:function(){stream.lineEnd=lineEndPolygon;},polygonEnd:function(){stream.lineEnd=lineEnd;stream.point=point;},pointRadius:function(_){pointRadius=_;return stream;},result:d3_noop};function point(x,y){context.moveTo(x,y);context.arc(x,y,pointRadius,0,2*π);}
function pointLineStart(x,y){context.moveTo(x,y);stream.point=pointLine;}
function pointLine(x,y){context.lineTo(x,y);}
function lineEnd(){stream.point=point;}
function lineEndPolygon(){context.closePath();}
return stream;}
d3.geo.path=function(){var pointRadius=4.5,projection,context,projectStream,contextStream;function path(object){if(object)d3.geo.stream(object,projectStream(contextStream.pointRadius(typeof pointRadius==="function"?+pointRadius.apply(this,arguments):pointRadius)));return contextStream.result();}
path.area=function(object){d3_geo_pathAreaSum=0;d3.geo.stream(object,projectStream(d3_geo_pathArea));return d3_geo_pathAreaSum;};path.centroid=function(object){d3_geo_centroidDimension=d3_geo_centroidX=d3_geo_centroidY=d3_geo_centroidZ=0;d3.geo.stream(object,projectStream(d3_geo_pathCentroid));return d3_geo_centroidZ?[d3_geo_centroidX/d3_geo_centroidZ,d3_geo_centroidY/d3_geo_centroidZ]:undefined;};path.bounds=function(object){return d3_geo_bounds(projectStream)(object);};path.projection=function(_){if(!arguments.length)return projection;projectStream=(projection=_)?_.stream||d3_geo_pathProjectStream(_):d3_identity;return path;};path.context=function(_){if(!arguments.length)return context;contextStream=(context=_)==null?new d3_geo_pathBuffer():new d3_geo_pathContext(_);return path;};path.pointRadius=function(_){if(!arguments.length)return pointRadius;pointRadius=typeof _==="function"?_:+_;return path;};return path.projection(d3.geo.albersUsa()).context(null);};function d3_geo_pathCircle(radius){return"m0,"+radius+"a"+radius+","+radius+" 0 1,1 0,"+-2*radius+"a"+radius+","+radius+" 0 1,1 0,"+ +2*radius+"z";}
function d3_geo_pathProjectStream(project){var resample=d3_geo_resample(function(λ,φ){return project([λ*d3_degrees,φ*d3_degrees]);});return function(stream){stream=resample(stream);return{point:function(λ,φ){stream.point(λ*d3_radians,φ*d3_radians);},sphere:function(){stream.sphere();},lineStart:function(){stream.lineStart();},lineEnd:function(){stream.lineEnd();},polygonStart:function(){stream.polygonStart();},polygonEnd:function(){stream.polygonEnd();}};};}
d3.geo.albers=function(){return d3.geo.conicEqualArea().parallels([29.5,45.5]).rotate([98,0]).center([0,38]).scale(1e3);};function d3_geo_azimuthal(scale,angle){function azimuthal(λ,φ){var cosλ=Math.cos(λ),cosφ=Math.cos(φ),k=scale(cosλ*cosφ);return[k*cosφ*Math.sin(λ),k*Math.sin(φ)];}
azimuthal.invert=function(x,y){var ρ=Math.sqrt(x*x+y*y),c=angle(ρ),sinc=Math.sin(c),cosc=Math.cos(c);return[Math.atan2(x*sinc,ρ*cosc),Math.asin(ρ&&y*sinc/ρ)];};return azimuthal;}
var d3_geo_azimuthalEqualArea=d3_geo_azimuthal(function(cosλcosφ){return Math.sqrt(2/(1+cosλcosφ));},function(ρ){return 2*Math.asin(ρ/2);});(d3.geo.azimuthalEqualArea=function(){return d3_geo_projection(d3_geo_azimuthalEqualArea);}).raw=d3_geo_azimuthalEqualArea;var d3_geo_azimuthalEquidistant=d3_geo_azimuthal(function(cosλcosφ){var c=Math.acos(cosλcosφ);return c&&c/Math.sin(c);},d3_identity);(d3.geo.azimuthalEquidistant=function(){return d3_geo_projection(d3_geo_azimuthalEquidistant);}).raw=d3_geo_azimuthalEquidistant;function d3_geo_conicConformal(φ0,φ1){var cosφ0=Math.cos(φ0),t=function(φ){return Math.tan(π/4+φ/2);},n=φ0===φ1?Math.sin(φ0):Math.log(cosφ0/Math.cos(φ1))/Math.log(t(φ1)/t(φ0)),F=cosφ0*Math.pow(t(φ0),n)/n;if(!n)return d3_geo_mercator;function forward(λ,φ){var ρ=Math.abs(Math.abs(φ)-π/2)<ε?0:F/Math.pow(t(φ),n);return[ρ*Math.sin(n*λ),F-ρ*Math.cos(n*λ)];}
forward.invert=function(x,y){var ρ0_y=F-y,ρ=d3_sgn(n)*Math.sqrt(x*x+ρ0_y*ρ0_y);return[Math.atan2(x,ρ0_y)/n,2*Math.atan(Math.pow(F/ρ,1/n))-π/2];};return forward;}
(d3.geo.conicConformal=function(){return d3_geo_conic(d3_geo_conicConformal);}).raw=d3_geo_conicConformal;function d3_geo_conicEquidistant(φ0,φ1){var cosφ0=Math.cos(φ0),n=φ0===φ1?Math.sin(φ0):(cosφ0-Math.cos(φ1))/(φ1-φ0),G=cosφ0/n+φ0;if(Math.abs(n)<ε)return d3_geo_equirectangular;function forward(λ,φ){var ρ=G-φ;return[ρ*Math.sin(n*λ),G-ρ*Math.cos(n*λ)];}
forward.invert=function(x,y){var ρ0_y=G-y;return[Math.atan2(x,ρ0_y)/n,G-d3_sgn(n)*Math.sqrt(x*x+ρ0_y*ρ0_y)];};return forward;}
(d3.geo.conicEquidistant=function(){return d3_geo_conic(d3_geo_conicEquidistant);}).raw=d3_geo_conicEquidistant;var d3_geo_gnomonic=d3_geo_azimuthal(function(cosλcosφ){return 1/cosλcosφ;},Math.atan);(d3.geo.gnomonic=function(){return d3_geo_projection(d3_geo_gnomonic);}).raw=d3_geo_gnomonic;function d3_geo_mercator(λ,φ){return[λ,Math.log(Math.tan(π/4+φ/2))];}
d3_geo_mercator.invert=function(x,y){return[x,2*Math.atan(Math.exp(y))-π/2];};function d3_geo_mercatorProjection(project){var m=d3_geo_projection(project),scale=m.scale,translate=m.translate,clipExtent=m.clipExtent,clipAuto;m.scale=function(){var v=scale.apply(m,arguments);return v===m?clipAuto?m.clipExtent(null):m:v;};m.translate=function(){var v=translate.apply(m,arguments);return v===m?clipAuto?m.clipExtent(null):m:v;};m.clipExtent=function(_){var v=clipExtent.apply(m,arguments);if(v===m){if(clipAuto=_==null){var k=π*scale(),t=translate();clipExtent([[t[0]-k,t[1]-k],[t[0]+k,t[1]+k]]);}}else if(clipAuto){v=null;}
return v;};return m.clipExtent(null);}
(d3.geo.mercator=function(){return d3_geo_mercatorProjection(d3_geo_mercator);}).raw=d3_geo_mercator;var d3_geo_orthographic=d3_geo_azimuthal(function(){return 1;},Math.asin);(d3.geo.orthographic=function(){return d3_geo_projection(d3_geo_orthographic);}).raw=d3_geo_orthographic;var d3_geo_stereographic=d3_geo_azimuthal(function(cosλcosφ){return 1/(1+cosλcosφ);},function(ρ){return 2*Math.atan(ρ);});(d3.geo.stereographic=function(){return d3_geo_projection(d3_geo_stereographic);}).raw=d3_geo_stereographic;function d3_geo_transverseMercator(λ,φ){var B=Math.cos(φ)*Math.sin(λ);return[Math.log((1+B)/(1-B))/2,Math.atan2(Math.tan(φ),Math.cos(λ))];}
d3_geo_transverseMercator.invert=function(x,y){return[Math.atan2(d3_sinh(x),Math.cos(y)),d3_asin(Math.sin(y)/d3_cosh(x))];};(d3.geo.transverseMercator=function(){return d3_geo_mercatorProjection(d3_geo_transverseMercator);}).raw=d3_geo_transverseMercator;d3.geom={};d3.svg={};function d3_svg_line(projection){var x=d3_svg_lineX,y=d3_svg_lineY,defined=d3_true,interpolate=d3_svg_lineLinear,interpolateKey=interpolate.key,tension=.7;function line(data){var segments=[],points=[],i=-1,n=data.length,d,fx=d3_functor(x),fy=d3_functor(y);function segment(){segments.push("M",interpolate(projection(points),tension));}
while(++i<n){if(defined.call(this,d=data[i],i)){points.push([+fx.call(this,d,i),+fy.call(this,d,i)]);}else if(points.length){segment();points=[];}}
if(points.length)segment();return segments.length?segments.join(""):null;}
line.x=function(_){if(!arguments.length)return x;x=_;return line;};line.y=function(_){if(!arguments.length)return y;y=_;return line;};line.defined=function(_){if(!arguments.length)return defined;defined=_;return line;};line.interpolate=function(_){if(!arguments.length)return interpolateKey;if(typeof _==="function")interpolateKey=interpolate=_;else interpolateKey=(interpolate=d3_svg_lineInterpolators.get(_)||d3_svg_lineLinear).key;return line;};line.tension=function(_){if(!arguments.length)return tension;tension=_;return line;};return line;}
d3.svg.line=function(){return d3_svg_line(d3_identity);};function d3_svg_lineX(d){return d[0];}
function d3_svg_lineY(d){return d[1];}
var d3_svg_lineInterpolators=d3.map({linear:d3_svg_lineLinear,"linear-closed":d3_svg_lineLinearClosed,"step-before":d3_svg_lineStepBefore,"step-after":d3_svg_lineStepAfter,basis:d3_svg_lineBasis,"basis-open":d3_svg_lineBasisOpen,"basis-closed":d3_svg_lineBasisClosed,bundle:d3_svg_lineBundle,cardinal:d3_svg_lineCardinal,"cardinal-open":d3_svg_lineCardinalOpen,"cardinal-closed":d3_svg_lineCardinalClosed,monotone:d3_svg_lineMonotone});d3_svg_lineInterpolators.forEach(function(key,value){value.key=key;value.closed=/-closed$/.test(key);});function d3_svg_lineLinear(points){return points.join("L");}
function d3_svg_lineLinearClosed(points){return d3_svg_lineLinear(points)+"Z";}
function d3_svg_lineStepBefore(points){var i=0,n=points.length,p=points[0],path=[p[0],",",p[1]];while(++i<n)path.push("V",(p=points[i])[1],"H",p[0]);return path.join("");}
function d3_svg_lineStepAfter(points){var i=0,n=points.length,p=points[0],path=[p[0],",",p[1]];while(++i<n)path.push("H",(p=points[i])[0],"V",p[1]);return path.join("");}
function d3_svg_lineCardinalOpen(points,tension){return points.length<4?d3_svg_lineLinear(points):points[1]+d3_svg_lineHermite(points.slice(1,points.length-1),d3_svg_lineCardinalTangents(points,tension));}
function d3_svg_lineCardinalClosed(points,tension){return points.length<3?d3_svg_lineLinear(points):points[0]+d3_svg_lineHermite((points.push(points[0]),points),d3_svg_lineCardinalTangents([points[points.length-2]].concat(points,[points[1]]),tension));}
function d3_svg_lineCardinal(points,tension){return points.length<3?d3_svg_lineLinear(points):points[0]+d3_svg_lineHermite(points,d3_svg_lineCardinalTangents(points,tension));}
function d3_svg_lineHermite(points,tangents){if(tangents.length<1||points.length!=tangents.length&&points.length!=tangents.length+2){return d3_svg_lineLinear(points);}
var quad=points.length!=tangents.length,path="",p0=points[0],p=points[1],t0=tangents[0],t=t0,pi=1;if(quad){path+="Q"+(p[0]-t0[0]*2/3)+","+(p[1]-t0[1]*2/3)+","+p[0]+","+p[1];p0=points[1];pi=2;}
if(tangents.length>1){t=tangents[1];p=points[pi];pi++;path+="C"+(p0[0]+t0[0])+","+(p0[1]+t0[1])+","+(p[0]-t[0])+","+(p[1]-t[1])+","+p[0]+","+p[1];for(var i=2;i<tangents.length;i++,pi++){p=points[pi];t=tangents[i];path+="S"+(p[0]-t[0])+","+(p[1]-t[1])+","+p[0]+","+p[1];}}
if(quad){var lp=points[pi];path+="Q"+(p[0]+t[0]*2/3)+","+(p[1]+t[1]*2/3)+","+lp[0]+","+lp[1];}
return path;}
function d3_svg_lineCardinalTangents(points,tension){var tangents=[],a=(1-tension)/2,p0,p1=points[0],p2=points[1],i=1,n=points.length;while(++i<n){p0=p1;p1=p2;p2=points[i];tangents.push([a*(p2[0]-p0[0]),a*(p2[1]-p0[1])]);}
return tangents;}
function d3_svg_lineBasis(points){if(points.length<3)return d3_svg_lineLinear(points);var i=1,n=points.length,pi=points[0],x0=pi[0],y0=pi[1],px=[x0,x0,x0,(pi=points[1])[0]],py=[y0,y0,y0,pi[1]],path=[x0,",",y0];d3_svg_lineBasisBezier(path,px,py);while(++i<n){pi=points[i];px.shift();px.push(pi[0]);py.shift();py.push(pi[1]);d3_svg_lineBasisBezier(path,px,py);}
i=-1;while(++i<2){px.shift();px.push(pi[0]);py.shift();py.push(pi[1]);d3_svg_lineBasisBezier(path,px,py);}
return path.join("");}
function d3_svg_lineBasisOpen(points){if(points.length<4)return d3_svg_lineLinear(points);var path=[],i=-1,n=points.length,pi,px=[0],py=[0];while(++i<3){pi=points[i];px.push(pi[0]);py.push(pi[1]);}
path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3,px)+","+d3_svg_lineDot4(d3_svg_lineBasisBezier3,py));--i;while(++i<n){pi=points[i];px.shift();px.push(pi[0]);py.shift();py.push(pi[1]);d3_svg_lineBasisBezier(path,px,py);}
return path.join("");}
function d3_svg_lineBasisClosed(points){var path,i=-1,n=points.length,m=n+4,pi,px=[],py=[];while(++i<4){pi=points[i%n];px.push(pi[0]);py.push(pi[1]);}
path=[d3_svg_lineDot4(d3_svg_lineBasisBezier3,px),",",d3_svg_lineDot4(d3_svg_lineBasisBezier3,py)];--i;while(++i<m){pi=points[i%n];px.shift();px.push(pi[0]);py.shift();py.push(pi[1]);d3_svg_lineBasisBezier(path,px,py);}
return path.join("");}
function d3_svg_lineBundle(points,tension){var n=points.length-1;if(n){var x0=points[0][0],y0=points[0][1],dx=points[n][0]-x0,dy=points[n][1]-y0,i=-1,p,t;while(++i<=n){p=points[i];t=i/n;p[0]=tension*p[0]+(1-tension)*(x0+t*dx);p[1]=tension*p[1]+(1-tension)*(y0+t*dy);}}
return d3_svg_lineBasis(points);}
function d3_svg_lineDot4(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3];}
var d3_svg_lineBasisBezier1=[0,2/3,1/3,0],d3_svg_lineBasisBezier2=[0,1/3,2/3,0],d3_svg_lineBasisBezier3=[0,1/6,2/3,1/6];function d3_svg_lineBasisBezier(path,x,y){path.push("C",d3_svg_lineDot4(d3_svg_lineBasisBezier1,x),",",d3_svg_lineDot4(d3_svg_lineBasisBezier1,y),",",d3_svg_lineDot4(d3_svg_lineBasisBezier2,x),",",d3_svg_lineDot4(d3_svg_lineBasisBezier2,y),",",d3_svg_lineDot4(d3_svg_lineBasisBezier3,x),",",d3_svg_lineDot4(d3_svg_lineBasisBezier3,y));}
function d3_svg_lineSlope(p0,p1){return(p1[1]-p0[1])/(p1[0]-p0[0]);}
function d3_svg_lineFiniteDifferences(points){var i=0,j=points.length-1,m=[],p0=points[0],p1=points[1],d=m[0]=d3_svg_lineSlope(p0,p1);while(++i<j){m[i]=(d+(d=d3_svg_lineSlope(p0=p1,p1=points[i+1])))/2;}
m[i]=d;return m;}
function d3_svg_lineMonotoneTangents(points){var tangents=[],d,a,b,s,m=d3_svg_lineFiniteDifferences(points),i=-1,j=points.length-1;while(++i<j){d=d3_svg_lineSlope(points[i],points[i+1]);if(Math.abs(d)<1e-6){m[i]=m[i+1]=0;}else{a=m[i]/d;b=m[i+1]/d;s=a*a+b*b;if(s>9){s=d*3/Math.sqrt(s);m[i]=s*a;m[i+1]=s*b;}}}
i=-1;while(++i<=j){s=(points[Math.min(j,i+1)][0]-points[Math.max(0,i-1)][0])/(6*(1+m[i]*m[i]));tangents.push([s||0,m[i]*s||0]);}
return tangents;}
function d3_svg_lineMonotone(points){return points.length<3?d3_svg_lineLinear(points):points[0]+d3_svg_lineHermite(points,d3_svg_lineMonotoneTangents(points));}
d3.geom.hull=function(vertices){var x=d3_svg_lineX,y=d3_svg_lineY;if(arguments.length)return hull(vertices);function hull(data){if(data.length<3)return[];var fx=d3_functor(x),fy=d3_functor(y),n=data.length,vertices,plen=n-1,points=[],stack=[],d,i,j,h=0,x1,y1,x2,y2,u,v,a,sp;if(fx===d3_svg_lineX&&y===d3_svg_lineY)vertices=data;else for(i=0,vertices=[];i<n;++i){vertices.push([+fx.call(this,d=data[i],i),+fy.call(this,d,i)]);}
for(i=1;i<n;++i){if(vertices[i][1]<vertices[h][1]||vertices[i][1]==vertices[h][1]&&vertices[i][0]<vertices[h][0])h=i;}
for(i=0;i<n;++i){if(i===h)continue;y1=vertices[i][1]-vertices[h][1];x1=vertices[i][0]-vertices[h][0];points.push({angle:Math.atan2(y1,x1),index:i});}
points.sort(function(a,b){return a.angle-b.angle;});a=points[0].angle;v=points[0].index;u=0;for(i=1;i<plen;++i){j=points[i].index;if(a==points[i].angle){x1=vertices[v][0]-vertices[h][0];y1=vertices[v][1]-vertices[h][1];x2=vertices[j][0]-vertices[h][0];y2=vertices[j][1]-vertices[h][1];if(x1*x1+y1*y1>=x2*x2+y2*y2){points[i].index=-1;continue;}else{points[u].index=-1;}}
a=points[i].angle;u=i;v=j;}
stack.push(h);for(i=0,j=0;i<2;++j){if(points[j].index>-1){stack.push(points[j].index);i++;}}
sp=stack.length;for(;j<plen;++j){if(points[j].index<0)continue;while(!d3_geom_hullCCW(stack[sp-2],stack[sp-1],points[j].index,vertices)){--sp;}
stack[sp++]=points[j].index;}
var poly=[];for(i=sp-1;i>=0;--i)poly.push(data[stack[i]]);return poly;}
hull.x=function(_){return arguments.length?(x=_,hull):x;};hull.y=function(_){return arguments.length?(y=_,hull):y;};return hull;};function d3_geom_hullCCW(i1,i2,i3,v){var t,a,b,c,d,e,f;t=v[i1];a=t[0];b=t[1];t=v[i2];c=t[0];d=t[1];t=v[i3];e=t[0];f=t[1];return(f-b)*(c-a)-(d-b)*(e-a)>0;}
d3.geom.polygon=function(coordinates){coordinates.area=function(){var i=0,n=coordinates.length,area=coordinates[n-1][1]*coordinates[0][0]-coordinates[n-1][0]*coordinates[0][1];while(++i<n){area+=coordinates[i-1][1]*coordinates[i][0]-coordinates[i-1][0]*coordinates[i][1];}
return area*.5;};coordinates.centroid=function(k){var i=-1,n=coordinates.length,x=0,y=0,a,b=coordinates[n-1],c;if(!arguments.length)k=-1/(6*coordinates.area());while(++i<n){a=b;b=coordinates[i];c=a[0]*b[1]-b[0]*a[1];x+=(a[0]+b[0])*c;y+=(a[1]+b[1])*c;}
return[x*k,y*k];};coordinates.clip=function(subject){var input,i=-1,n=coordinates.length,j,m,a=coordinates[n-1],b,c,d;while(++i<n){input=subject.slice();subject.length=0;b=coordinates[i];c=input[(m=input.length)-1];j=-1;while(++j<m){d=input[j];if(d3_geom_polygonInside(d,a,b)){if(!d3_geom_polygonInside(c,a,b)){subject.push(d3_geom_polygonIntersect(c,d,a,b));}
subject.push(d);}else if(d3_geom_polygonInside(c,a,b)){subject.push(d3_geom_polygonIntersect(c,d,a,b));}
c=d;}
a=b;}
return subject;};return coordinates;};function d3_geom_polygonInside(p,a,b){return(b[0]-a[0])*(p[1]-a[1])<(b[1]-a[1])*(p[0]-a[0]);}
function d3_geom_polygonIntersect(c,d,a,b){var x1=c[0],x3=a[0],x21=d[0]-x1,x43=b[0]-x3,y1=c[1],y3=a[1],y21=d[1]-y1,y43=b[1]-y3,ua=(x43*(y1-y3)-y43*(x1-x3))/(y43*x21-x43*y21);return[x1+ua*x21,y1+ua*y21];}
d3.geom.delaunay=function(vertices){var edges=vertices.map(function(){return[];}),triangles=[];d3_geom_voronoiTessellate(vertices,function(e){edges[e.region.l.index].push(vertices[e.region.r.index]);});edges.forEach(function(edge,i){var v=vertices[i],cx=v[0],cy=v[1];edge.forEach(function(v){v.angle=Math.atan2(v[0]-cx,v[1]-cy);});edge.sort(function(a,b){return a.angle-b.angle;});for(var j=0,m=edge.length-1;j<m;j++){triangles.push([v,edge[j],edge[j+1]]);}});return triangles;};d3.geom.voronoi=function(points){var size=null,x=d3_svg_lineX,y=d3_svg_lineY,clip;if(arguments.length)return voronoi(points);function voronoi(data){var points,polygons=data.map(function(){return[];}),fx=d3_functor(x),fy=d3_functor(y),d,i,n=data.length,Z=1e6;if(fx===d3_svg_lineX&&fy===d3_svg_lineY)points=data;else for(points=[],i=0;i<n;++i){points.push([+fx.call(this,d=data[i],i),+fy.call(this,d,i)]);}
d3_geom_voronoiTessellate(points,function(e){var s1,s2,x1,x2,y1,y2;if(e.a===1&&e.b>=0){s1=e.ep.r;s2=e.ep.l;}else{s1=e.ep.l;s2=e.ep.r;}
if(e.a===1){y1=s1?s1.y:-Z;x1=e.c-e.b*y1;y2=s2?s2.y:Z;x2=e.c-e.b*y2;}else{x1=s1?s1.x:-Z;y1=e.c-e.a*x1;x2=s2?s2.x:Z;y2=e.c-e.a*x2;}
var v1=[x1,y1],v2=[x2,y2];polygons[e.region.l.index].push(v1,v2);polygons[e.region.r.index].push(v1,v2);});polygons=polygons.map(function(polygon,i){var cx=points[i][0],cy=points[i][1],angle=polygon.map(function(v){return Math.atan2(v[0]-cx,v[1]-cy);}),order=d3.range(polygon.length).sort(function(a,b){return angle[a]-angle[b];});return order.filter(function(d,i){return!i||angle[d]-angle[order[i-1]]>ε;}).map(function(d){return polygon[d];});});polygons.forEach(function(polygon,i){var n=polygon.length;if(!n)return polygon.push([-Z,-Z],[-Z,Z],[Z,Z],[Z,-Z]);if(n>2)return;var p0=points[i],p1=polygon[0],p2=polygon[1],x0=p0[0],y0=p0[1],x1=p1[0],y1=p1[1],x2=p2[0],y2=p2[1],dx=Math.abs(x2-x1),dy=y2-y1;if(Math.abs(dy)<ε){var y=y0<y1?-Z:Z;polygon.push([-Z,y],[Z,y]);}else if(dx<ε){var x=x0<x1?-Z:Z;polygon.push([x,-Z],[x,Z]);}else{var y=(x2-x1)*(y1-y0)<(x1-x0)*(y2-y1)?Z:-Z,z=Math.abs(dy)-dx;if(Math.abs(z)<ε){polygon.push([dy<0?y:-y,y]);}else{if(z>0)y*=-1;polygon.push([-Z,y],[Z,y]);}}});if(clip)for(i=0;i<n;++i)clip(polygons[i]);for(i=0;i<n;++i)polygons[i].point=data[i];return polygons;}
voronoi.x=function(_){return arguments.length?(x=_,voronoi):x;};voronoi.y=function(_){return arguments.length?(y=_,voronoi):y;};voronoi.size=function(_){if(!arguments.length)return size;if(_==null){clip=null;}else{size=[+_[0],+_[1]];clip=d3.geom.polygon([[0,0],[0,size[1]],size,[size[0],0]]).clip;}
return voronoi;};voronoi.links=function(data){var points,graph=data.map(function(){return[];}),links=[],fx=d3_functor(x),fy=d3_functor(y),d,i,n=data.length;if(fx===d3_svg_lineX&&fy===d3_svg_lineY)points=data;else for(i=0;i<n;++i){points.push([+fx.call(this,d=data[i],i),+fy.call(this,d,i)]);}
d3_geom_voronoiTessellate(points,function(e){var l=e.region.l.index,r=e.region.r.index;if(graph[l][r])return;graph[l][r]=graph[r][l]=true;links.push({source:data[l],target:data[r]});});return links;};voronoi.triangles=function(data){if(x===d3_svg_lineX&&y===d3_svg_lineY)return d3.geom.delaunay(data);var points,point,fx=d3_functor(x),fy=d3_functor(y),d,i,n;for(i=0,points=[],n=data.length;i<n;++i){point=[+fx.call(this,d=data[i],i),+fy.call(this,d,i)];point.data=d;points.push(point);}
return d3.geom.delaunay(points).map(function(triangle){return triangle.map(function(point){return point.data;});});};return voronoi;};var d3_geom_voronoiOpposite={l:"r",r:"l"};function d3_geom_voronoiTessellate(points,callback){var Sites={list:points.map(function(v,i){return{index:i,x:v[0],y:v[1]};}).sort(function(a,b){return a.y<b.y?-1:a.y>b.y?1:a.x<b.x?-1:a.x>b.x?1:0;}),bottomSite:null};var EdgeList={list:[],leftEnd:null,rightEnd:null,init:function(){EdgeList.leftEnd=EdgeList.createHalfEdge(null,"l");EdgeList.rightEnd=EdgeList.createHalfEdge(null,"l");EdgeList.leftEnd.r=EdgeList.rightEnd;EdgeList.rightEnd.l=EdgeList.leftEnd;EdgeList.list.unshift(EdgeList.leftEnd,EdgeList.rightEnd);},createHalfEdge:function(edge,side){return{edge:edge,side:side,vertex:null,l:null,r:null};},insert:function(lb,he){he.l=lb;he.r=lb.r;lb.r.l=he;lb.r=he;},leftBound:function(p){var he=EdgeList.leftEnd;do{he=he.r;}while(he!=EdgeList.rightEnd&&Geom.rightOf(he,p));he=he.l;return he;},del:function(he){he.l.r=he.r;he.r.l=he.l;he.edge=null;},right:function(he){return he.r;},left:function(he){return he.l;},leftRegion:function(he){return he.edge==null?Sites.bottomSite:he.edge.region[he.side];},rightRegion:function(he){return he.edge==null?Sites.bottomSite:he.edge.region[d3_geom_voronoiOpposite[he.side]];}};var Geom={bisect:function(s1,s2){var newEdge={region:{l:s1,r:s2},ep:{l:null,r:null}};var dx=s2.x-s1.x,dy=s2.y-s1.y,adx=dx>0?dx:-dx,ady=dy>0?dy:-dy;newEdge.c=s1.x*dx+s1.y*dy+(dx*dx+dy*dy)*.5;if(adx>ady){newEdge.a=1;newEdge.b=dy/dx;newEdge.c/=dx;}else{newEdge.b=1;newEdge.a=dx/dy;newEdge.c/=dy;}
return newEdge;},intersect:function(el1,el2){var e1=el1.edge,e2=el2.edge;if(!e1||!e2||e1.region.r==e2.region.r){return null;}
var d=e1.a*e2.b-e1.b*e2.a;if(Math.abs(d)<1e-10){return null;}
var xint=(e1.c*e2.b-e2.c*e1.b)/d,yint=(e2.c*e1.a-e1.c*e2.a)/d,e1r=e1.region.r,e2r=e2.region.r,el,e;if(e1r.y<e2r.y||e1r.y==e2r.y&&e1r.x<e2r.x){el=el1;e=e1;}else{el=el2;e=e2;}
var rightOfSite=xint>=e.region.r.x;if(rightOfSite&&el.side==="l"||!rightOfSite&&el.side==="r"){return null;}
return{x:xint,y:yint};},rightOf:function(he,p){var e=he.edge,topsite=e.region.r,rightOfSite=p.x>topsite.x;if(rightOfSite&&he.side==="l"){return 1;}
if(!rightOfSite&&he.side==="r"){return 0;}
if(e.a===1){var dyp=p.y-topsite.y,dxp=p.x-topsite.x,fast=0,above=0;if(!rightOfSite&&e.b<0||rightOfSite&&e.b>=0){above=fast=dyp>=e.b*dxp;}else{above=p.x+p.y*e.b>e.c;if(e.b<0){above=!above;}
if(!above){fast=1;}}
if(!fast){var dxs=topsite.x-e.region.l.x;above=e.b*(dxp*dxp-dyp*dyp)<dxs*dyp*(1+2*dxp/dxs+e.b*e.b);if(e.b<0){above=!above;}}}else{var yl=e.c-e.a*p.x,t1=p.y-yl,t2=p.x-topsite.x,t3=yl-topsite.y;above=t1*t1>t2*t2+t3*t3;}
return he.side==="l"?above:!above;},endPoint:function(edge,side,site){edge.ep[side]=site;if(!edge.ep[d3_geom_voronoiOpposite[side]])return;callback(edge);},distance:function(s,t){var dx=s.x-t.x,dy=s.y-t.y;return Math.sqrt(dx*dx+dy*dy);}};var EventQueue={list:[],insert:function(he,site,offset){he.vertex=site;he.ystar=site.y+offset;for(var i=0,list=EventQueue.list,l=list.length;i<l;i++){var next=list[i];if(he.ystar>next.ystar||he.ystar==next.ystar&&site.x>next.vertex.x){continue;}else{break;}}
list.splice(i,0,he);},del:function(he){for(var i=0,ls=EventQueue.list,l=ls.length;i<l&&ls[i]!=he;++i){}
ls.splice(i,1);},empty:function(){return EventQueue.list.length===0;},nextEvent:function(he){for(var i=0,ls=EventQueue.list,l=ls.length;i<l;++i){if(ls[i]==he)return ls[i+1];}
return null;},min:function(){var elem=EventQueue.list[0];return{x:elem.vertex.x,y:elem.ystar};},extractMin:function(){return EventQueue.list.shift();}};EdgeList.init();Sites.bottomSite=Sites.list.shift();var newSite=Sites.list.shift(),newIntStar;var lbnd,rbnd,llbnd,rrbnd,bisector;var bot,top,temp,p,v;var e,pm;while(true){if(!EventQueue.empty()){newIntStar=EventQueue.min();}
if(newSite&&(EventQueue.empty()||newSite.y<newIntStar.y||newSite.y==newIntStar.y&&newSite.x<newIntStar.x)){lbnd=EdgeList.leftBound(newSite);rbnd=EdgeList.right(lbnd);bot=EdgeList.rightRegion(lbnd);e=Geom.bisect(bot,newSite);bisector=EdgeList.createHalfEdge(e,"l");EdgeList.insert(lbnd,bisector);p=Geom.intersect(lbnd,bisector);if(p){EventQueue.del(lbnd);EventQueue.insert(lbnd,p,Geom.distance(p,newSite));}
lbnd=bisector;bisector=EdgeList.createHalfEdge(e,"r");EdgeList.insert(lbnd,bisector);p=Geom.intersect(bisector,rbnd);if(p){EventQueue.insert(bisector,p,Geom.distance(p,newSite));}
newSite=Sites.list.shift();}else if(!EventQueue.empty()){lbnd=EventQueue.extractMin();llbnd=EdgeList.left(lbnd);rbnd=EdgeList.right(lbnd);rrbnd=EdgeList.right(rbnd);bot=EdgeList.leftRegion(lbnd);top=EdgeList.rightRegion(rbnd);v=lbnd.vertex;Geom.endPoint(lbnd.edge,lbnd.side,v);Geom.endPoint(rbnd.edge,rbnd.side,v);EdgeList.del(lbnd);EventQueue.del(rbnd);EdgeList.del(rbnd);pm="l";if(bot.y>top.y){temp=bot;bot=top;top=temp;pm="r";}
e=Geom.bisect(bot,top);bisector=EdgeList.createHalfEdge(e,pm);EdgeList.insert(llbnd,bisector);Geom.endPoint(e,d3_geom_voronoiOpposite[pm],v);p=Geom.intersect(llbnd,bisector);if(p){EventQueue.del(llbnd);EventQueue.insert(llbnd,p,Geom.distance(p,bot));}
p=Geom.intersect(bisector,rrbnd);if(p){EventQueue.insert(bisector,p,Geom.distance(p,bot));}}else{break;}}
for(lbnd=EdgeList.right(EdgeList.leftEnd);lbnd!=EdgeList.rightEnd;lbnd=EdgeList.right(lbnd)){callback(lbnd.edge);}}
d3.geom.quadtree=function(points,x1,y1,x2,y2){var x=d3_svg_lineX,y=d3_svg_lineY,compat;if(compat=arguments.length){x=d3_geom_quadtreeCompatX;y=d3_geom_quadtreeCompatY;if(compat===3){y2=y1;x2=x1;y1=x1=0;}
return quadtree(points);}
function quadtree(data){var d,fx=d3_functor(x),fy=d3_functor(y),xs,ys,i,n,x1_,y1_,x2_,y2_;if(x1!=null){x1_=x1,y1_=y1,x2_=x2,y2_=y2;}else{x2_=y2_=-(x1_=y1_=Infinity);xs=[],ys=[];n=data.length;if(compat)for(i=0;i<n;++i){d=data[i];if(d.x<x1_)x1_=d.x;if(d.y<y1_)y1_=d.y;if(d.x>x2_)x2_=d.x;if(d.y>y2_)y2_=d.y;xs.push(d.x);ys.push(d.y);}else for(i=0;i<n;++i){var x_=+fx(d=data[i],i),y_=+fy(d,i);if(x_<x1_)x1_=x_;if(y_<y1_)y1_=y_;if(x_>x2_)x2_=x_;if(y_>y2_)y2_=y_;xs.push(x_);ys.push(y_);}}
var dx=x2_-x1_,dy=y2_-y1_;if(dx>dy)y2_=y1_+dx;else x2_=x1_+dy;function insert(n,d,x,y,x1,y1,x2,y2){if(isNaN(x)||isNaN(y))return;if(n.leaf){var nx=n.x,ny=n.y;if(nx!=null){if(Math.abs(nx-x)+Math.abs(ny-y)<.01){insertChild(n,d,x,y,x1,y1,x2,y2);}else{var nPoint=n.point;n.x=n.y=n.point=null;insertChild(n,nPoint,nx,ny,x1,y1,x2,y2);insertChild(n,d,x,y,x1,y1,x2,y2);}}else{n.x=x,n.y=y,n.point=d;}}else{insertChild(n,d,x,y,x1,y1,x2,y2);}}
function insertChild(n,d,x,y,x1,y1,x2,y2){var sx=(x1+x2)*.5,sy=(y1+y2)*.5,right=x>=sx,bottom=y>=sy,i=(bottom<<1)+right;n.leaf=false;n=n.nodes[i]||(n.nodes[i]=d3_geom_quadtreeNode());if(right)x1=sx;else x2=sx;if(bottom)y1=sy;else y2=sy;insert(n,d,x,y,x1,y1,x2,y2);}
var root=d3_geom_quadtreeNode();root.add=function(d){insert(root,d,+fx(d,++i),+fy(d,i),x1_,y1_,x2_,y2_);};root.visit=function(f){d3_geom_quadtreeVisit(f,root,x1_,y1_,x2_,y2_);};i=-1;if(x1==null){while(++i<n){insert(root,data[i],xs[i],ys[i],x1_,y1_,x2_,y2_);}
--i;}else data.forEach(root.add);xs=ys=data=d=null;return root;}
quadtree.x=function(_){return arguments.length?(x=_,quadtree):x;};quadtree.y=function(_){return arguments.length?(y=_,quadtree):y;};quadtree.size=function(_){if(!arguments.length)return x1==null?null:[x2,y2];if(_==null){x1=y1=x2=y2=null;}else{x1=y1=0;x2=+_[0],y2=+_[1];}
return quadtree;};return quadtree;};function d3_geom_quadtreeCompatX(d){return d.x;}
function d3_geom_quadtreeCompatY(d){return d.y;}
function d3_geom_quadtreeNode(){return{leaf:true,nodes:[],point:null,x:null,y:null};}
function d3_geom_quadtreeVisit(f,node,x1,y1,x2,y2){if(!f(node,x1,y1,x2,y2)){var sx=(x1+x2)*.5,sy=(y1+y2)*.5,children=node.nodes;if(children[0])d3_geom_quadtreeVisit(f,children[0],x1,y1,sx,sy);if(children[1])d3_geom_quadtreeVisit(f,children[1],sx,y1,x2,sy);if(children[2])d3_geom_quadtreeVisit(f,children[2],x1,sy,sx,y2);if(children[3])d3_geom_quadtreeVisit(f,children[3],sx,sy,x2,y2);}}
d3.interpolateRgb=d3_interpolateRgb;function d3_interpolateRgb(a,b){a=d3.rgb(a);b=d3.rgb(b);var ar=a.r,ag=a.g,ab=a.b,br=b.r-ar,bg=b.g-ag,bb=b.b-ab;return function(t){return"#"+d3_rgb_hex(Math.round(ar+br*t))+d3_rgb_hex(Math.round(ag+bg*t))+d3_rgb_hex(Math.round(ab+bb*t));};}
d3.transform=function(string){var g=d3_document.createElementNS(d3.ns.prefix.svg,"g");return(d3.transform=function(string){g.setAttribute("transform",string);var t=g.transform.baseVal.consolidate();return new d3_transform(t?t.matrix:d3_transformIdentity);})(string);};function d3_transform(m){var r0=[m.a,m.b],r1=[m.c,m.d],kx=d3_transformNormalize(r0),kz=d3_transformDot(r0,r1),ky=d3_transformNormalize(d3_transformCombine(r1,r0,-kz))||0;if(r0[0]*r1[1]<r1[0]*r0[1]){r0[0]*=-1;r0[1]*=-1;kx*=-1;kz*=-1;}
this.rotate=(kx?Math.atan2(r0[1],r0[0]):Math.atan2(-r1[0],r1[1]))*d3_degrees;this.translate=[m.e,m.f];this.scale=[kx,ky];this.skew=ky?Math.atan2(kz,ky)*d3_degrees:0;}
d3_transform.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")";};function d3_transformDot(a,b){return a[0]*b[0]+a[1]*b[1];}
function d3_transformNormalize(a){var k=Math.sqrt(d3_transformDot(a,a));if(k){a[0]/=k;a[1]/=k;}
return k;}
function d3_transformCombine(a,b,k){a[0]+=k*b[0];a[1]+=k*b[1];return a;}
var d3_transformIdentity={a:1,b:0,c:0,d:1,e:0,f:0};d3.interpolateNumber=d3_interpolateNumber;function d3_interpolateNumber(a,b){b-=a=+a;return function(t){return a+b*t;};}
d3.interpolateTransform=d3_interpolateTransform;function d3_interpolateTransform(a,b){var s=[],q=[],n,A=d3.transform(a),B=d3.transform(b),ta=A.translate,tb=B.translate,ra=A.rotate,rb=B.rotate,wa=A.skew,wb=B.skew,ka=A.scale,kb=B.scale;if(ta[0]!=tb[0]||ta[1]!=tb[1]){s.push("translate(",null,",",null,")");q.push({i:1,x:d3_interpolateNumber(ta[0],tb[0])},{i:3,x:d3_interpolateNumber(ta[1],tb[1])});}else if(tb[0]||tb[1]){s.push("translate("+tb+")");}else{s.push("");}
if(ra!=rb){if(ra-rb>180)rb+=360;else if(rb-ra>180)ra+=360;q.push({i:s.push(s.pop()+"rotate(",null,")")-2,x:d3_interpolateNumber(ra,rb)});}else if(rb){s.push(s.pop()+"rotate("+rb+")");}
if(wa!=wb){q.push({i:s.push(s.pop()+"skewX(",null,")")-2,x:d3_interpolateNumber(wa,wb)});}else if(wb){s.push(s.pop()+"skewX("+wb+")");}
if(ka[0]!=kb[0]||ka[1]!=kb[1]){n=s.push(s.pop()+"scale(",null,",",null,")");q.push({i:n-4,x:d3_interpolateNumber(ka[0],kb[0])},{i:n-2,x:d3_interpolateNumber(ka[1],kb[1])});}else if(kb[0]!=1||kb[1]!=1){s.push(s.pop()+"scale("+kb+")");}
n=q.length;return function(t){var i=-1,o;while(++i<n)s[(o=q[i]).i]=o.x(t);return s.join("");};}
d3.interpolateObject=d3_interpolateObject;function d3_interpolateObject(a,b){var i={},c={},k;for(k in a){if(k in b){i[k]=d3_interpolateByName(k)(a[k],b[k]);}else{c[k]=a[k];}}
for(k in b){if(!(k in a)){c[k]=b[k];}}
return function(t){for(k in i)c[k]=i[k](t);return c;};}
d3.interpolateString=d3_interpolateString;function d3_interpolateString(a,b){var m,i,j,s0=0,s1=0,s=[],q=[],n,o;a=a+"",b=b+"";d3_interpolate_number.lastIndex=0;for(i=0;m=d3_interpolate_number.exec(b);++i){if(m.index)s.push(b.substring(s0,s1=m.index));q.push({i:s.length,x:m[0]});s.push(null);s0=d3_interpolate_number.lastIndex;}
if(s0<b.length)s.push(b.substring(s0));for(i=0,n=q.length;(m=d3_interpolate_number.exec(a))&&i<n;++i){o=q[i];if(o.x==m[0]){if(o.i){if(s[o.i+1]==null){s[o.i-1]+=o.x;s.splice(o.i,1);for(j=i+1;j<n;++j)q[j].i--;}else{s[o.i-1]+=o.x+s[o.i+1];s.splice(o.i,2);for(j=i+1;j<n;++j)q[j].i-=2;}}else{if(s[o.i+1]==null){s[o.i]=o.x;}else{s[o.i]=o.x+s[o.i+1];s.splice(o.i+1,1);for(j=i+1;j<n;++j)q[j].i--;}}
q.splice(i,1);n--;i--;}else{o.x=d3_interpolateNumber(parseFloat(m[0]),parseFloat(o.x));}}
while(i<n){o=q.pop();if(s[o.i+1]==null){s[o.i]=o.x;}else{s[o.i]=o.x+s[o.i+1];s.splice(o.i+1,1);}
n--;}
if(s.length===1){return s[0]==null?q[0].x:function(){return b;};}
return function(t){for(i=0;i<n;++i)s[(o=q[i]).i]=o.x(t);return s.join("");};}
var d3_interpolate_number=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;d3.interpolate=d3_interpolate;function d3_interpolate(a,b){var i=d3.interpolators.length,f;while(--i>=0&&!(f=d3.interpolators[i](a,b)));return f;}
function d3_interpolateByName(name){return name=="transform"?d3_interpolateTransform:d3_interpolate;}
d3.interpolators=[function(a,b){var t=typeof b;return(t==="string"||t!==typeof a?d3_rgb_names.has(b)||/^(#|rgb\(|hsl\()/.test(b)?d3_interpolateRgb:d3_interpolateString:b instanceof d3_Color?d3_interpolateRgb:t==="object"?Array.isArray(b)?d3_interpolateArray:d3_interpolateObject:d3_interpolateNumber)(a,b);}];d3.interpolateArray=d3_interpolateArray;function d3_interpolateArray(a,b){var x=[],c=[],na=a.length,nb=b.length,n0=Math.min(a.length,b.length),i;for(i=0;i<n0;++i)x.push(d3_interpolate(a[i],b[i]));for(;i<na;++i)c[i]=a[i];for(;i<nb;++i)c[i]=b[i];return function(t){for(i=0;i<n0;++i)c[i]=x[i](t);return c;};}
var d3_ease_default=function(){return d3_identity;};var d3_ease=d3.map({linear:d3_ease_default,poly:d3_ease_poly,quad:function(){return d3_ease_quad;},cubic:function(){return d3_ease_cubic;},sin:function(){return d3_ease_sin;},exp:function(){return d3_ease_exp;},circle:function(){return d3_ease_circle;},elastic:d3_ease_elastic,back:d3_ease_back,bounce:function(){return d3_ease_bounce;}});var d3_ease_mode=d3.map({"in":d3_identity,out:d3_ease_reverse,"in-out":d3_ease_reflect,"out-in":function(f){return d3_ease_reflect(d3_ease_reverse(f));}});d3.ease=function(name){var i=name.indexOf("-"),t=i>=0?name.substring(0,i):name,m=i>=0?name.substring(i+1):"in";t=d3_ease.get(t)||d3_ease_default;m=d3_ease_mode.get(m)||d3_identity;return d3_ease_clamp(m(t.apply(null,Array.prototype.slice.call(arguments,1))));};function d3_ease_clamp(f){return function(t){return t<=0?0:t>=1?1:f(t);};}
function d3_ease_reverse(f){return function(t){return 1-f(1-t);};}
function d3_ease_reflect(f){return function(t){return.5*(t<.5?f(2*t):2-f(2-2*t));};}
function d3_ease_quad(t){return t*t;}
function d3_ease_cubic(t){return t*t*t;}
function d3_ease_cubicInOut(t){if(t<=0)return 0;if(t>=1)return 1;var t2=t*t,t3=t2*t;return 4*(t<.5?t3:3*(t-t2)+t3-.75);}
function d3_ease_poly(e){return function(t){return Math.pow(t,e);};}
function d3_ease_sin(t){return 1-Math.cos(t*π/2);}
function d3_ease_exp(t){return Math.pow(2,10*(t-1));}
function d3_ease_circle(t){return 1-Math.sqrt(1-t*t);}
function d3_ease_elastic(a,p){var s;if(arguments.length<2)p=.45;if(arguments.length)s=p/(2*π)*Math.asin(1/a);else a=1,s=p/4;return function(t){return 1+a*Math.pow(2,10*-t)*Math.sin((t-s)*2*π/p);};}
function d3_ease_back(s){if(!s)s=1.70158;return function(t){return t*t*((s+1)*t-s);};}
function d3_ease_bounce(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375;}
d3.interpolateHcl=d3_interpolateHcl;function d3_interpolateHcl(a,b){a=d3.hcl(a);b=d3.hcl(b);var ah=a.h,ac=a.c,al=a.l,bh=b.h-ah,bc=b.c-ac,bl=b.l-al;if(isNaN(bc))bc=0,ac=isNaN(ac)?b.c:ac;if(isNaN(bh))bh=0,ah=isNaN(ah)?b.h:ah;else if(bh>180)bh-=360;else if(bh<-180)bh+=360;return function(t){return d3_hcl_lab(ah+bh*t,ac+bc*t,al+bl*t)+"";};}
d3.interpolateHsl=d3_interpolateHsl;function d3_interpolateHsl(a,b){a=d3.hsl(a);b=d3.hsl(b);var ah=a.h,as=a.s,al=a.l,bh=b.h-ah,bs=b.s-as,bl=b.l-al;if(isNaN(bs))bs=0,as=isNaN(as)?b.s:as;if(isNaN(bh))bh=0,ah=isNaN(ah)?b.h:ah;else if(bh>180)bh-=360;else if(bh<-180)bh+=360;return function(t){return d3_hsl_rgb(ah+bh*t,as+bs*t,al+bl*t)+"";};}
d3.interpolateLab=d3_interpolateLab;function d3_interpolateLab(a,b){a=d3.lab(a);b=d3.lab(b);var al=a.l,aa=a.a,ab=a.b,bl=b.l-al,ba=b.a-aa,bb=b.b-ab;return function(t){return d3_lab_rgb(al+bl*t,aa+ba*t,ab+bb*t)+"";};}
d3.interpolateRound=d3_interpolateRound;function d3_interpolateRound(a,b){b-=a;return function(t){return Math.round(a+b*t);};}
function d3_uninterpolateNumber(a,b){b=b-(a=+a)?1/(b-a):0;return function(x){return(x-a)*b;};}
function d3_uninterpolateClamp(a,b){b=b-(a=+a)?1/(b-a):0;return function(x){return Math.max(0,Math.min(1,(x-a)*b));};}
d3.layout={};d3.layout.bundle=function(){return function(links){var paths=[],i=-1,n=links.length;while(++i<n)paths.push(d3_layout_bundlePath(links[i]));return paths;};};function d3_layout_bundlePath(link){var start=link.source,end=link.target,lca=d3_layout_bundleLeastCommonAncestor(start,end),points=[start];while(start!==lca){start=start.parent;points.push(start);}
var k=points.length;while(end!==lca){points.splice(k,0,end);end=end.parent;}
return points;}
function d3_layout_bundleAncestors(node){var ancestors=[],parent=node.parent;while(parent!=null){ancestors.push(node);node=parent;parent=parent.parent;}
ancestors.push(node);return ancestors;}
function d3_layout_bundleLeastCommonAncestor(a,b){if(a===b)return a;var aNodes=d3_layout_bundleAncestors(a),bNodes=d3_layout_bundleAncestors(b),aNode=aNodes.pop(),bNode=bNodes.pop(),sharedNode=null;while(aNode===bNode){sharedNode=aNode;aNode=aNodes.pop();bNode=bNodes.pop();}
return sharedNode;}
d3.layout.chord=function(){var chord={},chords,groups,matrix,n,padding=0,sortGroups,sortSubgroups,sortChords;function relayout(){var subgroups={},groupSums=[],groupIndex=d3.range(n),subgroupIndex=[],k,x,x0,i,j;chords=[];groups=[];k=0,i=-1;while(++i<n){x=0,j=-1;while(++j<n){x+=matrix[i][j];}
groupSums.push(x);subgroupIndex.push(d3.range(n));k+=x;}
if(sortGroups){groupIndex.sort(function(a,b){return sortGroups(groupSums[a],groupSums[b]);});}
if(sortSubgroups){subgroupIndex.forEach(function(d,i){d.sort(function(a,b){return sortSubgroups(matrix[i][a],matrix[i][b]);});});}
k=(2*π-padding*n)/k;x=0,i=-1;while(++i<n){x0=x,j=-1;while(++j<n){var di=groupIndex[i],dj=subgroupIndex[di][j],v=matrix[di][dj],a0=x,a1=x+=v*k;subgroups[di+"-"+dj]={index:di,subindex:dj,startAngle:a0,endAngle:a1,value:v};}
groups[di]={index:di,startAngle:x0,endAngle:x,value:(x-x0)/k};x+=padding;}
i=-1;while(++i<n){j=i-1;while(++j<n){var source=subgroups[i+"-"+j],target=subgroups[j+"-"+i];if(source.value||target.value){chords.push(source.value<target.value?{source:target,target:source}:{source:source,target:target});}}}
if(sortChords)resort();}
function resort(){chords.sort(function(a,b){return sortChords((a.source.value+a.target.value)/2,(b.source.value+b.target.value)/2);});}
chord.matrix=function(x){if(!arguments.length)return matrix;n=(matrix=x)&&matrix.length;chords=groups=null;return chord;};chord.padding=function(x){if(!arguments.length)return padding;padding=x;chords=groups=null;return chord;};chord.sortGroups=function(x){if(!arguments.length)return sortGroups;sortGroups=x;chords=groups=null;return chord;};chord.sortSubgroups=function(x){if(!arguments.length)return sortSubgroups;sortSubgroups=x;chords=null;return chord;};chord.sortChords=function(x){if(!arguments.length)return sortChords;sortChords=x;if(chords)resort();return chord;};chord.chords=function(){if(!chords)relayout();return chords;};chord.groups=function(){if(!groups)relayout();return groups;};return chord;};d3.layout.force=function(){var force={},event=d3.dispatch("start","tick","end"),size=[1,1],drag,alpha,friction=.9,linkDistance=d3_layout_forceLinkDistance,linkStrength=d3_layout_forceLinkStrength,charge=-30,gravity=.1,theta=.8,nodes=[],links=[],distances,strengths,charges;function repulse(node){return function(quad,x1,_,x2){if(quad.point!==node){var dx=quad.cx-node.x,dy=quad.cy-node.y,dn=1/Math.sqrt(dx*dx+dy*dy);if((x2-x1)*dn<theta){var k=quad.charge*dn*dn;node.px-=dx*k;node.py-=dy*k;return true;}
if(quad.point&&isFinite(dn)){var k=quad.pointCharge*dn*dn;node.px-=dx*k;node.py-=dy*k;}}
return!quad.charge;};}
force.tick=function(){if((alpha*=.99)<.005){event.end({type:"end",alpha:alpha=0});return true;}
var n=nodes.length,m=links.length,q,i,o,s,t,l,k,x,y;for(i=0;i<m;++i){o=links[i];s=o.source;t=o.target;x=t.x-s.x;y=t.y-s.y;if(l=x*x+y*y){l=alpha*strengths[i]*((l=Math.sqrt(l))-distances[i])/l;x*=l;y*=l;t.x-=x*(k=s.weight/(t.weight+s.weight));t.y-=y*k;s.x+=x*(k=1-k);s.y+=y*k;}}
if(k=alpha*gravity){x=size[0]/2;y=size[1]/2;i=-1;if(k)while(++i<n){o=nodes[i];o.x+=(x-o.x)*k;o.y+=(y-o.y)*k;}}
if(charge){d3_layout_forceAccumulate(q=d3.geom.quadtree(nodes),alpha,charges);i=-1;while(++i<n){if(!(o=nodes[i]).fixed){q.visit(repulse(o));}}}
i=-1;while(++i<n){o=nodes[i];if(o.fixed){o.x=o.px;o.y=o.py;}else{o.x-=(o.px-(o.px=o.x))*friction;o.y-=(o.py-(o.py=o.y))*friction;}}
event.tick({type:"tick",alpha:alpha});};force.nodes=function(x){if(!arguments.length)return nodes;nodes=x;return force;};force.links=function(x){if(!arguments.length)return links;links=x;return force;};force.size=function(x){if(!arguments.length)return size;size=x;return force;};force.linkDistance=function(x){if(!arguments.length)return linkDistance;linkDistance=typeof x==="function"?x:+x;return force;};force.distance=force.linkDistance;force.linkStrength=function(x){if(!arguments.length)return linkStrength;linkStrength=typeof x==="function"?x:+x;return force;};force.friction=function(x){if(!arguments.length)return friction;friction=+x;return force;};force.charge=function(x){if(!arguments.length)return charge;charge=typeof x==="function"?x:+x;return force;};force.gravity=function(x){if(!arguments.length)return gravity;gravity=+x;return force;};force.theta=function(x){if(!arguments.length)return theta;theta=+x;return force;};force.alpha=function(x){if(!arguments.length)return alpha;x=+x;if(alpha){if(x>0)alpha=x;else alpha=0;}else if(x>0){event.start({type:"start",alpha:alpha=x});d3.timer(force.tick);}
return force;};force.start=function(){var i,j,n=nodes.length,m=links.length,w=size[0],h=size[1],neighbors,o;for(i=0;i<n;++i){(o=nodes[i]).index=i;o.weight=0;}
for(i=0;i<m;++i){o=links[i];if(typeof o.source=="number")o.source=nodes[o.source];if(typeof o.target=="number")o.target=nodes[o.target];++o.source.weight;++o.target.weight;}
for(i=0;i<n;++i){o=nodes[i];if(isNaN(o.x))o.x=position("x",w);if(isNaN(o.y))o.y=position("y",h);if(isNaN(o.px))o.px=o.x;if(isNaN(o.py))o.py=o.y;}
distances=[];if(typeof linkDistance==="function")for(i=0;i<m;++i)distances[i]=+linkDistance.call(this,links[i],i);else for(i=0;i<m;++i)distances[i]=linkDistance;strengths=[];if(typeof linkStrength==="function")for(i=0;i<m;++i)strengths[i]=+linkStrength.call(this,links[i],i);else for(i=0;i<m;++i)strengths[i]=linkStrength;charges=[];if(typeof charge==="function")for(i=0;i<n;++i)charges[i]=+charge.call(this,nodes[i],i);else for(i=0;i<n;++i)charges[i]=charge;function position(dimension,size){var neighbors=neighbor(i),j=-1,m=neighbors.length,x;while(++j<m)if(!isNaN(x=neighbors[j][dimension]))return x;return Math.random()*size;}
function neighbor(){if(!neighbors){neighbors=[];for(j=0;j<n;++j){neighbors[j]=[];}
for(j=0;j<m;++j){var o=links[j];neighbors[o.source.index].push(o.target);neighbors[o.target.index].push(o.source);}}
return neighbors[i];}
return force.resume();};force.resume=function(){return force.alpha(.1);};force.stop=function(){return force.alpha(0);};force.drag=function(){if(!drag)drag=d3.behavior.drag().origin(d3_identity).on("dragstart.force",d3_layout_forceDragstart).on("drag.force",dragmove).on("dragend.force",d3_layout_forceDragend);if(!arguments.length)return drag;this.on("mouseover.force",d3_layout_forceMouseover).on("mouseout.force",d3_layout_forceMouseout).call(drag);};function dragmove(d){d.px=d3.event.x,d.py=d3.event.y;force.resume();}
return d3.rebind(force,event,"on");};function d3_layout_forceDragstart(d){d.fixed|=2;}
function d3_layout_forceDragend(d){d.fixed&=~6;}
function d3_layout_forceMouseover(d){d.fixed|=4;d.px=d.x,d.py=d.y;}
function d3_layout_forceMouseout(d){d.fixed&=~4;}
function d3_layout_forceAccumulate(quad,alpha,charges){var cx=0,cy=0;quad.charge=0;if(!quad.leaf){var nodes=quad.nodes,n=nodes.length,i=-1,c;while(++i<n){c=nodes[i];if(c==null)continue;d3_layout_forceAccumulate(c,alpha,charges);quad.charge+=c.charge;cx+=c.charge*c.cx;cy+=c.charge*c.cy;}}
if(quad.point){if(!quad.leaf){quad.point.x+=Math.random()-.5;quad.point.y+=Math.random()-.5;}
var k=alpha*charges[quad.point.index];quad.charge+=quad.pointCharge=k;cx+=k*quad.point.x;cy+=k*quad.point.y;}
quad.cx=cx/quad.charge;quad.cy=cy/quad.charge;}
var d3_layout_forceLinkDistance=20,d3_layout_forceLinkStrength=1;d3.layout.hierarchy=function(){var sort=d3_layout_hierarchySort,children=d3_layout_hierarchyChildren,value=d3_layout_hierarchyValue;function recurse(node,depth,nodes){var childs=children.call(hierarchy,node,depth);node.depth=depth;nodes.push(node);if(childs&&(n=childs.length)){var i=-1,n,c=node.children=[],v=0,j=depth+1,d;while(++i<n){d=recurse(childs[i],j,nodes);d.parent=node;c.push(d);v+=d.value;}
if(sort)c.sort(sort);if(value)node.value=v;}else if(value){node.value=+value.call(hierarchy,node,depth)||0;}
return node;}
function revalue(node,depth){var children=node.children,v=0;if(children&&(n=children.length)){var i=-1,n,j=depth+1;while(++i<n)v+=revalue(children[i],j);}else if(value){v=+value.call(hierarchy,node,depth)||0;}
if(value)node.value=v;return v;}
function hierarchy(d){var nodes=[];recurse(d,0,nodes);return nodes;}
hierarchy.sort=function(x){if(!arguments.length)return sort;sort=x;return hierarchy;};hierarchy.children=function(x){if(!arguments.length)return children;children=x;return hierarchy;};hierarchy.value=function(x){if(!arguments.length)return value;value=x;return hierarchy;};hierarchy.revalue=function(root){revalue(root,0);return root;};return hierarchy;};function d3_layout_hierarchyRebind(object,hierarchy){d3.rebind(object,hierarchy,"sort","children","value");object.nodes=object;object.links=d3_layout_hierarchyLinks;return object;}
function d3_layout_hierarchyChildren(d){return d.children;}
function d3_layout_hierarchyValue(d){return d.value;}
function d3_layout_hierarchySort(a,b){return b.value-a.value;}
function d3_layout_hierarchyLinks(nodes){return d3.merge(nodes.map(function(parent){return(parent.children||[]).map(function(child){return{source:parent,target:child};});}));}
d3.layout.partition=function(){var hierarchy=d3.layout.hierarchy(),size=[1,1];function position(node,x,dx,dy){var children=node.children;node.x=x;node.y=node.depth*dy;node.dx=dx;node.dy=dy;if(children&&(n=children.length)){var i=-1,n,c,d;dx=node.value?dx/node.value:0;while(++i<n){position(c=children[i],x,d=c.value*dx,dy);x+=d;}}}
function depth(node){var children=node.children,d=0;if(children&&(n=children.length)){var i=-1,n;while(++i<n)d=Math.max(d,depth(children[i]));}
return 1+d;}
function partition(d,i){var nodes=hierarchy.call(this,d,i);position(nodes[0],0,size[0],size[1]/depth(nodes[0]));return nodes;}
partition.size=function(x){if(!arguments.length)return size;size=x;return partition;};return d3_layout_hierarchyRebind(partition,hierarchy);};d3.layout.pie=function(){var value=Number,sort=d3_layout_pieSortByValue,startAngle=0,endAngle=2*π;function pie(data){var values=data.map(function(d,i){return+value.call(pie,d,i);});var a=+(typeof startAngle==="function"?startAngle.apply(this,arguments):startAngle);var k=((typeof endAngle==="function"?endAngle.apply(this,arguments):endAngle)-a)/d3.sum(values);var index=d3.range(data.length);if(sort!=null)index.sort(sort===d3_layout_pieSortByValue?function(i,j){return values[j]-values[i];}:function(i,j){return sort(data[i],data[j]);});var arcs=[];index.forEach(function(i){var d;arcs[i]={data:data[i],value:d=values[i],startAngle:a,endAngle:a+=d*k};});return arcs;}
pie.value=function(x){if(!arguments.length)return value;value=x;return pie;};pie.sort=function(x){if(!arguments.length)return sort;sort=x;return pie;};pie.startAngle=function(x){if(!arguments.length)return startAngle;startAngle=x;return pie;};pie.endAngle=function(x){if(!arguments.length)return endAngle;endAngle=x;return pie;};return pie;};var d3_layout_pieSortByValue={};d3.layout.stack=function(){var values=d3_identity,order=d3_layout_stackOrderDefault,offset=d3_layout_stackOffsetZero,out=d3_layout_stackOut,x=d3_layout_stackX,y=d3_layout_stackY;function stack(data,index){var series=data.map(function(d,i){return values.call(stack,d,i);});var points=series.map(function(d){return d.map(function(v,i){return[x.call(stack,v,i),y.call(stack,v,i)];});});var orders=order.call(stack,points,index);series=d3.permute(series,orders);points=d3.permute(points,orders);var offsets=offset.call(stack,points,index);var n=series.length,m=series[0].length,i,j,o;for(j=0;j<m;++j){out.call(stack,series[0][j],o=offsets[j],points[0][j][1]);for(i=1;i<n;++i){out.call(stack,series[i][j],o+=points[i-1][j][1],points[i][j][1]);}}
return data;}
stack.values=function(x){if(!arguments.length)return values;values=x;return stack;};stack.order=function(x){if(!arguments.length)return order;order=typeof x==="function"?x:d3_layout_stackOrders.get(x)||d3_layout_stackOrderDefault;return stack;};stack.offset=function(x){if(!arguments.length)return offset;offset=typeof x==="function"?x:d3_layout_stackOffsets.get(x)||d3_layout_stackOffsetZero;return stack;};stack.x=function(z){if(!arguments.length)return x;x=z;return stack;};stack.y=function(z){if(!arguments.length)return y;y=z;return stack;};stack.out=function(z){if(!arguments.length)return out;out=z;return stack;};return stack;};function d3_layout_stackX(d){return d.x;}
function d3_layout_stackY(d){return d.y;}
function d3_layout_stackOut(d,y0,y){d.y0=y0;d.y=y;}
var d3_layout_stackOrders=d3.map({"inside-out":function(data){var n=data.length,i,j,max=data.map(d3_layout_stackMaxIndex),sums=data.map(d3_layout_stackReduceSum),index=d3.range(n).sort(function(a,b){return max[a]-max[b];}),top=0,bottom=0,tops=[],bottoms=[];for(i=0;i<n;++i){j=index[i];if(top<bottom){top+=sums[j];tops.push(j);}else{bottom+=sums[j];bottoms.push(j);}}
return bottoms.reverse().concat(tops);},reverse:function(data){return d3.range(data.length).reverse();},"default":d3_layout_stackOrderDefault});var d3_layout_stackOffsets=d3.map({silhouette:function(data){var n=data.length,m=data[0].length,sums=[],max=0,i,j,o,y0=[];for(j=0;j<m;++j){for(i=0,o=0;i<n;i++)o+=data[i][j][1];if(o>max)max=o;sums.push(o);}
for(j=0;j<m;++j){y0[j]=(max-sums[j])/2;}
return y0;},wiggle:function(data){var n=data.length,x=data[0],m=x.length,i,j,k,s1,s2,s3,dx,o,o0,y0=[];y0[0]=o=o0=0;for(j=1;j<m;++j){for(i=0,s1=0;i<n;++i)s1+=data[i][j][1];for(i=0,s2=0,dx=x[j][0]-x[j-1][0];i<n;++i){for(k=0,s3=(data[i][j][1]-data[i][j-1][1])/(2*dx);k<i;++k){s3+=(data[k][j][1]-data[k][j-1][1])/dx;}
s2+=s3*data[i][j][1];}
y0[j]=o-=s1?s2/s1*dx:0;if(o<o0)o0=o;}
for(j=0;j<m;++j)y0[j]-=o0;return y0;},expand:function(data){var n=data.length,m=data[0].length,k=1/n,i,j,o,y0=[];for(j=0;j<m;++j){for(i=0,o=0;i<n;i++)o+=data[i][j][1];if(o)for(i=0;i<n;i++)data[i][j][1]/=o;else for(i=0;i<n;i++)data[i][j][1]=k;}
for(j=0;j<m;++j)y0[j]=0;return y0;},zero:d3_layout_stackOffsetZero});function d3_layout_stackOrderDefault(data){return d3.range(data.length);}
function d3_layout_stackOffsetZero(data){var j=-1,m=data[0].length,y0=[];while(++j<m)y0[j]=0;return y0;}
function d3_layout_stackMaxIndex(array){var i=1,j=0,v=array[0][1],k,n=array.length;for(;i<n;++i){if((k=array[i][1])>v){j=i;v=k;}}
return j;}
function d3_layout_stackReduceSum(d){return d.reduce(d3_layout_stackSum,0);}
function d3_layout_stackSum(p,d){return p+d[1];}
d3.layout.histogram=function(){var frequency=true,valuer=Number,ranger=d3_layout_histogramRange,binner=d3_layout_histogramBinSturges;function histogram(data,i){var bins=[],values=data.map(valuer,this),range=ranger.call(this,values,i),thresholds=binner.call(this,range,values,i),bin,i=-1,n=values.length,m=thresholds.length-1,k=frequency?1:1/n,x;while(++i<m){bin=bins[i]=[];bin.dx=thresholds[i+1]-(bin.x=thresholds[i]);bin.y=0;}
if(m>0){i=-1;while(++i<n){x=values[i];if(x>=range[0]&&x<=range[1]){bin=bins[d3.bisect(thresholds,x,1,m)-1];bin.y+=k;bin.push(data[i]);}}}
return bins;}
histogram.value=function(x){if(!arguments.length)return valuer;valuer=x;return histogram;};histogram.range=function(x){if(!arguments.length)return ranger;ranger=d3_functor(x);return histogram;};histogram.bins=function(x){if(!arguments.length)return binner;binner=typeof x==="number"?function(range){return d3_layout_histogramBinFixed(range,x);}:d3_functor(x);return histogram;};histogram.frequency=function(x){if(!arguments.length)return frequency;frequency=!!x;return histogram;};return histogram;};function d3_layout_histogramBinSturges(range,values){return d3_layout_histogramBinFixed(range,Math.ceil(Math.log(values.length)/Math.LN2+1));}
function d3_layout_histogramBinFixed(range,n){var x=-1,b=+range[0],m=(range[1]-b)/n,f=[];while(++x<=n)f[x]=m*x+b;return f;}
function d3_layout_histogramRange(values){return[d3.min(values),d3.max(values)];}
d3.layout.tree=function(){var hierarchy=d3.layout.hierarchy().sort(null).value(null),separation=d3_layout_treeSeparation,size=[1,1];function tree(d,i){var nodes=hierarchy.call(this,d,i),root=nodes[0];function firstWalk(node,previousSibling){var children=node.children,layout=node._tree;if(children&&(n=children.length)){var n,firstChild=children[0],previousChild,ancestor=firstChild,child,i=-1;while(++i<n){child=children[i];firstWalk(child,previousChild);ancestor=apportion(child,previousChild,ancestor);previousChild=child;}
d3_layout_treeShift(node);var midpoint=.5*(firstChild._tree.prelim+child._tree.prelim);if(previousSibling){layout.prelim=previousSibling._tree.prelim+separation(node,previousSibling);layout.mod=layout.prelim-midpoint;}else{layout.prelim=midpoint;}}else{if(previousSibling){layout.prelim=previousSibling._tree.prelim+separation(node,previousSibling);}}}
function secondWalk(node,x){node.x=node._tree.prelim+x;var children=node.children;if(children&&(n=children.length)){var i=-1,n;x+=node._tree.mod;while(++i<n){secondWalk(children[i],x);}}}
function apportion(node,previousSibling,ancestor){if(previousSibling){var vip=node,vop=node,vim=previousSibling,vom=node.parent.children[0],sip=vip._tree.mod,sop=vop._tree.mod,sim=vim._tree.mod,som=vom._tree.mod,shift;while(vim=d3_layout_treeRight(vim),vip=d3_layout_treeLeft(vip),vim&&vip){vom=d3_layout_treeLeft(vom);vop=d3_layout_treeRight(vop);vop._tree.ancestor=node;shift=vim._tree.prelim+sim-vip._tree.prelim-sip+separation(vim,vip);if(shift>0){d3_layout_treeMove(d3_layout_treeAncestor(vim,node,ancestor),node,shift);sip+=shift;sop+=shift;}
sim+=vim._tree.mod;sip+=vip._tree.mod;som+=vom._tree.mod;sop+=vop._tree.mod;}
if(vim&&!d3_layout_treeRight(vop)){vop._tree.thread=vim;vop._tree.mod+=sim-sop;}
if(vip&&!d3_layout_treeLeft(vom)){vom._tree.thread=vip;vom._tree.mod+=sip-som;ancestor=node;}}
return ancestor;}
d3_layout_treeVisitAfter(root,function(node,previousSibling){node._tree={ancestor:node,prelim:0,mod:0,change:0,shift:0,number:previousSibling?previousSibling._tree.number+1:0};});firstWalk(root);secondWalk(root,-root._tree.prelim);var left=d3_layout_treeSearch(root,d3_layout_treeLeftmost),right=d3_layout_treeSearch(root,d3_layout_treeRightmost),deep=d3_layout_treeSearch(root,d3_layout_treeDeepest),x0=left.x-separation(left,right)/2,x1=right.x+separation(right,left)/2,y1=deep.depth||1;d3_layout_treeVisitAfter(root,function(node){node.x=(node.x-x0)/(x1-x0)*size[0];node.y=node.depth/y1*size[1];delete node._tree;});return nodes;}
tree.separation=function(x){if(!arguments.length)return separation;separation=x;return tree;};tree.size=function(x){if(!arguments.length)return size;size=x;return tree;};return d3_layout_hierarchyRebind(tree,hierarchy);};function d3_layout_treeSeparation(a,b){return a.parent==b.parent?1:2;}
function d3_layout_treeLeft(node){var children=node.children;return children&&children.length?children[0]:node._tree.thread;}
function d3_layout_treeRight(node){var children=node.children,n;return children&&(n=children.length)?children[n-1]:node._tree.thread;}
function d3_layout_treeSearch(node,compare){var children=node.children;if(children&&(n=children.length)){var child,n,i=-1;while(++i<n){if(compare(child=d3_layout_treeSearch(children[i],compare),node)>0){node=child;}}}
return node;}
function d3_layout_treeRightmost(a,b){return a.x-b.x;}
function d3_layout_treeLeftmost(a,b){return b.x-a.x;}
function d3_layout_treeDeepest(a,b){return a.depth-b.depth;}
function d3_layout_treeVisitAfter(node,callback){function visit(node,previousSibling){var children=node.children;if(children&&(n=children.length)){var child,previousChild=null,i=-1,n;while(++i<n){child=children[i];visit(child,previousChild);previousChild=child;}}
callback(node,previousSibling);}
visit(node,null);}
function d3_layout_treeShift(node){var shift=0,change=0,children=node.children,i=children.length,child;while(--i>=0){child=children[i]._tree;child.prelim+=shift;child.mod+=shift;shift+=child.shift+(change+=child.change);}}
function d3_layout_treeMove(ancestor,node,shift){ancestor=ancestor._tree;node=node._tree;var change=shift/(node.number-ancestor.number);ancestor.change+=change;node.change-=change;node.shift+=shift;node.prelim+=shift;node.mod+=shift;}
function d3_layout_treeAncestor(vim,node,ancestor){return vim._tree.ancestor.parent==node.parent?vim._tree.ancestor:ancestor;}
d3.layout.pack=function(){var hierarchy=d3.layout.hierarchy().sort(d3_layout_packSort),padding=0,size=[1,1];function pack(d,i){var nodes=hierarchy.call(this,d,i),root=nodes[0];root.x=0;root.y=0;d3_layout_treeVisitAfter(root,function(d){d.r=Math.sqrt(d.value);});d3_layout_treeVisitAfter(root,d3_layout_packSiblings);var w=size[0],h=size[1],k=Math.max(2*root.r/w,2*root.r/h);if(padding>0){var dr=padding*k/2;d3_layout_treeVisitAfter(root,function(d){d.r+=dr;});d3_layout_treeVisitAfter(root,d3_layout_packSiblings);d3_layout_treeVisitAfter(root,function(d){d.r-=dr;});k=Math.max(2*root.r/w,2*root.r/h);}
d3_layout_packTransform(root,w/2,h/2,1/k);return nodes;}
pack.size=function(x){if(!arguments.length)return size;size=x;return pack;};pack.padding=function(_){if(!arguments.length)return padding;padding=+_;return pack;};return d3_layout_hierarchyRebind(pack,hierarchy);};function d3_layout_packSort(a,b){return a.value-b.value;}
function d3_layout_packInsert(a,b){var c=a._pack_next;a._pack_next=b;b._pack_prev=a;b._pack_next=c;c._pack_prev=b;}
function d3_layout_packSplice(a,b){a._pack_next=b;b._pack_prev=a;}
function d3_layout_packIntersects(a,b){var dx=b.x-a.x,dy=b.y-a.y,dr=a.r+b.r;return dr*dr-dx*dx-dy*dy>.001;}
function d3_layout_packSiblings(node){if(!(nodes=node.children)||!(n=nodes.length))return;var nodes,xMin=Infinity,xMax=-Infinity,yMin=Infinity,yMax=-Infinity,a,b,c,i,j,k,n;function bound(node){xMin=Math.min(node.x-node.r,xMin);xMax=Math.max(node.x+node.r,xMax);yMin=Math.min(node.y-node.r,yMin);yMax=Math.max(node.y+node.r,yMax);}
nodes.forEach(d3_layout_packLink);a=nodes[0];a.x=-a.r;a.y=0;bound(a);if(n>1){b=nodes[1];b.x=b.r;b.y=0;bound(b);if(n>2){c=nodes[2];d3_layout_packPlace(a,b,c);bound(c);d3_layout_packInsert(a,c);a._pack_prev=c;d3_layout_packInsert(c,b);b=a._pack_next;for(i=3;i<n;i++){d3_layout_packPlace(a,b,c=nodes[i]);var isect=0,s1=1,s2=1;for(j=b._pack_next;j!==b;j=j._pack_next,s1++){if(d3_layout_packIntersects(j,c)){isect=1;break;}}
if(isect==1){for(k=a._pack_prev;k!==j._pack_prev;k=k._pack_prev,s2++){if(d3_layout_packIntersects(k,c)){break;}}}
if(isect){if(s1<s2||s1==s2&&b.r<a.r)d3_layout_packSplice(a,b=j);else d3_layout_packSplice(a=k,b);i--;}else{d3_layout_packInsert(a,c);b=c;bound(c);}}}}
var cx=(xMin+xMax)/2,cy=(yMin+yMax)/2,cr=0;for(i=0;i<n;i++){c=nodes[i];c.x-=cx;c.y-=cy;cr=Math.max(cr,c.r+Math.sqrt(c.x*c.x+c.y*c.y));}
node.r=cr;nodes.forEach(d3_layout_packUnlink);}
function d3_layout_packLink(node){node._pack_next=node._pack_prev=node;}
function d3_layout_packUnlink(node){delete node._pack_next;delete node._pack_prev;}
function d3_layout_packTransform(node,x,y,k){var children=node.children;node.x=x+=k*node.x;node.y=y+=k*node.y;node.r*=k;if(children){var i=-1,n=children.length;while(++i<n)d3_layout_packTransform(children[i],x,y,k);}}
function d3_layout_packPlace(a,b,c){var db=a.r+c.r,dx=b.x-a.x,dy=b.y-a.y;if(db&&(dx||dy)){var da=b.r+c.r,dc=dx*dx+dy*dy;da*=da;db*=db;var x=.5+(db-da)/(2*dc),y=Math.sqrt(Math.max(0,2*da*(db+dc)-(db-=dc)*db-da*da))/(2*dc);c.x=a.x+x*dx+y*dy;c.y=a.y+x*dy-y*dx;}else{c.x=a.x+db;c.y=a.y;}}
d3.layout.cluster=function(){var hierarchy=d3.layout.hierarchy().sort(null).value(null),separation=d3_layout_treeSeparation,size=[1,1];function cluster(d,i){var nodes=hierarchy.call(this,d,i),root=nodes[0],previousNode,x=0;d3_layout_treeVisitAfter(root,function(node){var children=node.children;if(children&&children.length){node.x=d3_layout_clusterX(children);node.y=d3_layout_clusterY(children);}else{node.x=previousNode?x+=separation(node,previousNode):0;node.y=0;previousNode=node;}});var left=d3_layout_clusterLeft(root),right=d3_layout_clusterRight(root),x0=left.x-separation(left,right)/2,x1=right.x+separation(right,left)/2;d3_layout_treeVisitAfter(root,function(node){node.x=(node.x-x0)/(x1-x0)*size[0];node.y=(1-(root.y?node.y/root.y:1))*size[1];});return nodes;}
cluster.separation=function(x){if(!arguments.length)return separation;separation=x;return cluster;};cluster.size=function(x){if(!arguments.length)return size;size=x;return cluster;};return d3_layout_hierarchyRebind(cluster,hierarchy);};function d3_layout_clusterY(children){return 1+d3.max(children,function(child){return child.y;});}
function d3_layout_clusterX(children){return children.reduce(function(x,child){return x+child.x;},0)/children.length;}
function d3_layout_clusterLeft(node){var children=node.children;return children&&children.length?d3_layout_clusterLeft(children[0]):node;}
function d3_layout_clusterRight(node){var children=node.children,n;return children&&(n=children.length)?d3_layout_clusterRight(children[n-1]):node;}
d3.layout.treemap=function(){var hierarchy=d3.layout.hierarchy(),round=Math.round,size=[1,1],padding=null,pad=d3_layout_treemapPadNull,sticky=false,stickies,mode="squarify",ratio=.5*(1+Math.sqrt(5));function scale(children,k){var i=-1,n=children.length,child,area;while(++i<n){area=(child=children[i]).value*(k<0?0:k);child.area=isNaN(area)||area<=0?0:area;}}
function squarify(node){var children=node.children;if(children&&children.length){var rect=pad(node),row=[],remaining=children.slice(),child,best=Infinity,score,u=mode==="slice"?rect.dx:mode==="dice"?rect.dy:mode==="slice-dice"?node.depth&1?rect.dy:rect.dx:Math.min(rect.dx,rect.dy),n;scale(remaining,rect.dx*rect.dy/node.value);row.area=0;while((n=remaining.length)>0){row.push(child=remaining[n-1]);row.area+=child.area;if(mode!=="squarify"||(score=worst(row,u))<=best){remaining.pop();best=score;}else{row.area-=row.pop().area;position(row,u,rect,false);u=Math.min(rect.dx,rect.dy);row.length=row.area=0;best=Infinity;}}
if(row.length){position(row,u,rect,true);row.length=row.area=0;}
children.forEach(squarify);}}
function stickify(node){var children=node.children;if(children&&children.length){var rect=pad(node),remaining=children.slice(),child,row=[];scale(remaining,rect.dx*rect.dy/node.value);row.area=0;while(child=remaining.pop()){row.push(child);row.area+=child.area;if(child.z!=null){position(row,child.z?rect.dx:rect.dy,rect,!remaining.length);row.length=row.area=0;}}
children.forEach(stickify);}}
function worst(row,u){var s=row.area,r,rmax=0,rmin=Infinity,i=-1,n=row.length;while(++i<n){if(!(r=row[i].area))continue;if(r<rmin)rmin=r;if(r>rmax)rmax=r;}
s*=s;u*=u;return s?Math.max(u*rmax*ratio/s,s/(u*rmin*ratio)):Infinity;}
function position(row,u,rect,flush){var i=-1,n=row.length,x=rect.x,y=rect.y,v=u?round(row.area/u):0,o;if(u==rect.dx){if(flush||v>rect.dy)v=rect.dy;while(++i<n){o=row[i];o.x=x;o.y=y;o.dy=v;x+=o.dx=Math.min(rect.x+rect.dx-x,v?round(o.area/v):0);}
o.z=true;o.dx+=rect.x+rect.dx-x;rect.y+=v;rect.dy-=v;}else{if(flush||v>rect.dx)v=rect.dx;while(++i<n){o=row[i];o.x=x;o.y=y;o.dx=v;y+=o.dy=Math.min(rect.y+rect.dy-y,v?round(o.area/v):0);}
o.z=false;o.dy+=rect.y+rect.dy-y;rect.x+=v;rect.dx-=v;}}
function treemap(d){var nodes=stickies||hierarchy(d),root=nodes[0];root.x=0;root.y=0;root.dx=size[0];root.dy=size[1];if(stickies)hierarchy.revalue(root);scale([root],root.dx*root.dy/root.value);(stickies?stickify:squarify)(root);if(sticky)stickies=nodes;return nodes;}
treemap.size=function(x){if(!arguments.length)return size;size=x;return treemap;};treemap.padding=function(x){if(!arguments.length)return padding;function padFunction(node){var p=x.call(treemap,node,node.depth);return p==null?d3_layout_treemapPadNull(node):d3_layout_treemapPad(node,typeof p==="number"?[p,p,p,p]:p);}
function padConstant(node){return d3_layout_treemapPad(node,x);}
var type;pad=(padding=x)==null?d3_layout_treemapPadNull:(type=typeof x)==="function"?padFunction:type==="number"?(x=[x,x,x,x],padConstant):padConstant;return treemap;};treemap.round=function(x){if(!arguments.length)return round!=Number;round=x?Math.round:Number;return treemap;};treemap.sticky=function(x){if(!arguments.length)return sticky;sticky=x;stickies=null;return treemap;};treemap.ratio=function(x){if(!arguments.length)return ratio;ratio=x;return treemap;};treemap.mode=function(x){if(!arguments.length)return mode;mode=x+"";return treemap;};return d3_layout_hierarchyRebind(treemap,hierarchy);};function d3_layout_treemapPadNull(node){return{x:node.x,y:node.y,dx:node.dx,dy:node.dy};}
function d3_layout_treemapPad(node,padding){var x=node.x+padding[3],y=node.y+padding[0],dx=node.dx-padding[1]-padding[3],dy=node.dy-padding[0]-padding[2];if(dx<0){x+=dx/2;dx=0;}
if(dy<0){y+=dy/2;dy=0;}
return{x:x,y:y,dx:dx,dy:dy};}
d3.random={normal:function(µ,σ){var n=arguments.length;if(n<2)σ=1;if(n<1)µ=0;return function(){var x,y,r;do{x=Math.random()*2-1;y=Math.random()*2-1;r=x*x+y*y;}while(!r||r>1);return µ+σ*x*Math.sqrt(-2*Math.log(r)/r);};},logNormal:function(){var random=d3.random.normal.apply(d3,arguments);return function(){return Math.exp(random());};},irwinHall:function(m){return function(){for(var s=0,j=0;j<m;j++)s+=Math.random();return s/m;};}};d3.scale={};function d3_scaleExtent(domain){var start=domain[0],stop=domain[domain.length-1];return start<stop?[start,stop]:[stop,start];}
function d3_scaleRange(scale){return scale.rangeExtent?scale.rangeExtent():d3_scaleExtent(scale.range());}
function d3_scale_bilinear(domain,range,uninterpolate,interpolate){var u=uninterpolate(domain[0],domain[1]),i=interpolate(range[0],range[1]);return function(x){return i(u(x));};}
function d3_scale_nice(domain,nice){var i0=0,i1=domain.length-1,x0=domain[i0],x1=domain[i1],dx;if(x1<x0){dx=i0,i0=i1,i1=dx;dx=x0,x0=x1,x1=dx;}
if(nice=nice(x1-x0)){domain[i0]=nice.floor(x0);domain[i1]=nice.ceil(x1);}
return domain;}
function d3_scale_polylinear(domain,range,uninterpolate,interpolate){var u=[],i=[],j=0,k=Math.min(domain.length,range.length)-1;if(domain[k]<domain[0]){domain=domain.slice().reverse();range=range.slice().reverse();}
while(++j<=k){u.push(uninterpolate(domain[j-1],domain[j]));i.push(interpolate(range[j-1],range[j]));}
return function(x){var j=d3.bisect(domain,x,1,k)-1;return i[j](u[j](x));};}
d3.scale.linear=function(){return d3_scale_linear([0,1],[0,1],d3_interpolate,false);};function d3_scale_linear(domain,range,interpolate,clamp){var output,input;function rescale(){var linear=Math.min(domain.length,range.length)>2?d3_scale_polylinear:d3_scale_bilinear,uninterpolate=clamp?d3_uninterpolateClamp:d3_uninterpolateNumber;output=linear(domain,range,uninterpolate,interpolate);input=linear(range,domain,uninterpolate,d3_interpolate);return scale;}
function scale(x){return output(x);}
scale.invert=function(y){return input(y);};scale.domain=function(x){if(!arguments.length)return domain;domain=x.map(Number);return rescale();};scale.range=function(x){if(!arguments.length)return range;range=x;return rescale();};scale.rangeRound=function(x){return scale.range(x).interpolate(d3_interpolateRound);};scale.clamp=function(x){if(!arguments.length)return clamp;clamp=x;return rescale();};scale.interpolate=function(x){if(!arguments.length)return interpolate;interpolate=x;return rescale();};scale.ticks=function(m){return d3_scale_linearTicks(domain,m);};scale.tickFormat=function(m,format){return d3_scale_linearTickFormat(domain,m,format);};scale.nice=function(){d3_scale_nice(domain,d3_scale_linearNice);return rescale();};scale.copy=function(){return d3_scale_linear(domain,range,interpolate,clamp);};return rescale();}
function d3_scale_linearRebind(scale,linear){return d3.rebind(scale,linear,"range","rangeRound","interpolate","clamp");}
function d3_scale_linearNice(dx){dx=Math.pow(10,Math.round(Math.log(dx)/Math.LN10)-1);return dx&&{floor:function(x){return Math.floor(x/dx)*dx;},ceil:function(x){return Math.ceil(x/dx)*dx;}};}
function d3_scale_linearTickRange(domain,m){var extent=d3_scaleExtent(domain),span=extent[1]-extent[0],step=Math.pow(10,Math.floor(Math.log(span/m)/Math.LN10)),err=m/span*step;if(err<=.15)step*=10;else if(err<=.35)step*=5;else if(err<=.75)step*=2;extent[0]=Math.ceil(extent[0]/step)*step;extent[1]=Math.floor(extent[1]/step)*step+step*.5;extent[2]=step;return extent;}
function d3_scale_linearTicks(domain,m){return d3.range.apply(d3,d3_scale_linearTickRange(domain,m));}
function d3_scale_linearTickFormat(domain,m,format){var precision=-Math.floor(Math.log(d3_scale_linearTickRange(domain,m)[2])/Math.LN10+.01);return d3.format(format?format.replace(d3_format_re,function(a,b,c,d,e,f,g,h,i,j){return[b,c,d,e,f,g,h,i||"."+(precision-(j==="%")*2),j].join("");}):",."+precision+"f");}
d3.scale.log=function(){return d3_scale_log(d3.scale.linear().domain([0,Math.LN10]),10,d3_scale_logp,d3_scale_powp);};function d3_scale_log(linear,base,log,pow){function scale(x){return linear(log(x));}
scale.invert=function(x){return pow(linear.invert(x));};scale.domain=function(x){if(!arguments.length)return linear.domain().map(pow);if(x[0]<0)log=d3_scale_logn,pow=d3_scale_pown;else log=d3_scale_logp,pow=d3_scale_powp;linear.domain(x.map(log));return scale;};scale.base=function(_){if(!arguments.length)return base;base=+_;return scale;};scale.nice=function(){linear.domain(d3_scale_nice(linear.domain(),d3_scale_logNice(base)));return scale;};scale.ticks=function(){var extent=d3_scaleExtent(linear.domain()),ticks=[];if(extent.every(isFinite)){var b=Math.log(base),i=Math.floor(extent[0]/b),j=Math.ceil(extent[1]/b),u=pow(extent[0]),v=pow(extent[1]),n=base%1?2:base;if(log===d3_scale_logn){ticks.push(-Math.pow(base,-i));for(;i++<j;)for(var k=n-1;k>0;k--)ticks.push(-Math.pow(base,-i)*k);}else{for(;i<j;i++)for(var k=1;k<n;k++)ticks.push(Math.pow(base,i)*k);ticks.push(Math.pow(base,i));}
for(i=0;ticks[i]<u;i++){}
for(j=ticks.length;ticks[j-1]>v;j--){}
ticks=ticks.slice(i,j);}
return ticks;};scale.tickFormat=function(n,format){if(arguments.length<2)format=d3_scale_logFormat;if(!arguments.length)return format;var b=Math.log(base),k=Math.max(.1,n/scale.ticks().length),f=log===d3_scale_logn?(e=-1e-12,Math.floor):(e=1e-12,Math.ceil),e;return function(d){return d/pow(b*f(log(d)/b+e))<=k?format(d):"";};};scale.copy=function(){return d3_scale_log(linear.copy(),base,log,pow);};return d3_scale_linearRebind(scale,linear);}
var d3_scale_logFormat=d3.format(".0e");function d3_scale_logp(x){return Math.log(x<0?0:x);}
function d3_scale_powp(x){return Math.exp(x);}
function d3_scale_logn(x){return-Math.log(x>0?0:-x);}
function d3_scale_pown(x){return-Math.exp(-x);}
function d3_scale_logNice(base){base=Math.log(base);var nice={floor:function(x){return Math.floor(x/base)*base;},ceil:function(x){return Math.ceil(x/base)*base;}};return function(){return nice;};}
d3.scale.pow=function(){return d3_scale_pow(d3.scale.linear(),1);};function d3_scale_pow(linear,exponent){var powp=d3_scale_powPow(exponent),powb=d3_scale_powPow(1/exponent);function scale(x){return linear(powp(x));}
scale.invert=function(x){return powb(linear.invert(x));};scale.domain=function(x){if(!arguments.length)return linear.domain().map(powb);linear.domain(x.map(powp));return scale;};scale.ticks=function(m){return d3_scale_linearTicks(scale.domain(),m);};scale.tickFormat=function(m,format){return d3_scale_linearTickFormat(scale.domain(),m,format);};scale.nice=function(){return scale.domain(d3_scale_nice(scale.domain(),d3_scale_linearNice));};scale.exponent=function(x){if(!arguments.length)return exponent;var domain=scale.domain();powp=d3_scale_powPow(exponent=x);powb=d3_scale_powPow(1/exponent);return scale.domain(domain);};scale.copy=function(){return d3_scale_pow(linear.copy(),exponent);};return d3_scale_linearRebind(scale,linear);}
function d3_scale_powPow(e){return function(x){return x<0?-Math.pow(-x,e):Math.pow(x,e);};}
d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5);};d3.scale.ordinal=function(){return d3_scale_ordinal([],{t:"range",a:[[]]});};function d3_scale_ordinal(domain,ranger){var index,range,rangeBand;function scale(x){return range[((index.get(x)||index.set(x,domain.push(x)))-1)%range.length];}
function steps(start,step){return d3.range(domain.length).map(function(i){return start+step*i;});}
scale.domain=function(x){if(!arguments.length)return domain;domain=[];index=new d3_Map();var i=-1,n=x.length,xi;while(++i<n)if(!index.has(xi=x[i]))index.set(xi,domain.push(xi));return scale[ranger.t].apply(scale,ranger.a);};scale.range=function(x){if(!arguments.length)return range;range=x;rangeBand=0;ranger={t:"range",a:arguments};return scale;};scale.rangePoints=function(x,padding){if(arguments.length<2)padding=0;var start=x[0],stop=x[1],step=(stop-start)/(Math.max(1,domain.length-1)+padding);range=steps(domain.length<2?(start+stop)/2:start+step*padding/2,step);rangeBand=0;ranger={t:"rangePoints",a:arguments};return scale;};scale.rangeBands=function(x,padding,outerPadding){if(arguments.length<2)padding=0;if(arguments.length<3)outerPadding=padding;var reverse=x[1]<x[0],start=x[reverse-0],stop=x[1-reverse],step=(stop-start)/(domain.length-padding+2*outerPadding);range=steps(start+step*outerPadding,step);if(reverse)range.reverse();rangeBand=step*(1-padding);ranger={t:"rangeBands",a:arguments};return scale;};scale.rangeRoundBands=function(x,padding,outerPadding){if(arguments.length<2)padding=0;if(arguments.length<3)outerPadding=padding;var reverse=x[1]<x[0],start=x[reverse-0],stop=x[1-reverse],step=Math.floor((stop-start)/(domain.length-padding+2*outerPadding)),error=stop-start-(domain.length-padding)*step;range=steps(start+Math.round(error/2),step);if(reverse)range.reverse();rangeBand=Math.round(step*(1-padding));ranger={t:"rangeRoundBands",a:arguments};return scale;};scale.rangeBand=function(){return rangeBand;};scale.rangeExtent=function(){return d3_scaleExtent(ranger.a[0]);};scale.copy=function(){return d3_scale_ordinal(domain,ranger);};return scale.domain(domain);}
d3.scale.category10=function(){return d3.scale.ordinal().range(d3_category10);};d3.scale.category20=function(){return d3.scale.ordinal().range(d3_category20);};d3.scale.category20b=function(){return d3.scale.ordinal().range(d3_category20b);};d3.scale.category20c=function(){return d3.scale.ordinal().range(d3_category20c);};var d3_category10=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"];var d3_category20=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];var d3_category20b=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"];var d3_category20c=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){return d3_scale_quantile([],[]);};function d3_scale_quantile(domain,range){var thresholds;function rescale(){var k=0,q=range.length;thresholds=[];while(++k<q)thresholds[k-1]=d3.quantile(domain,k/q);return scale;}
function scale(x){if(isNaN(x=+x))return NaN;return range[d3.bisect(thresholds,x)];}
scale.domain=function(x){if(!arguments.length)return domain;domain=x.filter(function(d){return!isNaN(d);}).sort(d3.ascending);return rescale();};scale.range=function(x){if(!arguments.length)return range;range=x;return rescale();};scale.quantiles=function(){return thresholds;};scale.copy=function(){return d3_scale_quantile(domain,range);};return rescale();}
d3.scale.quantize=function(){return d3_scale_quantize(0,1,[0,1]);};function d3_scale_quantize(x0,x1,range){var kx,i;function scale(x){return range[Math.max(0,Math.min(i,Math.floor(kx*(x-x0))))];}
function rescale(){kx=range.length/(x1-x0);i=range.length-1;return scale;}
scale.domain=function(x){if(!arguments.length)return[x0,x1];x0=+x[0];x1=+x[x.length-1];return rescale();};scale.range=function(x){if(!arguments.length)return range;range=x;return rescale();};scale.copy=function(){return d3_scale_quantize(x0,x1,range);};return rescale();}
d3.scale.threshold=function(){return d3_scale_threshold([.5],[0,1]);};function d3_scale_threshold(domain,range){function scale(x){return range[d3.bisect(domain,x)];}
scale.domain=function(_){if(!arguments.length)return domain;domain=_;return scale;};scale.range=function(_){if(!arguments.length)return range;range=_;return scale;};scale.copy=function(){return d3_scale_threshold(domain,range);};return scale;}
d3.scale.identity=function(){return d3_scale_identity([0,1]);};function d3_scale_identity(domain){function identity(x){return+x;}
identity.invert=identity;identity.domain=identity.range=function(x){if(!arguments.length)return domain;domain=x.map(identity);return identity;};identity.ticks=function(m){return d3_scale_linearTicks(domain,m);};identity.tickFormat=function(m,format){return d3_scale_linearTickFormat(domain,m,format);};identity.copy=function(){return d3_scale_identity(domain);};return identity;}
d3.svg.arc=function(){var innerRadius=d3_svg_arcInnerRadius,outerRadius=d3_svg_arcOuterRadius,startAngle=d3_svg_arcStartAngle,endAngle=d3_svg_arcEndAngle;function arc(){var r0=innerRadius.apply(this,arguments),r1=outerRadius.apply(this,arguments),a0=startAngle.apply(this,arguments)+d3_svg_arcOffset,a1=endAngle.apply(this,arguments)+d3_svg_arcOffset,da=(a1<a0&&(da=a0,a0=a1,a1=da),a1-a0),df=da<π?"0":"1",c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);return da>=d3_svg_arcMax?r0?"M0,"+r1+"A"+r1+","+r1+" 0 1,1 0,"+-r1+"A"+r1+","+r1+" 0 1,1 0,"+r1+"M0,"+r0+"A"+r0+","+r0+" 0 1,0 0,"+-r0+"A"+r0+","+r0+" 0 1,0 0,"+r0+"Z":"M0,"+r1+"A"+r1+","+r1+" 0 1,1 0,"+-r1+"A"+r1+","+r1+" 0 1,1 0,"+r1+"Z":r0?"M"+r1*c0+","+r1*s0+"A"+r1+","+r1+" 0 "+df+",1 "+r1*c1+","+r1*s1+"L"+r0*c1+","+r0*s1+"A"+r0+","+r0+" 0 "+df+",0 "+r0*c0+","+r0*s0+"Z":"M"+r1*c0+","+r1*s0+"A"+r1+","+r1+" 0 "+df+",1 "+r1*c1+","+r1*s1+"L0,0"+"Z";}
arc.innerRadius=function(v){if(!arguments.length)return innerRadius;innerRadius=d3_functor(v);return arc;};arc.outerRadius=function(v){if(!arguments.length)return outerRadius;outerRadius=d3_functor(v);return arc;};arc.startAngle=function(v){if(!arguments.length)return startAngle;startAngle=d3_functor(v);return arc;};arc.endAngle=function(v){if(!arguments.length)return endAngle;endAngle=d3_functor(v);return arc;};arc.centroid=function(){var r=(innerRadius.apply(this,arguments)+outerRadius.apply(this,arguments))/2,a=(startAngle.apply(this,arguments)+endAngle.apply(this,arguments))/2+d3_svg_arcOffset;return[Math.cos(a)*r,Math.sin(a)*r];};return arc;};var d3_svg_arcOffset=-π/2,d3_svg_arcMax=2*π-1e-6;function d3_svg_arcInnerRadius(d){return d.innerRadius;}
function d3_svg_arcOuterRadius(d){return d.outerRadius;}
function d3_svg_arcStartAngle(d){return d.startAngle;}
function d3_svg_arcEndAngle(d){return d.endAngle;}
d3.svg.line.radial=function(){var line=d3_svg_line(d3_svg_lineRadial);line.radius=line.x,delete line.x;line.angle=line.y,delete line.y;return line;};function d3_svg_lineRadial(points){var point,i=-1,n=points.length,r,a;while(++i<n){point=points[i];r=point[0];a=point[1]+d3_svg_arcOffset;point[0]=r*Math.cos(a);point[1]=r*Math.sin(a);}
return points;}
function d3_svg_area(projection){var x0=d3_svg_lineX,x1=d3_svg_lineX,y0=0,y1=d3_svg_lineY,defined=d3_true,interpolate=d3_svg_lineLinear,interpolateKey=interpolate.key,interpolateReverse=interpolate,L="L",tension=.7;function area(data){var segments=[],points0=[],points1=[],i=-1,n=data.length,d,fx0=d3_functor(x0),fy0=d3_functor(y0),fx1=x0===x1?function(){return x;}:d3_functor(x1),fy1=y0===y1?function(){return y;}:d3_functor(y1),x,y;function segment(){segments.push("M",interpolate(projection(points1),tension),L,interpolateReverse(projection(points0.reverse()),tension),"Z");}
while(++i<n){if(defined.call(this,d=data[i],i)){points0.push([x=+fx0.call(this,d,i),y=+fy0.call(this,d,i)]);points1.push([+fx1.call(this,d,i),+fy1.call(this,d,i)]);}else if(points0.length){segment();points0=[];points1=[];}}
if(points0.length)segment();return segments.length?segments.join(""):null;}
area.x=function(_){if(!arguments.length)return x1;x0=x1=_;return area;};area.x0=function(_){if(!arguments.length)return x0;x0=_;return area;};area.x1=function(_){if(!arguments.length)return x1;x1=_;return area;};area.y=function(_){if(!arguments.length)return y1;y0=y1=_;return area;};area.y0=function(_){if(!arguments.length)return y0;y0=_;return area;};area.y1=function(_){if(!arguments.length)return y1;y1=_;return area;};area.defined=function(_){if(!arguments.length)return defined;defined=_;return area;};area.interpolate=function(_){if(!arguments.length)return interpolateKey;if(typeof _==="function")interpolateKey=interpolate=_;else interpolateKey=(interpolate=d3_svg_lineInterpolators.get(_)||d3_svg_lineLinear).key;interpolateReverse=interpolate.reverse||interpolate;L=interpolate.closed?"M":"L";return area;};area.tension=function(_){if(!arguments.length)return tension;tension=_;return area;};return area;}
d3_svg_lineStepBefore.reverse=d3_svg_lineStepAfter;d3_svg_lineStepAfter.reverse=d3_svg_lineStepBefore;d3.svg.area=function(){return d3_svg_area(d3_identity);};d3.svg.area.radial=function(){var area=d3_svg_area(d3_svg_lineRadial);area.radius=area.x,delete area.x;area.innerRadius=area.x0,delete area.x0;area.outerRadius=area.x1,delete area.x1;area.angle=area.y,delete area.y;area.startAngle=area.y0,delete area.y0;area.endAngle=area.y1,delete area.y1;return area;};d3.svg.chord=function(){var source=d3_source,target=d3_target,radius=d3_svg_chordRadius,startAngle=d3_svg_arcStartAngle,endAngle=d3_svg_arcEndAngle;function chord(d,i){var s=subgroup(this,source,d,i),t=subgroup(this,target,d,i);return"M"+s.p0+arc(s.r,s.p1,s.a1-s.a0)+(equals(s,t)?curve(s.r,s.p1,s.r,s.p0):curve(s.r,s.p1,t.r,t.p0)+arc(t.r,t.p1,t.a1-t.a0)+curve(t.r,t.p1,s.r,s.p0))+"Z";}
function subgroup(self,f,d,i){var subgroup=f.call(self,d,i),r=radius.call(self,subgroup,i),a0=startAngle.call(self,subgroup,i)+d3_svg_arcOffset,a1=endAngle.call(self,subgroup,i)+d3_svg_arcOffset;return{r:r,a0:a0,a1:a1,p0:[r*Math.cos(a0),r*Math.sin(a0)],p1:[r*Math.cos(a1),r*Math.sin(a1)]};}
function equals(a,b){return a.a0==b.a0&&a.a1==b.a1;}
function arc(r,p,a){return"A"+r+","+r+" 0 "+ +(a>π)+",1 "+p;}
function curve(r0,p0,r1,p1){return"Q 0,0 "+p1;}
chord.radius=function(v){if(!arguments.length)return radius;radius=d3_functor(v);return chord;};chord.source=function(v){if(!arguments.length)return source;source=d3_functor(v);return chord;};chord.target=function(v){if(!arguments.length)return target;target=d3_functor(v);return chord;};chord.startAngle=function(v){if(!arguments.length)return startAngle;startAngle=d3_functor(v);return chord;};chord.endAngle=function(v){if(!arguments.length)return endAngle;endAngle=d3_functor(v);return chord;};return chord;};function d3_svg_chordRadius(d){return d.radius;}
d3.svg.diagonal=function(){var source=d3_source,target=d3_target,projection=d3_svg_diagonalProjection;function diagonal(d,i){var p0=source.call(this,d,i),p3=target.call(this,d,i),m=(p0.y+p3.y)/2,p=[p0,{x:p0.x,y:m},{x:p3.x,y:m},p3];p=p.map(projection);return"M"+p[0]+"C"+p[1]+" "+p[2]+" "+p[3];}
diagonal.source=function(x){if(!arguments.length)return source;source=d3_functor(x);return diagonal;};diagonal.target=function(x){if(!arguments.length)return target;target=d3_functor(x);return diagonal;};diagonal.projection=function(x){if(!arguments.length)return projection;projection=x;return diagonal;};return diagonal;};function d3_svg_diagonalProjection(d){return[d.x,d.y];}
d3.svg.diagonal.radial=function(){var diagonal=d3.svg.diagonal(),projection=d3_svg_diagonalProjection,projection_=diagonal.projection;diagonal.projection=function(x){return arguments.length?projection_(d3_svg_diagonalRadialProjection(projection=x)):projection;};return diagonal;};function d3_svg_diagonalRadialProjection(projection){return function(){var d=projection.apply(this,arguments),r=d[0],a=d[1]+d3_svg_arcOffset;return[r*Math.cos(a),r*Math.sin(a)];};}
d3.svg.symbol=function(){var type=d3_svg_symbolType,size=d3_svg_symbolSize;function symbol(d,i){return(d3_svg_symbols.get(type.call(this,d,i))||d3_svg_symbolCircle)(size.call(this,d,i));}
symbol.type=function(x){if(!arguments.length)return type;type=d3_functor(x);return symbol;};symbol.size=function(x){if(!arguments.length)return size;size=d3_functor(x);return symbol;};return symbol;};function d3_svg_symbolSize(){return 64;}
function d3_svg_symbolType(){return"circle";}
function d3_svg_symbolCircle(size){var r=Math.sqrt(size/π);return"M0,"+r+"A"+r+","+r+" 0 1,1 0,"+-r+"A"+r+","+r+" 0 1,1 0,"+r+"Z";}
var d3_svg_symbols=d3.map({circle:d3_svg_symbolCircle,cross:function(size){var r=Math.sqrt(size/5)/2;return"M"+-3*r+","+-r+"H"+-r+"V"+-3*r+"H"+r+"V"+-r+"H"+3*r+"V"+r+"H"+r+"V"+3*r+"H"+-r+"V"+r+"H"+-3*r+"Z";},diamond:function(size){var ry=Math.sqrt(size/(2*d3_svg_symbolTan30)),rx=ry*d3_svg_symbolTan30;return"M0,"+-ry+"L"+rx+",0"+" 0,"+ry+" "+-rx+",0"+"Z";},square:function(size){var r=Math.sqrt(size)/2;return"M"+-r+","+-r+"L"+r+","+-r+" "+r+","+r+" "+-r+","+r+"Z";},"triangle-down":function(size){var rx=Math.sqrt(size/d3_svg_symbolSqrt3),ry=rx*d3_svg_symbolSqrt3/2;return"M0,"+ry+"L"+rx+","+-ry+" "+-rx+","+-ry+"Z";},"triangle-up":function(size){var rx=Math.sqrt(size/d3_svg_symbolSqrt3),ry=rx*d3_svg_symbolSqrt3/2;return"M0,"+-ry+"L"+rx+","+ry+" "+-rx+","+ry+"Z";}});d3.svg.symbolTypes=d3_svg_symbols.keys();var d3_svg_symbolSqrt3=Math.sqrt(3),d3_svg_symbolTan30=Math.tan(30*d3_radians);function d3_transition(groups,id){d3_arraySubclass(groups,d3_transitionPrototype);groups.id=id;return groups;}
var d3_transitionPrototype=[],d3_transitionId=0,d3_transitionInheritId,d3_transitionInherit={ease:d3_ease_cubicInOut,delay:0,duration:250};d3_transitionPrototype.call=d3_selectionPrototype.call;d3_transitionPrototype.empty=d3_selectionPrototype.empty;d3_transitionPrototype.node=d3_selectionPrototype.node;d3.transition=function(selection){return arguments.length?d3_transitionInheritId?selection.transition():selection:d3_selectionRoot.transition();};d3.transition.prototype=d3_transitionPrototype;d3_transitionPrototype.select=function(selector){var id=this.id,subgroups=[],subgroup,subnode,node;if(typeof selector!=="function")selector=d3_selection_selector(selector);for(var j=-1,m=this.length;++j<m;){subgroups.push(subgroup=[]);for(var group=this[j],i=-1,n=group.length;++i<n;){if((node=group[i])&&(subnode=selector.call(node,node.__data__,i))){if("__data__"in node)subnode.__data__=node.__data__;d3_transitionNode(subnode,i,id,node.__transition__[id]);subgroup.push(subnode);}else{subgroup.push(null);}}}
return d3_transition(subgroups,id);};d3_transitionPrototype.selectAll=function(selector){var id=this.id,subgroups=[],subgroup,subnodes,node,subnode,transition;if(typeof selector!=="function")selector=d3_selection_selectorAll(selector);for(var j=-1,m=this.length;++j<m;){for(var group=this[j],i=-1,n=group.length;++i<n;){if(node=group[i]){transition=node.__transition__[id];subnodes=selector.call(node,node.__data__,i);subgroups.push(subgroup=[]);for(var k=-1,o=subnodes.length;++k<o;){d3_transitionNode(subnode=subnodes[k],k,id,transition);subgroup.push(subnode);}}}}
return d3_transition(subgroups,id);};d3_transitionPrototype.filter=function(filter){var subgroups=[],subgroup,group,node;if(typeof filter!=="function")filter=d3_selection_filter(filter);for(var j=0,m=this.length;j<m;j++){subgroups.push(subgroup=[]);for(var group=this[j],i=0,n=group.length;i<n;i++){if((node=group[i])&&filter.call(node,node.__data__,i)){subgroup.push(node);}}}
return d3_transition(subgroups,this.id,this.time).ease(this.ease());};d3_transitionPrototype.tween=function(name,tween){var id=this.id;if(arguments.length<2)return this.node().__transition__[id].tween.get(name);return d3_selection_each(this,tween==null?function(node){node.__transition__[id].tween.remove(name);}:function(node){node.__transition__[id].tween.set(name,tween);});};function d3_transition_tween(groups,name,value,tween){var id=groups.id;return d3_selection_each(groups,typeof value==="function"?function(node,i,j){node.__transition__[id].tween.set(name,tween(value.call(node,node.__data__,i,j)));}:(value=tween(value),function(node){node.__transition__[id].tween.set(name,value);}));}
d3_transitionPrototype.attr=function(nameNS,value){if(arguments.length<2){for(value in nameNS)this.attr(value,nameNS[value]);return this;}
var interpolate=d3_interpolateByName(nameNS),name=d3.ns.qualify(nameNS);function attrNull(){this.removeAttribute(name);}
function attrNullNS(){this.removeAttributeNS(name.space,name.local);}
function attrTween(b){return b==null?attrNull:(b+="",function(){var a=this.getAttribute(name),i;return a!==b&&(i=interpolate(a,b),function(t){this.setAttribute(name,i(t));});});}
function attrTweenNS(b){return b==null?attrNullNS:(b+="",function(){var a=this.getAttributeNS(name.space,name.local),i;return a!==b&&(i=interpolate(a,b),function(t){this.setAttributeNS(name.space,name.local,i(t));});});}
return d3_transition_tween(this,"attr."+nameNS,value,name.local?attrTweenNS:attrTween);};d3_transitionPrototype.attrTween=function(nameNS,tween){var name=d3.ns.qualify(nameNS);function attrTween(d,i){var f=tween.call(this,d,i,this.getAttribute(name));return f&&function(t){this.setAttribute(name,f(t));};}
function attrTweenNS(d,i){var f=tween.call(this,d,i,this.getAttributeNS(name.space,name.local));return f&&function(t){this.setAttributeNS(name.space,name.local,f(t));};}
return this.tween("attr."+nameNS,name.local?attrTweenNS:attrTween);};d3_transitionPrototype.style=function(name,value,priority){var n=arguments.length;if(n<3){if(typeof name!=="string"){if(n<2)value="";for(priority in name)this.style(priority,name[priority],value);return this;}
priority="";}
var interpolate=d3_interpolateByName(name);function styleNull(){this.style.removeProperty(name);}
function styleString(b){return b==null?styleNull:(b+="",function(){var a=d3_window.getComputedStyle(this,null).getPropertyValue(name),i;return a!==b&&(i=interpolate(a,b),function(t){this.style.setProperty(name,i(t),priority);});});}
return d3_transition_tween(this,"style."+name,value,styleString);};d3_transitionPrototype.styleTween=function(name,tween,priority){if(arguments.length<3)priority="";function styleTween(d,i){var f=tween.call(this,d,i,d3_window.getComputedStyle(this,null).getPropertyValue(name));return f&&function(t){this.style.setProperty(name,f(t),priority);};}
return this.tween("style."+name,styleTween);};d3_transitionPrototype.text=function(value){return d3_transition_tween(this,"text",value,d3_transition_text);};function d3_transition_text(b){if(b==null)b="";return function(){this.textContent=b;};}
d3_transitionPrototype.remove=function(){return this.each("end.transition",function(){var p;if(!this.__transition__&&(p=this.parentNode))p.removeChild(this);});};d3_transitionPrototype.ease=function(value){var id=this.id;if(arguments.length<1)return this.node().__transition__[id].ease;if(typeof value!=="function")value=d3.ease.apply(d3,arguments);return d3_selection_each(this,function(node){node.__transition__[id].ease=value;});};d3_transitionPrototype.delay=function(value){var id=this.id;return d3_selection_each(this,typeof value==="function"?function(node,i,j){node.__transition__[id].delay=value.call(node,node.__data__,i,j)|0;}:(value|=0,function(node){node.__transition__[id].delay=value;}));};d3_transitionPrototype.duration=function(value){var id=this.id;return d3_selection_each(this,typeof value==="function"?function(node,i,j){node.__transition__[id].duration=Math.max(1,value.call(node,node.__data__,i,j)|0);}:(value=Math.max(1,value|0),function(node){node.__transition__[id].duration=value;}));};d3_transitionPrototype.each=function(type,listener){var id=this.id;if(arguments.length<2){var inherit=d3_transitionInherit,inheritId=d3_transitionInheritId;d3_transitionInheritId=id;d3_selection_each(this,function(node,i,j){d3_transitionInherit=node.__transition__[id];type.call(node,node.__data__,i,j);});d3_transitionInherit=inherit;d3_transitionInheritId=inheritId;}else{d3_selection_each(this,function(node){node.__transition__[id].event.on(type,listener);});}
return this;};d3_transitionPrototype.transition=function(){var id0=this.id,id1=++d3_transitionId,subgroups=[],subgroup,group,node,transition;for(var j=0,m=this.length;j<m;j++){subgroups.push(subgroup=[]);for(var group=this[j],i=0,n=group.length;i<n;i++){if(node=group[i]){transition=Object.create(node.__transition__[id0]);transition.delay+=transition.duration;d3_transitionNode(node,i,id1,transition);}
subgroup.push(node);}}
return d3_transition(subgroups,id1);};function d3_transitionNode(node,i,id,inherit){var lock=node.__transition__||(node.__transition__={active:0,count:0}),transition=lock[id];if(!transition){var time=inherit.time;transition=lock[id]={tween:new d3_Map(),event:d3.dispatch("start","end"),time:time,ease:inherit.ease,delay:inherit.delay,duration:inherit.duration};++lock.count;d3.timer(function(elapsed){var d=node.__data__,ease=transition.ease,event=transition.event,delay=transition.delay,duration=transition.duration,tweened=[];return delay<=elapsed?start(elapsed):d3.timer(start,delay,time),1;function start(elapsed){if(lock.active>id)return stop();lock.active=id;event.start.call(node,d,i);transition.tween.forEach(function(key,value){if(value=value.call(node,d,i)){tweened.push(value);}});if(!tick(elapsed))d3.timer(tick,0,time);return 1;}
function tick(elapsed){if(lock.active!==id)return stop();var t=(elapsed-delay)/duration,e=ease(t),n=tweened.length;while(n>0){tweened[--n].call(node,e);}
if(t>=1){stop();event.end.call(node,d,i);return 1;}}
function stop(){if(--lock.count)delete lock[id];else delete node.__transition__;return 1;}},0,time);return transition;}}
d3.svg.axis=function(){var scale=d3.scale.linear(),orient=d3_svg_axisDefaultOrient,tickMajorSize=6,tickMinorSize=6,tickEndSize=6,tickPadding=3,tickArguments_=[10],tickValues=null,tickFormat_,tickSubdivide=0;function axis(g){g.each(function(){var g=d3.select(this);var ticks=tickValues==null?scale.ticks?scale.ticks.apply(scale,tickArguments_):scale.domain():tickValues,tickFormat=tickFormat_==null?scale.tickFormat?scale.tickFormat.apply(scale,tickArguments_):String:tickFormat_;var subticks=d3_svg_axisSubdivide(scale,ticks,tickSubdivide),subtick=g.selectAll(".tick.minor").data(subticks,String),subtickEnter=subtick.enter().insert("line",".tick").attr("class","tick minor").style("opacity",1e-6),subtickExit=d3.transition(subtick.exit()).style("opacity",1e-6).remove(),subtickUpdate=d3.transition(subtick).style("opacity",1);var tick=g.selectAll(".tick.major").data(ticks,String),tickEnter=tick.enter().insert("g","path").attr("class","tick major").style("opacity",1e-6),tickExit=d3.transition(tick.exit()).style("opacity",1e-6).remove(),tickUpdate=d3.transition(tick).style("opacity",1),tickTransform;var range=d3_scaleRange(scale),path=g.selectAll(".domain").data([0]),pathUpdate=(path.enter().append("path").attr("class","domain"),d3.transition(path));var scale1=scale.copy(),scale0=this.__chart__||scale1;this.__chart__=scale1;tickEnter.append("line");tickEnter.append("text");var lineEnter=tickEnter.select("line"),lineUpdate=tickUpdate.select("line"),text=tick.select("text").text(tickFormat),textEnter=tickEnter.select("text"),textUpdate=tickUpdate.select("text");switch(orient){case"bottom":{tickTransform=d3_svg_axisX;subtickEnter.attr("y2",tickMinorSize);subtickUpdate.attr("x2",0).attr("y2",tickMinorSize);lineEnter.attr("y2",tickMajorSize);textEnter.attr("y",Math.max(tickMajorSize,0)+tickPadding);lineUpdate.attr("x2",0).attr("y2",tickMajorSize);textUpdate.attr("x",0).attr("y",Math.max(tickMajorSize,0)+tickPadding);text.attr("dy",".71em").style("text-anchor","middle");pathUpdate.attr("d","M"+range[0]+","+tickEndSize+"V0H"+range[1]+"V"+tickEndSize);break;}
case"top":{tickTransform=d3_svg_axisX;subtickEnter.attr("y2",-tickMinorSize);subtickUpdate.attr("x2",0).attr("y2",-tickMinorSize);lineEnter.attr("y2",-tickMajorSize);textEnter.attr("y",-(Math.max(tickMajorSize,0)+tickPadding));lineUpdate.attr("x2",0).attr("y2",-tickMajorSize);textUpdate.attr("x",0).attr("y",-(Math.max(tickMajorSize,0)+tickPadding));text.attr("dy","0em").style("text-anchor","middle");pathUpdate.attr("d","M"+range[0]+","+-tickEndSize+"V0H"+range[1]+"V"+-tickEndSize);break;}
case"left":{tickTransform=d3_svg_axisY;subtickEnter.attr("x2",-tickMinorSize);subtickUpdate.attr("x2",-tickMinorSize).attr("y2",0);lineEnter.attr("x2",-tickMajorSize);textEnter.attr("x",-(Math.max(tickMajorSize,0)+tickPadding));lineUpdate.attr("x2",-tickMajorSize).attr("y2",0);textUpdate.attr("x",-(Math.max(tickMajorSize,0)+tickPadding)).attr("y",0);text.attr("dy",".32em").style("text-anchor","end");pathUpdate.attr("d","M"+-tickEndSize+","+range[0]+"H0V"+range[1]+"H"+-tickEndSize);break;}
case"right":{tickTransform=d3_svg_axisY;subtickEnter.attr("x2",tickMinorSize);subtickUpdate.attr("x2",tickMinorSize).attr("y2",0);lineEnter.attr("x2",tickMajorSize);textEnter.attr("x",Math.max(tickMajorSize,0)+tickPadding);lineUpdate.attr("x2",tickMajorSize).attr("y2",0);textUpdate.attr("x",Math.max(tickMajorSize,0)+tickPadding).attr("y",0);text.attr("dy",".32em").style("text-anchor","start");pathUpdate.attr("d","M"+tickEndSize+","+range[0]+"H0V"+range[1]+"H"+tickEndSize);break;}}
if(scale.ticks){tickEnter.call(tickTransform,scale0);tickUpdate.call(tickTransform,scale1);tickExit.call(tickTransform,scale1);subtickEnter.call(tickTransform,scale0);subtickUpdate.call(tickTransform,scale1);subtickExit.call(tickTransform,scale1);}else{var dx=scale1.rangeBand()/2,x=function(d){return scale1(d)+dx;};tickEnter.call(tickTransform,x);tickUpdate.call(tickTransform,x);}});}
axis.scale=function(x){if(!arguments.length)return scale;scale=x;return axis;};axis.orient=function(x){if(!arguments.length)return orient;orient=x in d3_svg_axisOrients?x+"":d3_svg_axisDefaultOrient;return axis;};axis.ticks=function(){if(!arguments.length)return tickArguments_;tickArguments_=arguments;return axis;};axis.tickValues=function(x){if(!arguments.length)return tickValues;tickValues=x;return axis;};axis.tickFormat=function(x){if(!arguments.length)return tickFormat_;tickFormat_=x;return axis;};axis.tickSize=function(x,y){if(!arguments.length)return tickMajorSize;var n=arguments.length-1;tickMajorSize=+x;tickMinorSize=n>1?+y:tickMajorSize;tickEndSize=n>0?+arguments[n]:tickMajorSize;return axis;};axis.tickPadding=function(x){if(!arguments.length)return tickPadding;tickPadding=+x;return axis;};axis.tickSubdivide=function(x){if(!arguments.length)return tickSubdivide;tickSubdivide=+x;return axis;};return axis;};var d3_svg_axisDefaultOrient="bottom",d3_svg_axisOrients={top:1,right:1,bottom:1,left:1};function d3_svg_axisX(selection,x){selection.attr("transform",function(d){return"translate("+x(d)+",0)";});}
function d3_svg_axisY(selection,y){selection.attr("transform",function(d){return"translate(0,"+y(d)+")";});}
function d3_svg_axisSubdivide(scale,ticks,m){subticks=[];if(m&&ticks.length>1){var extent=d3_scaleExtent(scale.domain()),subticks,i=-1,n=ticks.length,d=(ticks[1]-ticks[0])/++m,j,v;while(++i<n){for(j=m;--j>0;){if((v=+ticks[i]-j*d)>=extent[0]){subticks.push(v);}}}
for(--i,j=0;++j<m&&(v=+ticks[i]+j*d)<extent[1];){subticks.push(v);}}
return subticks;}
d3.svg.brush=function(){var event=d3_eventDispatch(brush,"brushstart","brush","brushend"),x=null,y=null,resizes=d3_svg_brushResizes[0],extent=[[0,0],[0,0]],extentDomain;function brush(g){g.each(function(){var g=d3.select(this),bg=g.selectAll(".background").data([0]),fg=g.selectAll(".extent").data([0]),tz=g.selectAll(".resize").data(resizes,String),e;g.style("pointer-events","all").on("mousedown.brush",brushstart).on("touchstart.brush",brushstart);bg.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");fg.enter().append("rect").attr("class","extent").style("cursor","move");tz.enter().append("g").attr("class",function(d){return"resize "+d;}).style("cursor",function(d){return d3_svg_brushCursor[d];}).append("rect").attr("x",function(d){return/[ew]$/.test(d)?-3:null;}).attr("y",function(d){return/^[ns]/.test(d)?-3:null;}).attr("width",6).attr("height",6).style("visibility","hidden");tz.style("display",brush.empty()?"none":null);tz.exit().remove();if(x){e=d3_scaleRange(x);bg.attr("x",e[0]).attr("width",e[1]-e[0]);redrawX(g);}
if(y){e=d3_scaleRange(y);bg.attr("y",e[0]).attr("height",e[1]-e[0]);redrawY(g);}
redraw(g);});}
function redraw(g){g.selectAll(".resize").attr("transform",function(d){return"translate("+extent[+/e$/.test(d)][0]+","+extent[+/^s/.test(d)][1]+")";});}
function redrawX(g){g.select(".extent").attr("x",extent[0][0]);g.selectAll(".extent,.n>rect,.s>rect").attr("width",extent[1][0]-extent[0][0]);}
function redrawY(g){g.select(".extent").attr("y",extent[0][1]);g.selectAll(".extent,.e>rect,.w>rect").attr("height",extent[1][1]-extent[0][1]);}
function brushstart(){var target=this,eventTarget=d3.select(d3.event.target),event_=event.of(target,arguments),g=d3.select(target),resizing=eventTarget.datum(),resizingX=!/^(n|s)$/.test(resizing)&&x,resizingY=!/^(e|w)$/.test(resizing)&&y,dragging=eventTarget.classed("extent"),center,origin=mouse(),offset;var w=d3.select(d3_window).on("mousemove.brush",brushmove).on("mouseup.brush",brushend).on("touchmove.brush",brushmove).on("touchend.brush",brushend).on("keydown.brush",keydown).on("keyup.brush",keyup);if(dragging){origin[0]=extent[0][0]-origin[0];origin[1]=extent[0][1]-origin[1];}else if(resizing){var ex=+/w$/.test(resizing),ey=+/^n/.test(resizing);offset=[extent[1-ex][0]-origin[0],extent[1-ey][1]-origin[1]];origin[0]=extent[ex][0];origin[1]=extent[ey][1];}else if(d3.event.altKey)center=origin.slice();g.style("pointer-events","none").selectAll(".resize").style("display",null);d3.select("body").style("cursor",eventTarget.style("cursor"));event_({type:"brushstart"});brushmove();d3_eventCancel();function mouse(){var touches=d3.event.changedTouches;return touches?d3.touches(target,touches)[0]:d3.mouse(target);}
function keydown(){if(d3.event.keyCode==32){if(!dragging){center=null;origin[0]-=extent[1][0];origin[1]-=extent[1][1];dragging=2;}
d3_eventCancel();}}
function keyup(){if(d3.event.keyCode==32&&dragging==2){origin[0]+=extent[1][0];origin[1]+=extent[1][1];dragging=0;d3_eventCancel();}}
function brushmove(){var point=mouse(),moved=false;if(offset){point[0]+=offset[0];point[1]+=offset[1];}
if(!dragging){if(d3.event.altKey){if(!center)center=[(extent[0][0]+extent[1][0])/2,(extent[0][1]+extent[1][1])/2];origin[0]=extent[+(point[0]<center[0])][0];origin[1]=extent[+(point[1]<center[1])][1];}else center=null;}
if(resizingX&&move1(point,x,0)){redrawX(g);moved=true;}
if(resizingY&&move1(point,y,1)){redrawY(g);moved=true;}
if(moved){redraw(g);event_({type:"brush",mode:dragging?"move":"resize"});}}
function move1(point,scale,i){var range=d3_scaleRange(scale),r0=range[0],r1=range[1],position=origin[i],size=extent[1][i]-extent[0][i],min,max;if(dragging){r0-=position;r1-=size+position;}
min=Math.max(r0,Math.min(r1,point[i]));if(dragging){max=(min+=position)+size;}else{if(center)position=Math.max(r0,Math.min(r1,2*center[i]-min));if(position<min){max=min;min=position;}else{max=position;}}
if(extent[0][i]!==min||extent[1][i]!==max){extentDomain=null;extent[0][i]=min;extent[1][i]=max;return true;}}
function brushend(){brushmove();g.style("pointer-events","all").selectAll(".resize").style("display",brush.empty()?"none":null);d3.select("body").style("cursor",null);w.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);event_({type:"brushend"});d3_eventCancel();}}
brush.x=function(z){if(!arguments.length)return x;x=z;resizes=d3_svg_brushResizes[!x<<1|!y];return brush;};brush.y=function(z){if(!arguments.length)return y;y=z;resizes=d3_svg_brushResizes[!x<<1|!y];return brush;};brush.extent=function(z){var x0,x1,y0,y1,t;if(!arguments.length){z=extentDomain||extent;if(x){x0=z[0][0],x1=z[1][0];if(!extentDomain){x0=extent[0][0],x1=extent[1][0];if(x.invert)x0=x.invert(x0),x1=x.invert(x1);if(x1<x0)t=x0,x0=x1,x1=t;}}
if(y){y0=z[0][1],y1=z[1][1];if(!extentDomain){y0=extent[0][1],y1=extent[1][1];if(y.invert)y0=y.invert(y0),y1=y.invert(y1);if(y1<y0)t=y0,y0=y1,y1=t;}}
return x&&y?[[x0,y0],[x1,y1]]:x?[x0,x1]:y&&[y0,y1];}
extentDomain=[[0,0],[0,0]];if(x){x0=z[0],x1=z[1];if(y)x0=x0[0],x1=x1[0];extentDomain[0][0]=x0,extentDomain[1][0]=x1;if(x.invert)x0=x(x0),x1=x(x1);if(x1<x0)t=x0,x0=x1,x1=t;extent[0][0]=x0|0,extent[1][0]=x1|0;}
if(y){y0=z[0],y1=z[1];if(x)y0=y0[1],y1=y1[1];extentDomain[0][1]=y0,extentDomain[1][1]=y1;if(y.invert)y0=y(y0),y1=y(y1);if(y1<y0)t=y0,y0=y1,y1=t;extent[0][1]=y0|0,extent[1][1]=y1|0;}
return brush;};brush.clear=function(){extentDomain=null;extent[0][0]=extent[0][1]=extent[1][0]=extent[1][1]=0;return brush;};brush.empty=function(){return x&&extent[0][0]===extent[1][0]||y&&extent[0][1]===extent[1][1];};return d3.rebind(brush,event,"on");};var d3_svg_brushCursor={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"};var d3_svg_brushResizes=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]];d3.time={};var d3_time=Date,d3_time_daySymbols=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function d3_time_utc(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0]);}
d3_time_utc.prototype={getDate:function(){return this._.getUTCDate();},getDay:function(){return this._.getUTCDay();},getFullYear:function(){return this._.getUTCFullYear();},getHours:function(){return this._.getUTCHours();},getMilliseconds:function(){return this._.getUTCMilliseconds();},getMinutes:function(){return this._.getUTCMinutes();},getMonth:function(){return this._.getUTCMonth();},getSeconds:function(){return this._.getUTCSeconds();},getTime:function(){return this._.getTime();},getTimezoneOffset:function(){return 0;},valueOf:function(){return this._.valueOf();},setDate:function(){d3_time_prototype.setUTCDate.apply(this._,arguments);},setDay:function(){d3_time_prototype.setUTCDay.apply(this._,arguments);},setFullYear:function(){d3_time_prototype.setUTCFullYear.apply(this._,arguments);},setHours:function(){d3_time_prototype.setUTCHours.apply(this._,arguments);},setMilliseconds:function(){d3_time_prototype.setUTCMilliseconds.apply(this._,arguments);},setMinutes:function(){d3_time_prototype.setUTCMinutes.apply(this._,arguments);},setMonth:function(){d3_time_prototype.setUTCMonth.apply(this._,arguments);},setSeconds:function(){d3_time_prototype.setUTCSeconds.apply(this._,arguments);},setTime:function(){d3_time_prototype.setTime.apply(this._,arguments);}};var d3_time_prototype=Date.prototype;var d3_time_formatDateTime="%a %b %e %X %Y",d3_time_formatDate="%m/%d/%Y",d3_time_formatTime="%H:%M:%S";var d3_time_days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],d3_time_dayAbbreviations=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],d3_time_months=["January","February","March","April","May","June","July","August","September","October","November","December"],d3_time_monthAbbreviations=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function d3_time_interval(local,step,number){function round(date){var d0=local(date),d1=offset(d0,1);return date-d0<d1-date?d0:d1;}
function ceil(date){step(date=local(new d3_time(date-1)),1);return date;}
function offset(date,k){step(date=new d3_time(+date),k);return date;}
function range(t0,t1,dt){var time=ceil(t0),times=[];if(dt>1){while(time<t1){if(!(number(time)%dt))times.push(new Date(+time));step(time,1);}}else{while(time<t1)times.push(new Date(+time)),step(time,1);}
return times;}
function range_utc(t0,t1,dt){try{d3_time=d3_time_utc;var utc=new d3_time_utc();utc._=t0;return range(utc,t1,dt);}finally{d3_time=Date;}}
local.floor=local;local.round=round;local.ceil=ceil;local.offset=offset;local.range=range;var utc=local.utc=d3_time_interval_utc(local);utc.floor=utc;utc.round=d3_time_interval_utc(round);utc.ceil=d3_time_interval_utc(ceil);utc.offset=d3_time_interval_utc(offset);utc.range=range_utc;return local;}
function d3_time_interval_utc(method){return function(date,k){try{d3_time=d3_time_utc;var utc=new d3_time_utc();utc._=date;return method(utc,k)._;}finally{d3_time=Date;}};}
d3.time.year=d3_time_interval(function(date){date=d3.time.day(date);date.setMonth(0,1);return date;},function(date,offset){date.setFullYear(date.getFullYear()+offset);},function(date){return date.getFullYear();});d3.time.years=d3.time.year.range;d3.time.years.utc=d3.time.year.utc.range;d3.time.day=d3_time_interval(function(date){var day=new d3_time(1970,0);day.setFullYear(date.getFullYear(),date.getMonth(),date.getDate());return day;},function(date,offset){date.setDate(date.getDate()+offset);},function(date){return date.getDate()-1;});d3.time.days=d3.time.day.range;d3.time.days.utc=d3.time.day.utc.range;d3.time.dayOfYear=function(date){var year=d3.time.year(date);return Math.floor((date-year-(date.getTimezoneOffset()-year.getTimezoneOffset())*6e4)/864e5);};d3_time_daySymbols.forEach(function(day,i){day=day.toLowerCase();i=7-i;var interval=d3.time[day]=d3_time_interval(function(date){(date=d3.time.day(date)).setDate(date.getDate()-(date.getDay()+i)%7);return date;},function(date,offset){date.setDate(date.getDate()+Math.floor(offset)*7);},function(date){var day=d3.time.year(date).getDay();return Math.floor((d3.time.dayOfYear(date)+(day+i)%7)/7)-(day!==i);});d3.time[day+"s"]=interval.range;d3.time[day+"s"].utc=interval.utc.range;d3.time[day+"OfYear"]=function(date){var day=d3.time.year(date).getDay();return Math.floor((d3.time.dayOfYear(date)+(day+i)%7)/7);};});d3.time.week=d3.time.sunday;d3.time.weeks=d3.time.sunday.range;d3.time.weeks.utc=d3.time.sunday.utc.range;d3.time.weekOfYear=d3.time.sundayOfYear;d3.time.format=function(template){var n=template.length;function format(date){var string=[],i=-1,j=0,c,p,f;while(++i<n){if(template.charCodeAt(i)===37){string.push(template.substring(j,i));if((p=d3_time_formatPads[c=template.charAt(++i)])!=null)c=template.charAt(++i);if(f=d3_time_formats[c])c=f(date,p==null?c==="e"?" ":"0":p);string.push(c);j=i+1;}}
string.push(template.substring(j,i));return string.join("");}
format.parse=function(string){var d={y:1900,m:0,d:1,H:0,M:0,S:0,L:0},i=d3_time_parse(d,template,string,0);if(i!=string.length)return null;if("p"in d)d.H=d.H%12+d.p*12;var date=new d3_time();date.setFullYear(d.y,d.m,d.d);date.setHours(d.H,d.M,d.S,d.L);return date;};format.toString=function(){return template;};return format;};function d3_time_parse(date,template,string,j){var c,p,i=0,n=template.length,m=string.length;while(i<n){if(j>=m)return-1;c=template.charCodeAt(i++);if(c===37){p=d3_time_parsers[template.charAt(i++)];if(!p||(j=p(date,string,j))<0)return-1;}else if(c!=string.charCodeAt(j++)){return-1;}}
return j;}
function d3_time_formatRe(names){return new RegExp("^(?:"+names.map(d3.requote).join("|")+")","i");}
function d3_time_formatLookup(names){var map=new d3_Map(),i=-1,n=names.length;while(++i<n)map.set(names[i].toLowerCase(),i);return map;}
function d3_time_formatPad(value,fill,width){value+="";var length=value.length;return length<width?new Array(width-length+1).join(fill)+value:value;}
var d3_time_dayRe=d3_time_formatRe(d3_time_days),d3_time_dayAbbrevRe=d3_time_formatRe(d3_time_dayAbbreviations),d3_time_monthRe=d3_time_formatRe(d3_time_months),d3_time_monthLookup=d3_time_formatLookup(d3_time_months),d3_time_monthAbbrevRe=d3_time_formatRe(d3_time_monthAbbreviations),d3_time_monthAbbrevLookup=d3_time_formatLookup(d3_time_monthAbbreviations);var d3_time_formatPads={"-":"",_:" ","0":"0"};var d3_time_formats={a:function(d){return d3_time_dayAbbreviations[d.getDay()];},A:function(d){return d3_time_days[d.getDay()];},b:function(d){return d3_time_monthAbbreviations[d.getMonth()];},B:function(d){return d3_time_months[d.getMonth()];},c:d3.time.format(d3_time_formatDateTime),d:function(d,p){return d3_time_formatPad(d.getDate(),p,2);},e:function(d,p){return d3_time_formatPad(d.getDate(),p,2);},H:function(d,p){return d3_time_formatPad(d.getHours(),p,2);},I:function(d,p){return d3_time_formatPad(d.getHours()%12||12,p,2);},j:function(d,p){return d3_time_formatPad(1+d3.time.dayOfYear(d),p,3);},L:function(d,p){return d3_time_formatPad(d.getMilliseconds(),p,3);},m:function(d,p){return d3_time_formatPad(d.getMonth()+1,p,2);},M:function(d,p){return d3_time_formatPad(d.getMinutes(),p,2);},p:function(d){return d.getHours()>=12?"PM":"AM";},S:function(d,p){return d3_time_formatPad(d.getSeconds(),p,2);},U:function(d,p){return d3_time_formatPad(d3.time.sundayOfYear(d),p,2);},w:function(d){return d.getDay();},W:function(d,p){return d3_time_formatPad(d3.time.mondayOfYear(d),p,2);},x:d3.time.format(d3_time_formatDate),X:d3.time.format(d3_time_formatTime),y:function(d,p){return d3_time_formatPad(d.getFullYear()%100,p,2);},Y:function(d,p){return d3_time_formatPad(d.getFullYear()%1e4,p,4);},Z:d3_time_zone,"%":function(){return"%";}};var d3_time_parsers={a:d3_time_parseWeekdayAbbrev,A:d3_time_parseWeekday,b:d3_time_parseMonthAbbrev,B:d3_time_parseMonth,c:d3_time_parseLocaleFull,d:d3_time_parseDay,e:d3_time_parseDay,H:d3_time_parseHour24,I:d3_time_parseHour24,L:d3_time_parseMilliseconds,m:d3_time_parseMonthNumber,M:d3_time_parseMinutes,p:d3_time_parseAmPm,S:d3_time_parseSeconds,x:d3_time_parseLocaleDate,X:d3_time_parseLocaleTime,y:d3_time_parseYear,Y:d3_time_parseFullYear};function d3_time_parseWeekdayAbbrev(date,string,i){d3_time_dayAbbrevRe.lastIndex=0;var n=d3_time_dayAbbrevRe.exec(string.substring(i));return n?i+=n[0].length:-1;}
function d3_time_parseWeekday(date,string,i){d3_time_dayRe.lastIndex=0;var n=d3_time_dayRe.exec(string.substring(i));return n?i+=n[0].length:-1;}
function d3_time_parseMonthAbbrev(date,string,i){d3_time_monthAbbrevRe.lastIndex=0;var n=d3_time_monthAbbrevRe.exec(string.substring(i));return n?(date.m=d3_time_monthAbbrevLookup.get(n[0].toLowerCase()),i+=n[0].length):-1;}
function d3_time_parseMonth(date,string,i){d3_time_monthRe.lastIndex=0;var n=d3_time_monthRe.exec(string.substring(i));return n?(date.m=d3_time_monthLookup.get(n[0].toLowerCase()),i+=n[0].length):-1;}
function d3_time_parseLocaleFull(date,string,i){return d3_time_parse(date,d3_time_formats.c.toString(),string,i);}
function d3_time_parseLocaleDate(date,string,i){return d3_time_parse(date,d3_time_formats.x.toString(),string,i);}
function d3_time_parseLocaleTime(date,string,i){return d3_time_parse(date,d3_time_formats.X.toString(),string,i);}
function d3_time_parseFullYear(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+4));return n?(date.y=+n[0],i+=n[0].length):-1;}
function d3_time_parseYear(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.y=d3_time_expandYear(+n[0]),i+=n[0].length):-1;}
function d3_time_expandYear(d){return d+(d>68?1900:2e3);}
function d3_time_parseMonthNumber(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.m=n[0]-1,i+=n[0].length):-1;}
function d3_time_parseDay(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.d=+n[0],i+=n[0].length):-1;}
function d3_time_parseHour24(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.H=+n[0],i+=n[0].length):-1;}
function d3_time_parseMinutes(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.M=+n[0],i+=n[0].length):-1;}
function d3_time_parseSeconds(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.S=+n[0],i+=n[0].length):-1;}
function d3_time_parseMilliseconds(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+3));return n?(date.L=+n[0],i+=n[0].length):-1;}
var d3_time_numberRe=/^\s*\d+/;function d3_time_parseAmPm(date,string,i){var n=d3_time_amPmLookup.get(string.substring(i,i+=2).toLowerCase());return n==null?-1:(date.p=n,i);}
var d3_time_amPmLookup=d3.map({am:0,pm:1});function d3_time_zone(d){var z=d.getTimezoneOffset(),zs=z>0?"-":"+",zh=~~(Math.abs(z)/60),zm=Math.abs(z)%60;return zs+d3_time_formatPad(zh,"0",2)+d3_time_formatPad(zm,"0",2);}
d3.time.format.utc=function(template){var local=d3.time.format(template);function format(date){try{d3_time=d3_time_utc;var utc=new d3_time();utc._=date;return local(utc);}finally{d3_time=Date;}}
format.parse=function(string){try{d3_time=d3_time_utc;var date=local.parse(string);return date&&date._;}finally{d3_time=Date;}};format.toString=local.toString;return format;};var d3_time_formatIso=d3.time.format.utc("%Y-%m-%dT%H:%M:%S.%LZ");d3.time.format.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?d3_time_formatIsoNative:d3_time_formatIso;function d3_time_formatIsoNative(date){return date.toISOString();}
d3_time_formatIsoNative.parse=function(string){var date=new Date(string);return isNaN(date)?null:date;};d3_time_formatIsoNative.toString=d3_time_formatIso.toString;d3.time.second=d3_time_interval(function(date){return new d3_time(Math.floor(date/1e3)*1e3);},function(date,offset){date.setTime(date.getTime()+Math.floor(offset)*1e3);},function(date){return date.getSeconds();});d3.time.seconds=d3.time.second.range;d3.time.seconds.utc=d3.time.second.utc.range;d3.time.minute=d3_time_interval(function(date){return new d3_time(Math.floor(date/6e4)*6e4);},function(date,offset){date.setTime(date.getTime()+Math.floor(offset)*6e4);},function(date){return date.getMinutes();});d3.time.minutes=d3.time.minute.range;d3.time.minutes.utc=d3.time.minute.utc.range;d3.time.hour=d3_time_interval(function(date){var timezone=date.getTimezoneOffset()/60;return new d3_time((Math.floor(date/36e5-timezone)+timezone)*36e5);},function(date,offset){date.setTime(date.getTime()+Math.floor(offset)*36e5);},function(date){return date.getHours();});d3.time.hours=d3.time.hour.range;d3.time.hours.utc=d3.time.hour.utc.range;d3.time.month=d3_time_interval(function(date){date=d3.time.day(date);date.setDate(1);return date;},function(date,offset){date.setMonth(date.getMonth()+offset);},function(date){return date.getMonth();});d3.time.months=d3.time.month.range;d3.time.months.utc=d3.time.month.utc.range;function d3_time_scale(linear,methods,format){function scale(x){return linear(x);}
scale.invert=function(x){return d3_time_scaleDate(linear.invert(x));};scale.domain=function(x){if(!arguments.length)return linear.domain().map(d3_time_scaleDate);linear.domain(x);return scale;};scale.nice=function(m){return scale.domain(d3_scale_nice(scale.domain(),function(){return m;}));};scale.ticks=function(m,k){var extent=d3_scaleExtent(scale.domain());if(typeof m!=="function"){var span=extent[1]-extent[0],target=span/m,i=d3.bisect(d3_time_scaleSteps,target);if(i==d3_time_scaleSteps.length)return methods.year(extent,m);if(!i)return linear.ticks(m).map(d3_time_scaleDate);if(Math.log(target/d3_time_scaleSteps[i-1])<Math.log(d3_time_scaleSteps[i]/target))--i;m=methods[i];k=m[1];m=m[0].range;}
return m(extent[0],new Date(+extent[1]+1),k);};scale.tickFormat=function(){return format;};scale.copy=function(){return d3_time_scale(linear.copy(),methods,format);};return d3_scale_linearRebind(scale,linear);}
function d3_time_scaleDate(t){return new Date(t);}
function d3_time_scaleFormat(formats){return function(date){var i=formats.length-1,f=formats[i];while(!f[1](date))f=formats[--i];return f[0](date);};}
function d3_time_scaleSetYear(y){var d=new Date(y,0,1);d.setFullYear(y);return d;}
function d3_time_scaleGetYear(d){var y=d.getFullYear(),d0=d3_time_scaleSetYear(y),d1=d3_time_scaleSetYear(y+1);return y+(d-d0)/(d1-d0);}
var d3_time_scaleSteps=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6];var d3_time_scaleLocalMethods=[[d3.time.second,1],[d3.time.second,5],[d3.time.second,15],[d3.time.second,30],[d3.time.minute,1],[d3.time.minute,5],[d3.time.minute,15],[d3.time.minute,30],[d3.time.hour,1],[d3.time.hour,3],[d3.time.hour,6],[d3.time.hour,12],[d3.time.day,1],[d3.time.day,2],[d3.time.week,1],[d3.time.month,1],[d3.time.month,3],[d3.time.year,1]];var d3_time_scaleLocalFormats=[[d3.time.format("%Y"),d3_true],[d3.time.format("%B"),function(d){return d.getMonth();}],[d3.time.format("%b %d"),function(d){return d.getDate()!=1;}],[d3.time.format("%a %d"),function(d){return d.getDay()&&d.getDate()!=1;}],[d3.time.format("%I %p"),function(d){return d.getHours();}],[d3.time.format("%I:%M"),function(d){return d.getMinutes();}],[d3.time.format(":%S"),function(d){return d.getSeconds();}],[d3.time.format(".%L"),function(d){return d.getMilliseconds();}]];var d3_time_scaleLinear=d3.scale.linear(),d3_time_scaleLocalFormat=d3_time_scaleFormat(d3_time_scaleLocalFormats);d3_time_scaleLocalMethods.year=function(extent,m){return d3_time_scaleLinear.domain(extent.map(d3_time_scaleGetYear)).ticks(m).map(d3_time_scaleSetYear);};d3.time.scale=function(){return d3_time_scale(d3.scale.linear(),d3_time_scaleLocalMethods,d3_time_scaleLocalFormat);};var d3_time_scaleUTCMethods=d3_time_scaleLocalMethods.map(function(m){return[m[0].utc,m[1]];});var d3_time_scaleUTCFormats=[[d3.time.format.utc("%Y"),d3_true],[d3.time.format.utc("%B"),function(d){return d.getUTCMonth();}],[d3.time.format.utc("%b %d"),function(d){return d.getUTCDate()!=1;}],[d3.time.format.utc("%a %d"),function(d){return d.getUTCDay()&&d.getUTCDate()!=1;}],[d3.time.format.utc("%I %p"),function(d){return d.getUTCHours();}],[d3.time.format.utc("%I:%M"),function(d){return d.getUTCMinutes();}],[d3.time.format.utc(":%S"),function(d){return d.getUTCSeconds();}],[d3.time.format.utc(".%L"),function(d){return d.getUTCMilliseconds();}]];var d3_time_scaleUTCFormat=d3_time_scaleFormat(d3_time_scaleUTCFormats);function d3_time_scaleUTCSetYear(y){var d=new Date(Date.UTC(y,0,1));d.setUTCFullYear(y);return d;}
function d3_time_scaleUTCGetYear(d){var y=d.getUTCFullYear(),d0=d3_time_scaleUTCSetYear(y),d1=d3_time_scaleUTCSetYear(y+1);return y+(d-d0)/(d1-d0);}
d3_time_scaleUTCMethods.year=function(extent,m){return d3_time_scaleLinear.domain(extent.map(d3_time_scaleUTCGetYear)).ticks(m).map(d3_time_scaleUTCSetYear);};d3.time.scale.utc=function(){return d3_time_scale(d3.scale.linear(),d3_time_scaleUTCMethods,d3_time_scaleUTCFormat);};d3.text=function(){return d3.xhr.apply(d3,arguments).response(d3_text);};function d3_text(request){return request.responseText;}
d3.json=function(url,callback){return d3.xhr(url,"application/json",callback).response(d3_json);};function d3_json(request){return JSON.parse(request.responseText);}
d3.html=function(url,callback){return d3.xhr(url,"text/html",callback).response(d3_html);};function d3_html(request){var range=d3_document.createRange();range.selectNode(d3_document.body);return range.createContextualFragment(request.responseText);}
d3.xml=function(){return d3.xhr.apply(d3,arguments).response(d3_xml);};function d3_xml(request){return request.responseXML;}
return d3;}();!function($){$(function(){"use strict"
$.support.transition=(function(){var thisBody=document.body||document.documentElement,thisStyle=thisBody.style,support=thisStyle.transition!==undefined||thisStyle.WebkitTransition!==undefined||thisStyle.MozTransition!==undefined||thisStyle.MsTransition!==undefined||thisStyle.OTransition!==undefined
return support&&{end:(function(){var transitionEnd="TransitionEnd"
if($.browser.webkit){transitionEnd="webkitTransitionEnd"}else if($.browser.mozilla){transitionEnd="transitionend"}else if($.browser.opera){transitionEnd="oTransitionEnd"}
return transitionEnd}())}})()})}(window.jQuery);!function($){"use strict"
var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on('click',dismiss,this.close)}
Alert.prototype={constructor:Alert,close:function(e){var $this=$(this),selector=$this.attr('data-target'),$parent
if(!selector){selector=$this.attr('href')
selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,'')}
$parent=$(selector)
$parent.trigger('close')
e&&e.preventDefault()
$parent.length||($parent=$this.hasClass('alert')?$this:$this.parent())
$parent.trigger('close').removeClass('in')
function removeElement(){$parent.trigger('closed').remove()}
$.support.transition&&$parent.hasClass('fade')?$parent.on($.support.transition.end,removeElement):removeElement()}}
$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data('alert')
if(!data)$this.data('alert',(data=new Alert(this)))
if(typeof option=='string')data[option].call($this)})}
$.fn.alert.Constructor=Alert
$(function(){$('body').on('click.alert.data-api',dismiss,Alert.prototype.close)})}(window.jQuery);!function($){"use strict"
var Button=function(element,options){this.$element=$(element)
this.options=$.extend({},$.fn.button.defaults,options)}
Button.prototype={constructor:Button,setState:function(state){var d='disabled',$el=this.$element,data=$el.data(),val=$el.is('input')?'val':'html'
state=state+'Text'
data.resetText||$el.data('resetText',$el[val]())
$el[val](data[state]||this.options[state])
setTimeout(function(){state=='loadingText'?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},toggle:function(){var $parent=this.$element.parent('[data-toggle="buttons-radio"]')
$parent&&$parent.find('.active').removeClass('active')
this.$element.toggleClass('active')}}
$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data('button'),options=typeof option=='object'&&option
if(!data)$this.data('button',(data=new Button(this,options)))
if(option=='toggle')data.toggle()
else if(option)data.setState(option)})}
$.fn.button.defaults={loadingText:'loading...'}
$.fn.button.Constructor=Button
$(function(){$('body').on('click.button.data-api','[data-toggle^=button]',function(e){var $btn=$(e.target)
if(!$btn.hasClass('btn'))$btn=$btn.closest('.btn')
$btn.button('toggle')})})}(window.jQuery);!function($){"use strict"
var Carousel=function(element,options){this.$element=$(element)
this.options=$.extend({},$.fn.carousel.defaults,options)
this.options.slide&&this.slide(this.options.slide)}
Carousel.prototype={cycle:function(){this.interval=setInterval($.proxy(this.next,this),this.options.interval)
return this},to:function(pos){var $active=this.$element.find('.active'),children=$active.parent().children(),activePos=children.index($active),that=this
if(pos>(children.length-1)||pos<0)return
if(this.sliding){return this.$element.one('slid',function(){that.to(pos)})}
if(activePos==pos){return this.pause().cycle()}
return this.slide(pos>activePos?'next':'prev',$(children[pos]))},pause:function(){clearInterval(this.interval)
this.interval=null
return this},next:function(){if(this.sliding)return
return this.slide('next')},prev:function(){if(this.sliding)return
return this.slide('prev')},slide:function(type,next){var $active=this.$element.find('.active'),$next=next||$active[type](),isCycling=this.interval,direction=type=='next'?'left':'right',fallback=type=='next'?'first':'last',that=this
if(!$next.length)return
this.sliding=true
isCycling&&this.pause()
$next=$next.length?$next:this.$element.find('.item')[fallback]()
if(!$.support.transition&&this.$element.hasClass('slide')){this.$element.trigger('slide')
$active.removeClass('active')
$next.addClass('active')
this.sliding=false
this.$element.trigger('slid')}else{$next.addClass(type)
$next[0].offsetWidth
$active.addClass(direction)
$next.addClass(direction)
this.$element.trigger('slide')
this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(' ')).addClass('active')
$active.removeClass(['active',direction].join(' '))
that.sliding=false
setTimeout(function(){that.$element.trigger('slid')},0)})}
isCycling&&this.cycle()
return this}}
$.fn.carousel=function(option){return this.each(function(){var $this=$(this),data=$this.data('carousel'),options=typeof option=='object'&&option
if(!data)$this.data('carousel',(data=new Carousel(this,options)))
if(typeof option=='number')data.to(option)
else if(typeof option=='string'||(option=options.slide))data[option]()
else data.cycle()})}
$.fn.carousel.defaults={interval:5000}
$.fn.carousel.Constructor=Carousel
$(function(){$('body').on('click.carousel.data-api','[data-slide]',function(e){var $this=$(this),href,$target=$($this.attr('data-target')||(href=$this.attr('href'))&&href.replace(/.*(?=#[^\s]+$)/,'')),options=!$target.data('modal')&&$.extend({},$target.data(),$this.data())
$target.carousel(options)
e.preventDefault()})})}(window.jQuery);!function($){"use strict"
var Collapse=function(element,options){this.$element=$(element)
this.options=$.extend({},$.fn.collapse.defaults,options)
if(this.options["parent"]){this.$parent=$(this.options["parent"])}
this.options.toggle&&this.toggle()}
Collapse.prototype={constructor:Collapse,dimension:function(){var hasWidth=this.$element.hasClass('width')
return hasWidth?'width':'height'},show:function(){var dimension=this.dimension(),scroll=$.camelCase(['scroll',dimension].join('-')),actives=this.$parent&&this.$parent.find('.in'),hasData
if(actives&&actives.length){hasData=actives.data('collapse')
actives.collapse('hide')
hasData||actives.data('collapse',null)}
this.$element[dimension](0)
this.transition('addClass','show','shown')
this.$element[dimension](this.$element[0][scroll])},hide:function(){var dimension=this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass','hide','hidden')
this.$element[dimension](0)},reset:function(size){var dimension=this.dimension()
this.$element.removeClass('collapse')
[dimension](size||'auto')
[0].offsetWidth
this.$element.addClass('collapse')},transition:function(method,startEvent,completeEvent){var that=this,complete=function(){if(startEvent=='show')that.reset()
that.$element.trigger(completeEvent)}
this.$element.trigger(startEvent)
[method]('in')
$.support.transition&&this.$element.hasClass('collapse')?this.$element.one($.support.transition.end,complete):complete()},toggle:function(){this[this.$element.hasClass('in')?'hide':'show']()}}
$.fn.collapse=function(option){return this.each(function(){var $this=$(this),data=$this.data('collapse'),options=typeof option=='object'&&option
if(!data)$this.data('collapse',(data=new Collapse(this,options)))
if(typeof option=='string')data[option]()})}
$.fn.collapse.defaults={toggle:true}
$.fn.collapse.Constructor=Collapse
$(function(){$('body').on('click.collapse.data-api','[data-toggle=collapse]',function(e){var $this=$(this),href,target=$this.attr('data-target')||e.preventDefault()||(href=$this.attr('href'))&&href.replace(/.*(?=#[^\s]+$)/,''),option=$(target).data('collapse')?'toggle':$this.data()
$(target).collapse(option)})})}(window.jQuery);!function($){"use strict"
var toggle='[data-toggle="dropdown"]',Dropdown=function(element){var $el=$(element).on('click.dropdown.data-api',this.toggle)
$('html').on('click.dropdown.data-api',function(){$el.parent().removeClass('open')})}
Dropdown.prototype={constructor:Dropdown,toggle:function(e){var $this=$(this),selector=$this.attr('data-target'),$parent,isActive
if(!selector){selector=$this.attr('href')
selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,'')}
$parent=$(selector)
$parent.length||($parent=$this.parent())
isActive=$parent.hasClass('open')
clearMenus()
!isActive&&$parent.toggleClass('open')
return false}}
function clearMenus(){$(toggle).parent().removeClass('open')}
$.fn.dropdown=function(option){return this.each(function(){var $this=$(this),data=$this.data('dropdown')
if(!data)$this.data('dropdown',(data=new Dropdown(this)))
if(typeof option=='string')data[option].call($this)})}
$.fn.dropdown.Constructor=Dropdown
$(function(){$('html').on('click.dropdown.data-api',clearMenus)
$('body').on('click.dropdown.data-api',toggle,Dropdown.prototype.toggle)})}(window.jQuery);!function($){"use strict"
var Modal=function(content,options){this.options=options
this.$element=$(content).delegate('[data-dismiss="modal"]','click.dismiss.modal',$.proxy(this.hide,this))}
Modal.prototype={constructor:Modal,toggle:function(){return this[!this.isShown?'show':'hide']()},show:function(){var that=this
if(this.isShown)return
$('body').addClass('modal-open')
this.isShown=true
this.$element.trigger('show')
escape.call(this)
backdrop.call(this,function(){var transition=$.support.transition&&that.$element.hasClass('fade')
!that.$element.parent().length&&that.$element.appendTo(document.body)
that.$element.show()
if(transition){that.$element[0].offsetWidth}
that.$element.addClass('in')
transition?that.$element.one($.support.transition.end,function(){that.$element.trigger('shown')}):that.$element.trigger('shown')})},hide:function(e){e&&e.preventDefault()
if(!this.isShown)return
var that=this
this.isShown=false
$('body').removeClass('modal-open')
escape.call(this)
this.$element.trigger('hide').removeClass('in')
$.support.transition&&this.$element.hasClass('fade')?hideWithTransition.call(this):hideModal.call(this)}}
function hideWithTransition(){var that=this,timeout=setTimeout(function(){that.$element.off($.support.transition.end)
hideModal.call(that)},500)
this.$element.one($.support.transition.end,function(){clearTimeout(timeout)
hideModal.call(that)})}
function hideModal(that){this.$element.hide().trigger('hidden')
backdrop.call(this)}
function backdrop(callback){var that=this,animate=this.$element.hasClass('fade')?'fade':''
if(this.isShown&&this.options.backdrop){var doAnimate=$.support.transition&&animate
this.$backdrop=$('<div class="modal-backdrop '+animate+'" />').appendTo(document.body)
if(this.options.backdrop!='static'){this.$backdrop.click($.proxy(this.hide,this))}
if(doAnimate)this.$backdrop[0].offsetWidth
this.$backdrop.addClass('in')
doAnimate?this.$backdrop.one($.support.transition.end,callback):callback()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass('in')
$.support.transition&&this.$element.hasClass('fade')?this.$backdrop.one($.support.transition.end,$.proxy(removeBackdrop,this)):removeBackdrop.call(this)}else if(callback){callback()}}
function removeBackdrop(){this.$backdrop.remove()
this.$backdrop=null}
function escape(){var that=this
if(this.isShown&&this.options.keyboard){$(document).on('keyup.dismiss.modal',function(e){e.which==27&&that.hide()})}else if(!this.isShown){$(document).off('keyup.dismiss.modal')}}
$.fn.modal=function(option){return this.each(function(){var $this=$(this),data=$this.data('modal'),options=$.extend({},$.fn.modal.defaults,$this.data(),typeof option=='object'&&option)
if(!data)$this.data('modal',(data=new Modal(this,options)))
if(typeof option=='string')data[option]()
else if(options.show)data.show()})}
$.fn.modal.defaults={backdrop:true,keyboard:true,show:true}
$.fn.modal.Constructor=Modal
$(function(){$('body').on('click.modal.data-api','[data-toggle="modal"]',function(e){var $this=$(this),href,$target=$($this.attr('data-target')||(href=$this.attr('href'))&&href.replace(/.*(?=#[^\s]+$)/,'')),option=$target.data('modal')?'toggle':$.extend({},$target.data(),$this.data())
e.preventDefault()
$target.modal(option)})})}(window.jQuery);!function($){"use strict"
var Tooltip=function(element,options){this.init('tooltip',element,options)}
Tooltip.prototype={constructor:Tooltip,init:function(type,element,options){var eventIn,eventOut
this.type=type
this.$element=$(element)
this.options=this.getOptions(options)
this.enabled=true
if(this.options.trigger!='manual'){eventIn=this.options.trigger=='hover'?'mouseenter':'focus'
eventOut=this.options.trigger=='hover'?'mouseleave':'blur'
this.$element.on(eventIn,this.options.selector,$.proxy(this.enter,this))
this.$element.on(eventOut,this.options.selector,$.proxy(this.leave,this))}
this.options.selector?(this._options=$.extend({},this.options,{trigger:'manual',selector:''})):this.fixTitle()},getOptions:function(options){options=$.extend({},$.fn[this.type].defaults,options,this.$element.data())
if(options.delay&&typeof options.delay=='number'){options.delay={show:options.delay,hide:options.delay}}
return options},enter:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type)
if(!self.options.delay||!self.options.delay.show){self.show()}else{self.hoverState='in'
setTimeout(function(){if(self.hoverState=='in'){self.show()}},self.options.delay.show)}},leave:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type)
if(!self.options.delay||!self.options.delay.hide){self.hide()}else{self.hoverState='out'
setTimeout(function(){if(self.hoverState=='out'){self.hide()}},self.options.delay.hide)}},show:function(){var $tip,inside,pos,actualWidth,actualHeight,placement,tp
if(this.hasContent()&&this.enabled){$tip=this.tip()
this.setContent()
if(this.options.animation){$tip.addClass('fade')}
placement=typeof this.options.placement=='function'?this.options.placement.call(this,$tip[0],this.$element[0]):this.options.placement
inside=/in/.test(placement)
$tip.remove().css({top:0,left:0,display:'block'}).appendTo(inside?this.$element:document.body)
pos=this.getPosition(inside)
actualWidth=$tip[0].offsetWidth
actualHeight=$tip[0].offsetHeight
switch(inside?placement.split(' ')[1]:placement){case'bottom':tp={top:pos.top+pos.height,left:pos.left+pos.width/2-actualWidth/2}
break
case'top':tp={top:pos.top-actualHeight,left:pos.left+pos.width/2-actualWidth/2}
break
case'left':tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left-actualWidth}
break
case'right':tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left+pos.width}
break}
$tip.css(tp).addClass(placement).addClass('in')}},setContent:function(){var $tip=this.tip()
$tip.find('.tooltip-inner').html(this.getTitle())
$tip.removeClass('fade in top bottom left right')},hide:function(){var that=this,$tip=this.tip()
$tip.removeClass('in')
function removeWithAnimation(){var timeout=setTimeout(function(){$tip.off($.support.transition.end).remove()},500)
$tip.one($.support.transition.end,function(){clearTimeout(timeout)
$tip.remove()})}
$.support.transition&&this.$tip.hasClass('fade')?removeWithAnimation():$tip.remove()},fixTitle:function(){var $e=this.$element
if($e.attr('title')||typeof($e.attr('data-original-title'))!='string'){$e.attr('data-original-title',$e.attr('title')||'').removeAttr('title')}},hasContent:function(){return this.getTitle()},getPosition:function(inside){return $.extend({},(inside?{top:0,left:0}:this.$element.offset()),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var title,$e=this.$element,o=this.options
title=$e.attr('data-original-title')||(typeof o.title=='function'?o.title.call($e[0]):o.title)
title=title.toString().replace(/(^\s*|\s*$)/,"")
return title},tip:function(){return this.$tip=this.$tip||$(this.options.template)},validate:function(){if(!this.$element[0].parentNode){this.hide()
this.$element=null
this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(){this[this.tip().hasClass('in')?'hide':'show']()}}
$.fn.tooltip=function(option){return this.each(function(){var $this=$(this),data=$this.data('tooltip'),options=typeof option=='object'&&option
if(!data)$this.data('tooltip',(data=new Tooltip(this,options)))
if(typeof option=='string')data[option]()})}
$.fn.tooltip.Constructor=Tooltip
$.fn.tooltip.defaults={animation:true,delay:0,selector:false,placement:'top',trigger:'hover',title:'',template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'}}(window.jQuery);!function($){"use strict"
var Popover=function(element,options){this.init('popover',element,options)}
Popover.prototype=$.extend({},$.fn.tooltip.Constructor.prototype,{constructor:Popover,setContent:function(){var $tip=this.tip(),title=this.getTitle(),content=this.getContent()
$tip.find('.popover-title')[$.type(title)=='object'?'append':'html'](title)
$tip.find('.popover-content > *')[$.type(content)=='object'?'append':'html'](content)
$tip.removeClass('fade top bottom left right in')},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var content,$e=this.$element,o=this.options
content=$e.attr('data-content')||(typeof o.content=='function'?o.content.call($e[0]):o.content)
content=content.toString().replace(/(^\s*|\s*$)/,"")
return content},tip:function(){if(!this.$tip){this.$tip=$(this.options.template)}
return this.$tip}})
$.fn.popover=function(option){return this.each(function(){var $this=$(this),data=$this.data('popover'),options=typeof option=='object'&&option
if(!data)$this.data('popover',(data=new Popover(this,options)))
if(typeof option=='string')data[option]()})}
$.fn.popover.Constructor=Popover
$.fn.popover.defaults=$.extend({},$.fn.tooltip.defaults,{placement:'right',content:'',template:'<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'})}(window.jQuery);!function($){"use strict"
function ScrollSpy(element,options){var process=$.proxy(this.process,this),$element=$(element).is('body')?$(window):$(element),href
this.options=$.extend({},$.fn.scrollspy.defaults,options)
this.$scrollElement=$element.on('scroll.scroll.data-api',process)
this.selector=(this.options.target||((href=$(element).attr('href'))&&href.replace(/.*(?=#[^\s]+$)/,''))||'')+' .nav li > a'
this.$body=$('body').on('click.scroll.data-api',this.selector,process)
this.refresh()
this.process()}
ScrollSpy.prototype={constructor:ScrollSpy,refresh:function(){this.targets=this.$body.find(this.selector).map(function(){var href=$(this).attr('href')
return/^#\w/.test(href)&&$(href).length?href:null})
this.offsets=$.map(this.targets,function(id){return $(id).position().top})},process:function(){var scrollTop=this.$scrollElement.scrollTop()+this.options.offset,offsets=this.offsets,targets=this.targets,activeTarget=this.activeTarget,i
for(i=offsets.length;i--;){activeTarget!=targets[i]&&scrollTop>=offsets[i]&&(!offsets[i+1]||scrollTop<=offsets[i+1])&&this.activate(targets[i])}},activate:function(target){var active
this.activeTarget=target
this.$body.find(this.selector).parent('.active').removeClass('active')
active=this.$body.find(this.selector+'[href="'+target+'"]').parent('li').addClass('active')
if(active.parent('.dropdown-menu')){active.closest('li.dropdown').addClass('active')}}}
$.fn.scrollspy=function(option){return this.each(function(){var $this=$(this),data=$this.data('scrollspy'),options=typeof option=='object'&&option
if(!data)$this.data('scrollspy',(data=new ScrollSpy(this,options)))
if(typeof option=='string')data[option]()})}
$.fn.scrollspy.Constructor=ScrollSpy
$.fn.scrollspy.defaults={offset:10}
$(function(){$('[data-spy="scroll"]').each(function(){var $spy=$(this)
$spy.scrollspy($spy.data())})})}(window.jQuery);!function($){"use strict"
var Tab=function(element){this.element=$(element)}
Tab.prototype={constructor:Tab,show:function(){var $this=this.element,$ul=$this.closest('ul:not(.dropdown-menu)'),selector=$this.attr('data-target'),previous,$target
if(!selector){selector=$this.attr('href')
selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,'')}
if($this.parent('li').hasClass('active'))return
previous=$ul.find('.active a').last()[0]
$this.trigger({type:'show',relatedTarget:previous})
$target=$(selector)
this.activate($this.parent('li'),$ul)
this.activate($target,$target.parent(),function(){$this.trigger({type:'shown',relatedTarget:previous})})},activate:function(element,container,callback){var $active=container.find('> .active'),transition=callback&&$.support.transition&&$active.hasClass('fade')
function next(){$active.removeClass('active').find('> .dropdown-menu > .active').removeClass('active')
element.addClass('active')
if(transition){element[0].offsetWidth
element.addClass('in')}else{element.removeClass('fade')}
if(element.parent('.dropdown-menu')){element.closest('li.dropdown').addClass('active')}
callback&&callback()}
transition?$active.one($.support.transition.end,next):next()
$active.removeClass('in')}}
$.fn.tab=function(option){return this.each(function(){var $this=$(this),data=$this.data('tab')
if(!data)$this.data('tab',(data=new Tab(this)))
if(typeof option=='string')data[option]()})}
$.fn.tab.Constructor=Tab
$(function(){$('body').on('click.tab.data-api','[data-toggle="tab"], [data-toggle="pill"]',function(e){e.preventDefault()
$(this).tab('show')})})}(window.jQuery);!function($){"use strict"
var Typeahead=function(element,options){this.$element=$(element)
this.options=$.extend({},$.fn.typeahead.defaults,options)
this.matcher=this.options.matcher||this.matcher
this.sorter=this.options.sorter||this.sorter
this.highlighter=this.options.highlighter||this.highlighter
this.$menu=$(this.options.menu).appendTo('body')
this.source=this.options.source
this.shown=false
this.listen()}
Typeahead.prototype={constructor:Typeahead,select:function(){var val=this.$menu.find('.active').attr('data-value')
this.$element.val(val)
return this.hide()},show:function(){var pos=$.extend({},this.$element.offset(),{height:this.$element[0].offsetHeight})
this.$menu.css({top:pos.top+pos.height,left:pos.left})
this.$menu.show()
this.shown=true
return this},hide:function(){this.$menu.hide()
this.shown=false
return this},lookup:function(event){var that=this,items,q
this.query=this.$element.val()
if(!this.query){return this.shown?this.hide():this}
items=$.grep(this.source,function(item){if(that.matcher(item))return item})
items=this.sorter(items)
if(!items.length){return this.shown?this.hide():this}
return this.render(items.slice(0,this.options.items)).show()},matcher:function(item){return~item.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(items){var beginswith=[],caseSensitive=[],caseInsensitive=[],item
while(item=items.shift()){if(!item.toLowerCase().indexOf(this.query.toLowerCase()))beginswith.push(item)
else if(~item.indexOf(this.query))caseSensitive.push(item)
else caseInsensitive.push(item)}
return beginswith.concat(caseSensitive,caseInsensitive)},highlighter:function(item){return item.replace(new RegExp('('+this.query+')','ig'),function($1,match){return'<strong>'+match+'</strong>'})},render:function(items){var that=this
items=$(items).map(function(i,item){i=$(that.options.item).attr('data-value',item)
i.find('a').html(that.highlighter(item))
return i[0]})
items.first().addClass('active')
this.$menu.html(items)
return this},next:function(event){var active=this.$menu.find('.active').removeClass('active'),next=active.next()
if(!next.length){next=$(this.$menu.find('li')[0])}
next.addClass('active')},prev:function(event){var active=this.$menu.find('.active').removeClass('active'),prev=active.prev()
if(!prev.length){prev=this.$menu.find('li').last()}
prev.addClass('active')},listen:function(){this.$element.on('blur',$.proxy(this.blur,this)).on('keypress',$.proxy(this.keypress,this)).on('keyup',$.proxy(this.keyup,this))
if($.browser.webkit||$.browser.msie){this.$element.on('keydown',$.proxy(this.keypress,this))}
this.$menu.on('click',$.proxy(this.click,this)).on('mouseenter','li',$.proxy(this.mouseenter,this))},keyup:function(e){e.stopPropagation()
e.preventDefault()
switch(e.keyCode){case 40:case 38:break
case 9:case 13:if(!this.shown)return
this.select()
break
case 27:this.hide()
break
default:this.lookup()}},keypress:function(e){e.stopPropagation()
if(!this.shown)return
switch(e.keyCode){case 9:case 13:case 27:e.preventDefault()
break
case 38:e.preventDefault()
this.prev()
break
case 40:e.preventDefault()
this.next()
break}},blur:function(e){var that=this
e.stopPropagation()
e.preventDefault()
setTimeout(function(){that.hide()},150)},click:function(e){e.stopPropagation()
e.preventDefault()
this.select()},mouseenter:function(e){this.$menu.find('.active').removeClass('active')
$(e.currentTarget).addClass('active')}}
$.fn.typeahead=function(option){return this.each(function(){var $this=$(this),data=$this.data('typeahead'),options=typeof option=='object'&&option
if(!data)$this.data('typeahead',(data=new Typeahead(this,options)))
if(typeof option=='string')data[option]()})}
$.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>'}
$.fn.typeahead.Constructor=Typeahead
$(function(){$('body').on('focus.typeahead.data-api','[data-provide="typeahead"]',function(e){var $this=$(this)
if($this.data('typeahead'))return
e.preventDefault()
$this.typeahead($this.data())})})}(window.jQuery);!function($){var Datepicker=function(element,options){this.element=$(element);this.format=DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy');this.picker=$(DPGlobal.template).appendTo('body').on({click:$.proxy(this.click,this)});this.isInput=this.element.is('input');this.component=this.element.is('.date')?this.element.find('.add-on'):false;if(this.isInput){this.element.on({focus:$.proxy(this.show,this),keyup:$.proxy(this.update,this)});}else{if(this.component){this.component.on('click',$.proxy(this.show,this));}else{this.element.on('click',$.proxy(this.show,this));}}
this.minViewMode=options.minViewMode||this.element.data('date-minviewmode')||0;if(typeof this.minViewMode==='string'){switch(this.minViewMode){case'months':this.minViewMode=1;break;case'years':this.minViewMode=2;break;default:this.minViewMode=0;break;}}
this.viewMode=options.viewMode||this.element.data('date-viewmode')||0;if(typeof this.viewMode==='string'){switch(this.viewMode){case'months':this.viewMode=1;break;case'years':this.viewMode=2;break;default:this.viewMode=0;break;}}
this.startViewMode=this.viewMode;this.weekStart=options.weekStart||this.element.data('date-weekstart')||0;this.weekEnd=this.weekStart===0?6:this.weekStart-1;this.onRender=options.onRender;this.fillDow();this.fillMonths();this.update();this.showMode();};Datepicker.prototype={constructor:Datepicker,show:function(e){this.picker.show();this.height=this.component?this.component.outerHeight():this.element.outerHeight();this.place();$(window).on('resize',$.proxy(this.place,this));if(e){e.stopPropagation();e.preventDefault();}
if(!this.isInput){}
var that=this;$(document).on('mousedown',function(ev){if($(ev.target).closest('.datepicker').length==0){that.hide();}});this.element.trigger({type:'show',date:this.date});},hide:function(){this.picker.hide();$(window).off('resize',this.place);this.viewMode=this.startViewMode;this.showMode();if(!this.isInput){$(document).off('mousedown',this.hide);}
this.element.trigger({type:'hide',date:this.date});},set:function(){var formated=DPGlobal.formatDate(this.date,this.format);if(!this.isInput){if(this.component){this.element.find('input').prop('value',formated);}
this.element.data('date',formated);}else{this.element.prop('value',formated);}},setValue:function(newDate){if(typeof newDate==='string'){this.date=DPGlobal.parseDate(newDate,this.format);}else{this.date=new Date(newDate);}
this.set();this.viewDate=new Date(this.date.getFullYear(),this.date.getMonth(),1,0,0,0,0);this.fill();},place:function(){var offset=this.component?this.component.offset():this.element.offset();this.picker.css({top:offset.top+this.height,left:offset.left});},update:function(newDate){this.date=DPGlobal.parseDate(typeof newDate==='string'?newDate:(this.isInput?this.element.prop('value'):this.element.data('date')),this.format);this.viewDate=new Date(this.date.getFullYear(),this.date.getMonth(),1,0,0,0,0);this.fill();},fillDow:function(){var dowCnt=this.weekStart;var html='<tr>';while(dowCnt<this.weekStart+7){html+='<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';}
html+='</tr>';this.picker.find('.datepicker-days thead').append(html);},fillMonths:function(){var html='';var i=0
while(i<12){html+='<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';}
this.picker.find('.datepicker-months td').append(html);},fill:function(){var d=new Date(this.viewDate),year=d.getFullYear(),month=d.getMonth(),currentDate=this.date.valueOf();this.picker.find('.datepicker-days th:eq(1)').text(DPGlobal.dates.months[month]+' '+year);var prevMonth=new Date(year,month-1,28,0,0,0,0),day=DPGlobal.getDaysInMonth(prevMonth.getFullYear(),prevMonth.getMonth());prevMonth.setDate(day);prevMonth.setDate(day-(prevMonth.getDay()-this.weekStart+7)%7);var nextMonth=new Date(prevMonth);nextMonth.setDate(nextMonth.getDate()+42);nextMonth=nextMonth.valueOf();html=[];var clsName;while(prevMonth.valueOf()<nextMonth){if(prevMonth.getDay()===this.weekStart){html.push('<tr>');}
clsName=this.onRender(prevMonth);if(prevMonth.getMonth()<month){clsName+=' old';}else if(prevMonth.getMonth()>month){clsName+=' new';}
if(prevMonth.valueOf()===currentDate){clsName+=' active';}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate()+'</td>');if(prevMonth.getDay()===this.weekEnd){html.push('</tr>');}
prevMonth.setDate(prevMonth.getDate()+1);}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));var currentYear=this.date.getFullYear();var months=this.picker.find('.datepicker-months').find('th:eq(1)').text(year).end().find('span').removeClass('active');if(currentYear===year){months.eq(this.date.getMonth()).addClass('active');}
html='';year=parseInt(year/10,10)*10;var yearCont=this.picker.find('.datepicker-years').find('th:eq(1)').text(year+'-'+(year+9)).end().find('td');year-=1;for(var i=-1;i<11;i++){html+='<span class="year'+(i===-1||i===10?' old':'')+(currentYear===year?' active':'')+'">'+year+'</span>';year+=1;}
yearCont.html(html);},click:function(e){e.stopPropagation();e.preventDefault();var target=$(e.target).closest('span, td, th');if(target.length===1){switch(target[0].nodeName.toLowerCase()){case'th':switch(target[0].className){case'switch':this.showMode(1);break;case'prev':case'next':this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate,this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate)+
DPGlobal.modes[this.viewMode].navStep*(target[0].className==='prev'?-1:1));this.fill();this.set();break;}
break;case'span':if(target.is('.month')){var month=target.parent().find('span').index(target);this.viewDate.setMonth(month);}else{var year=parseInt(target.text(),10)||0;this.viewDate.setFullYear(year);}
if(this.viewMode!==0){this.date=new Date(this.viewDate);this.element.trigger({type:'changeDate',date:this.date,viewMode:DPGlobal.modes[this.viewMode].clsName});}
this.showMode(-1);this.fill();this.set();break;case'td':if(target.is('.day')&&!target.is('.disabled')){var day=parseInt(target.text(),10)||1;var month=this.viewDate.getMonth();if(target.is('.old')){month-=1;}else if(target.is('.new')){month+=1;}
var year=this.viewDate.getFullYear();this.date=new Date(year,month,day,0,0,0,0);this.viewDate=new Date(year,month,Math.min(28,day),0,0,0,0);this.fill();this.set();this.element.trigger({type:'changeDate',date:this.date,viewMode:DPGlobal.modes[this.viewMode].clsName});}
break;}}},mousedown:function(e){e.stopPropagation();e.preventDefault();},showMode:function(dir){if(dir){this.viewMode=Math.max(this.minViewMode,Math.min(2,this.viewMode+dir));}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();}};$.fn.datepicker=function(option,val){return this.each(function(){var $this=$(this),data=$this.data('datepicker'),options=typeof option==='object'&&option;if(!data){$this.data('datepicker',(data=new Datepicker(this,$.extend({},$.fn.datepicker.defaults,options))));}
if(typeof option==='string')data[option](val);});};$.fn.datepicker.defaults={onRender:function(date){return'';}};$.fn.datepicker.Constructor=Datepicker;var DPGlobal={modes:[{clsName:'days',navFnc:'Month',navStep:1},{clsName:'months',navFnc:'FullYear',navStep:1},{clsName:'years',navFnc:'FullYear',navStep:10}],dates:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa","Su"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},isLeapYear:function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0))},getDaysInMonth:function(year,month){return[31,(DPGlobal.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month]},parseFormat:function(format){var separator=format.match(/[.\/\-\s].*?/),parts=format.split(/\W+/);if(!separator||!parts||parts.length===0){throw new Error("Invalid date format.");}
return{separator:separator,parts:parts};},parseDate:function(date,format){var parts=date.split(format.separator),date=new Date(),val;date.setHours(0);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0);if(parts.length===format.parts.length){var year=date.getFullYear(),day=date.getDate(),month=date.getMonth();for(var i=0,cnt=format.parts.length;i<cnt;i++){val=parseInt(parts[i],10)||1;switch(format.parts[i]){case'dd':case'd':day=val;date.setDate(val);break;case'mm':case'm':month=val-1;date.setMonth(val-1);break;case'yy':year=2000+val;date.setFullYear(2000+val);break;case'yyyy':year=val;date.setFullYear(val);break;}}
date=new Date(year,month,day,0,0,0);}
return date;},formatDate:function(date,format){var val={d:date.getDate(),m:date.getMonth()+1,yy:date.getFullYear().toString().substring(2),yyyy:date.getFullYear()};val.dd=(val.d<10?'0':'')+val.d;val.mm=(val.m<10?'0':'')+val.m;var date=[];for(var i=0,cnt=format.parts.length;i<cnt;i++){date.push(val[format.parts[i]]);}
return date.join(format.separator);},headTemplate:'<thead>'+'<tr>'+'<th class="prev">&lsaquo;</th>'+'<th colspan="5" class="switch"></th>'+'<th class="next">&rsaquo;</th>'+'</tr>'+'</thead>',contTemplate:'<tbody><tr><td colspan="7"></td></tr></tbody>'};DPGlobal.template='<div class="datepicker dropdown-menu">'+'<div class="datepicker-days">'+'<table class=" table-condensed">'+
DPGlobal.headTemplate+'<tbody></tbody>'+'</table>'+'</div>'+'<div class="datepicker-months">'+'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+'</table>'+'</div>'+'<div class="datepicker-years">'+'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+'</table>'+'</div>'+'</div>';}(window.jQuery);var Hogan={};(function(Hogan,useArrayBuffer){Hogan.Template=function(renderFunc,text,compiler,options){this.r=renderFunc||this.r;this.c=compiler;this.options=options;this.text=text||'';this.buf=(useArrayBuffer)?[]:'';}
Hogan.Template.prototype={r:function(context,partials,indent){return'';},v:hoganEscape,t:coerceToString,render:function render(context,partials,indent){return this.ri([context],partials||{},indent);},ri:function(context,partials,indent){return this.r(context,partials,indent);},rp:function(name,context,partials,indent){var partial=partials[name];if(!partial){return'';}
if(this.c&&typeof partial=='string'){partial=this.c.compile(partial,this.options);}
return partial.ri(context,partials,indent);},rs:function(context,partials,section){var tail=context[context.length-1];if(!isArray(tail)){section(context,partials,this);return;}
for(var i=0;i<tail.length;i++){context.push(tail[i]);section(context,partials,this);context.pop();}},s:function(val,ctx,partials,inverted,start,end,tags){var pass;if(isArray(val)&&val.length===0){return false;}
if(typeof val=='function'){val=this.ls(val,ctx,partials,inverted,start,end,tags);}
pass=(val==='')||!!val;if(!inverted&&pass&&ctx){ctx.push((typeof val=='object')?val:ctx[ctx.length-1]);}
return pass;},d:function(key,ctx,partials,returnFound){var names=key.split('.'),val=this.f(names[0],ctx,partials,returnFound),cx=null;if(key==='.'&&isArray(ctx[ctx.length-2])){return ctx[ctx.length-1];}
for(var i=1;i<names.length;i++){if(val&&typeof val=='object'&&names[i]in val){cx=val;val=val[names[i]];}else{val='';}}
if(returnFound&&!val){return false;}
if(!returnFound&&typeof val=='function'){ctx.push(cx);val=this.lv(val,ctx,partials);ctx.pop();}
return val;},f:function(key,ctx,partials,returnFound){var val=false,v=null,found=false;for(var i=ctx.length-1;i>=0;i--){v=ctx[i];if(v&&typeof v=='object'&&key in v){val=v[key];found=true;break;}}
if(!found){return(returnFound)?false:"";}
if(!returnFound&&typeof val=='function'){val=this.lv(val,ctx,partials);}
return val;},ho:function(val,cx,partials,text,tags){var compiler=this.c;var options=this.options;options.delimiters=tags;var text=val.call(cx,text);text=(text==null)?String(text):text.toString();this.b(compiler.compile(text,options).render(cx,partials));return false;},b:(useArrayBuffer)?function(s){this.buf.push(s);}:function(s){this.buf+=s;},fl:(useArrayBuffer)?function(){var r=this.buf.join('');this.buf=[];return r;}:function(){var r=this.buf;this.buf='';return r;},ls:function(val,ctx,partials,inverted,start,end,tags){var cx=ctx[ctx.length-1],t=null;if(!inverted&&this.c&&val.length>0){return this.ho(val,cx,partials,this.text.substring(start,end),tags);}
t=val.call(cx);if(typeof t=='function'){if(inverted){return true;}else if(this.c){return this.ho(t,cx,partials,this.text.substring(start,end),tags);}}
return t;},lv:function(val,ctx,partials){var cx=ctx[ctx.length-1];var result=val.call(cx);if(typeof result=='function'){result=coerceToString(result.call(cx));if(this.c&&~result.indexOf("{\u007B")){return this.c.compile(result,this.options).render(cx,partials);}}
return coerceToString(result);}};var rAmp=/&/g,rLt=/</g,rGt=/>/g,rApos=/\'/g,rQuot=/\"/g,hChars=/[&<>\"\']/;function coerceToString(val){return String((val===null||val===undefined)?'':val);}
function hoganEscape(str){str=coerceToString(str);return hChars.test(str)?str.replace(rAmp,'&amp;').replace(rLt,'&lt;').replace(rGt,'&gt;').replace(rApos,'&#39;').replace(rQuot,'&quot;'):str;}
var isArray=Array.isArray||function(a){return Object.prototype.toString.call(a)==='[object Array]';};})(typeof exports!=='undefined'?exports:Hogan);(function(Hogan){var rIsWhitespace=/\S/,rQuot=/\"/g,rNewline=/\n/g,rCr=/\r/g,rSlash=/\\/g,tagTypes={'#':1,'^':2,'/':3,'!':4,'>':5,'<':6,'=':7,'_v':8,'{':9,'&':10};Hogan.scan=function scan(text,delimiters){var len=text.length,IN_TEXT=0,IN_TAG_TYPE=1,IN_TAG=2,state=IN_TEXT,tagType=null,tag=null,buf='',tokens=[],seenTag=false,i=0,lineStart=0,otag='{{',ctag='}}';function addBuf(){if(buf.length>0){tokens.push(new String(buf));buf='';}}
function lineIsWhitespace(){var isAllWhitespace=true;for(var j=lineStart;j<tokens.length;j++){isAllWhitespace=(tokens[j].tag&&tagTypes[tokens[j].tag]<tagTypes['_v'])||(!tokens[j].tag&&tokens[j].match(rIsWhitespace)===null);if(!isAllWhitespace){return false;}}
return isAllWhitespace;}
function filterLine(haveSeenTag,noNewLine){addBuf();if(haveSeenTag&&lineIsWhitespace()){for(var j=lineStart,next;j<tokens.length;j++){if(!tokens[j].tag){if((next=tokens[j+1])&&next.tag=='>'){next.indent=tokens[j].toString()}
tokens.splice(j,1);}}}else if(!noNewLine){tokens.push({tag:'\n'});}
seenTag=false;lineStart=tokens.length;}
function changeDelimiters(text,index){var close='='+ctag,closeIndex=text.indexOf(close,index),delimiters=trim(text.substring(text.indexOf('=',index)+1,closeIndex)).split(' ');otag=delimiters[0];ctag=delimiters[1];return closeIndex+close.length-1;}
if(delimiters){delimiters=delimiters.split(' ');otag=delimiters[0];ctag=delimiters[1];}
for(i=0;i<len;i++){if(state==IN_TEXT){if(tagChange(otag,text,i)){--i;addBuf();state=IN_TAG_TYPE;}else{if(text.charAt(i)=='\n'){filterLine(seenTag);}else{buf+=text.charAt(i);}}}else if(state==IN_TAG_TYPE){i+=otag.length-1;tag=tagTypes[text.charAt(i+1)];tagType=tag?text.charAt(i+1):'_v';if(tagType=='='){i=changeDelimiters(text,i);state=IN_TEXT;}else{if(tag){i++;}
state=IN_TAG;}
seenTag=i;}else{if(tagChange(ctag,text,i)){tokens.push({tag:tagType,n:trim(buf),otag:otag,ctag:ctag,i:(tagType=='/')?seenTag-ctag.length:i+otag.length});buf='';i+=ctag.length-1;state=IN_TEXT;if(tagType=='{'){if(ctag=='}}'){i++;}else{cleanTripleStache(tokens[tokens.length-1]);}}}else{buf+=text.charAt(i);}}}
filterLine(seenTag,true);return tokens;}
function cleanTripleStache(token){if(token.n.substr(token.n.length-1)==='}'){token.n=token.n.substring(0,token.n.length-1);}}
function trim(s){if(s.trim){return s.trim();}
return s.replace(/^\s*|\s*$/g,'');}
function tagChange(tag,text,index){if(text.charAt(index)!=tag.charAt(0)){return false;}
for(var i=1,l=tag.length;i<l;i++){if(text.charAt(index+i)!=tag.charAt(i)){return false;}}
return true;}
function buildTree(tokens,kind,stack,customTags){var instructions=[],opener=null,token=null;while(tokens.length>0){token=tokens.shift();if(token.tag=='#'||token.tag=='^'||isOpener(token,customTags)){stack.push(token);token.nodes=buildTree(tokens,token.tag,stack,customTags);instructions.push(token);}else if(token.tag=='/'){if(stack.length===0){throw new Error('Closing tag without opener: /'+token.n);}
opener=stack.pop();if(token.n!=opener.n&&!isCloser(token.n,opener.n,customTags)){throw new Error('Nesting error: '+opener.n+' vs. '+token.n);}
opener.end=token.i;return instructions;}else{instructions.push(token);}}
if(stack.length>0){throw new Error('missing closing tag: '+stack.pop().n);}
return instructions;}
function isOpener(token,tags){for(var i=0,l=tags.length;i<l;i++){if(tags[i].o==token.n){token.tag='#';return true;}}}
function isCloser(close,open,tags){for(var i=0,l=tags.length;i<l;i++){if(tags[i].c==close&&tags[i].o==open){return true;}}}
Hogan.generate=function(tree,text,options){var code='var _=this;_.b(i=i||"");'+walk(tree)+'return _.fl();';if(options.asString){return'function(c,p,i){'+code+';}';}
return new Hogan.Template(new Function('c','p','i',code),text,Hogan,options);}
function esc(s){return s.replace(rSlash,'\\\\').replace(rQuot,'\\\"').replace(rNewline,'\\n').replace(rCr,'\\r');}
function chooseMethod(s){return(~s.indexOf('.'))?'d':'f';}
function walk(tree){var code='';for(var i=0,l=tree.length;i<l;i++){var tag=tree[i].tag;if(tag=='#'){code+=section(tree[i].nodes,tree[i].n,chooseMethod(tree[i].n),tree[i].i,tree[i].end,tree[i].otag+" "+tree[i].ctag);}else if(tag=='^'){code+=invertedSection(tree[i].nodes,tree[i].n,chooseMethod(tree[i].n));}else if(tag=='<'||tag=='>'){code+=partial(tree[i]);}else if(tag=='{'||tag=='&'){code+=tripleStache(tree[i].n,chooseMethod(tree[i].n));}else if(tag=='\n'){code+=text('"\\n"'+(tree.length-1==i?'':' + i'));}else if(tag=='_v'){code+=variable(tree[i].n,chooseMethod(tree[i].n));}else if(tag===undefined){code+=text('"'+esc(tree[i])+'"');}}
return code;}
function section(nodes,id,method,start,end,tags){return'if(_.s(_.'+method+'("'+esc(id)+'",c,p,1),'+'c,p,0,'+start+','+end+',"'+tags+'")){'+'_.rs(c,p,'+'function(c,p,_){'+
walk(nodes)+'});c.pop();}';}
function invertedSection(nodes,id,method){return'if(!_.s(_.'+method+'("'+esc(id)+'",c,p,1),c,p,1,0,0,"")){'+
walk(nodes)+'};';}
function partial(tok){return'_.b(_.rp("'+esc(tok.n)+'",c,p,"'+(tok.indent||'')+'"));';}
function tripleStache(id,method){return'_.b(_.t(_.'+method+'("'+esc(id)+'",c,p,0)));';}
function variable(id,method){return'_.b(_.v(_.'+method+'("'+esc(id)+'",c,p,0)));';}
function text(id){return'_.b('+id+');';}
Hogan.parse=function(tokens,text,options){options=options||{};return buildTree(tokens,'',[],options.sectionTags||[]);},Hogan.cache={};Hogan.compile=function(text,options){options=options||{};var key=text+'||'+!!options.asString;var t=this.cache[key];if(t){return t;}
t=this.generate(this.parse(this.scan(text,options.delimiters),text,options),text,options);return this.cache[key]=t;};})(typeof exports!=='undefined'?exports:Hogan);horizon.addInitFunction(function(){var allPanelGroupBodies=$('.nav_accordion > dd > div > ul');allPanelGroupBodies.each(function(index,value){var activePanels=$(this).find('li > a.active');if(activePanels.length===0){$(this).slideUp(0);}});var activePanel=$('.nav_accordion > dd > div > ul > li > a.active');activePanel.closest('div').find('h4').addClass('active');$('.nav_accordion > dt').click(function(){var myDashHeader=$(this);var myDashWasActive=myDashHeader.hasClass("active");var allDashboardHeaders=$('.nav_accordion > dt');allDashboardHeaders.removeClass("active");var allDashboardBodies=$('.nav_accordion > dd');allDashboardBodies.slideUp();if(!myDashWasActive){myDashHeader.addClass("active");var myDashBody=myDashHeader.next();myDashBody.slideDown();var activeDashPanel=myDashBody.find("div > ul > li > a.active");if(activeDashPanel.length===0){var activePanel=myDashBody.find("div:first > ul");activePanel.slideDown();activePanel.closest('div').find("h4").addClass("active");var nonActivePanels=myDashBody.find("div:not(:first) > ul");nonActivePanels.slideUp();}
else
{activeDashPanel.closest('div').find("h4").addClass("active");allPanelGroupBodies.each(function(index,value){var activePanels=value.find('li > a.active');if(activePanels.length===0){$(this).slideUp();}});}}
return false;});$('.nav_accordion > dd > div > h4').click(function(){var myPanelGroupHeader=$(this);myPanelGroupWasActive=myPanelGroupHeader.hasClass("active");var allPanelGroupHeaders=$('.nav_accordion > dd > div > h4');allPanelGroupHeaders.removeClass("active");allPanelGroupBodies.slideUp();if(!myPanelGroupWasActive){myPanelGroupHeader.addClass("active");myPanelGroupHeader.closest('div').find('ul').slideDown();}});$('.nav_accordion > dd > ul > li > a').click(function(){horizon.modals.modal_spinner(gettext("Loading"));});});horizon.ajax={_queue:[],_active:[],get_messages:function(request){return request.getResponseHeader("X-Horizon-Messages");},queue:function(opts){var complete=opts.complete,active=horizon.ajax._active;opts.complete=function(){var index=$.inArray(request,active);if(index>-1){active.splice(index,1);}
horizon.ajax.next();if(complete){complete.apply(this,arguments);}};function request(){return $.ajax(opts);}
horizon.ajax._queue.push(request);horizon.ajax.next();},next:function(){var queue=horizon.ajax._queue,limit=horizon.conf.ajax.queue_limit,request;if(queue.length&&(!limit||horizon.ajax._active.length<limit)){request=queue.pop();horizon.ajax._active.push(request);return request();}}};horizon.cookies={read:function(cookie_name){var cookie=$.cookie("horizon."+cookie_name);if(cookie===null){return{};}
return $.parseJSON(cookie);},write:function(cookie_name,data){$.cookie("horizon."+cookie_name,JSON.stringify(data),{path:"/"});},update:function(cookie_name,key,value){var data=horizon.cookies.read("horizon."+cookie_name);data[key]=value;horizon.cookies.write(cookie_name,data);},remove:function(cookie_name){$.cookie("horizon."+cookie_name,null);}};horizon.forms={handle_snapshot_source:function(){$("div.table_wrapper, #modal_wrapper").on("change","select#id_snapshot_source",function(evt){var $option=$(this).find("option:selected");var $form=$(this).closest('form');var $volName=$form.find('input#id_name');if($volName.val()==""){$volName.val($option.data("name"));}
var $volSize=$form.find('input#id_size');var volSize=parseInt($volSize.val(),10)||-1;var dataSize=parseInt($option.data("size"),10)||-1;if(volSize<dataSize){$volSize.val(dataSize);}});},handle_volume_source:function(){$("div.table_wrapper, #modal_wrapper").on("change","select#id_volume_source",function(evt){var $option=$(this).find("option:selected");var $form=$(this).closest('form');var $volName=$form.find('input#id_name');if($volName.val()==""){$volName.val($option.data("name"));}
var $volSize=$form.find('input#id_size');var volSize=parseInt($volSize.val(),10)||-1;var dataSize=parseInt($option.data("size"),10)||-1;if(volSize<dataSize){$volSize.val(dataSize);}});},handle_image_source:function(){$("div.table_wrapper, #modal_wrapper").on("change","select#id_image_source",function(evt){var $option=$(this).find("option:selected");var $form=$(this).closest('form');var $volName=$form.find('input#id_name');if($volName.val()==""){$volName.val($option.data("name"));}
var $volSize=$form.find('input#id_size');var volSize=parseInt($volSize.val(),10)||-1;var dataSize=parseInt($option.data("size"),10)||-1;var minDiskSize=parseInt($option.data("min_disk"),10)||-1;var defaultVolSize=dataSize;if(minDiskSize>defaultVolSize){defaultVolSize=minDiskSize;}
if(volSize<defaultVolSize){$volSize.val(defaultVolSize);}});},datepicker:function(){var startDate=$('input#id_start').datepicker().on('changeDate',function(ev){if(ev.date.valueOf()>endDate.date.valueOf()){var newDate=new Date(ev.date);newDate.setDate(newDate.getDate()+1);endDate.setValue(newDate);$('input#id_end')[0].focus();}
startDate.hide();}).data('datepicker');var endDate=$('input#id_end').datepicker({onRender:function(date){return date.valueOf()<startDate.date.valueOf()?'disabled':'';}}).on('changeDate',function(ev){endDate.hide();}).data('datepicker');}};horizon.forms.bind_add_item_handlers=function(el){var $selects=$(el).find('select[data-add-item-url]');$selects.each(function(){var $this=$(this);$button=$("<a href='"+$this.attr("data-add-item-url")+"' "+"data-add-to-field='"+$this.attr("id")+"' "+"class='btn ajax-add ajax-modal btn-inline'>+</a>");$this.after($button);});};horizon.forms.prevent_multiple_submission=function(el){var $form=$(el).find("form");$form.submit(function(){var button=$(this).find('[type="submit"]');if(button.hasClass('btn-primary')&&!button.hasClass('always-enabled')){$(this).submit(function(){return false;});button.removeClass('primary').addClass('disabled');button.attr('disabled','disabled');}
return true;});};horizon.forms.init_examples=function(el){var $el=$(el);$el.find("#create_image_form input#id_copy_from").attr("placeholder","http://example.com/image.iso");$el.find(".table_search input").attr("placeholder",gettext("Filter"));$el.find("#attach_volume_form #id_device").attr("placeholder","/dev/vdc");};horizon.addInitFunction(function(){horizon.forms.prevent_multiple_submission($('body'));horizon.modals.addModalInitFunction(horizon.forms.prevent_multiple_submission);horizon.forms.bind_add_item_handlers($("body"));horizon.modals.addModalInitFunction(horizon.forms.bind_add_item_handlers);horizon.forms.init_examples($("body"));horizon.modals.addModalInitFunction(horizon.forms.init_examples);horizon.forms.handle_snapshot_source();horizon.forms.handle_volume_source();horizon.forms.handle_image_source();horizon.forms.datepicker();$("body").on("click","form button.btn-danger",function(evt){horizon.datatables.confirm(this);evt.preventDefault();});$(document).on("change",'select.switchable',function(evt){var $fieldset=$(evt.target).closest('fieldset'),$switchables=$fieldset.find('.switchable');$switchables.each(function(index,switchable){var $switchable=$(switchable),slug=$switchable.data('slug'),visible=$switchable.is(':visible'),val=$switchable.val();$fieldset.find('.switched[data-switch-on*="'+slug+'"]').each(function(index,input){var $input=$(input),data=$input.data(slug+"-"+val);if(typeof data==="undefined"||!visible){$input.closest('.form-field').hide();}else{$('label[for='+$input.attr('id')+']').html(data);$input.closest('.form-field').show();}});});});$('select.switchable').trigger('change');horizon.modals.addModalInitFunction(function(modal){$(modal).find('select.switchable').trigger('change');});function update_volume_source_displayed_fields(field){var $this=$(field),base_type=$this.val();$this.find("option").each(function(){if(this.value!==base_type){$("#id_"+this.value).closest(".control-group").hide();}else{$("#id_"+this.value).closest(".control-group").show();}});}
$(document).on('change','#id_volume_source_type',function(evt){update_volume_source_displayed_fields(this);});$('#id_volume_source_type').change();horizon.modals.addModalInitFunction(function(modal){$(modal).find("#id_volume_source_type").change();});$(document).tooltip({selector:"div.form-field :input:not(:checkbox)",placement:function(tip,input){return $(input).closest("form[class*='split']").length?"bottom":'right';},trigger:'focus',title:function(){return $(this).closest('div.form-field').children('.help-block').text();}});$(document).on('mousedown keydown','.form-field select',function(evt){$(this).tooltip('hide');});$(document).on('keydown.esc_btn',function(evt){if(evt.keyCode===27){$('.tooltip').hide();}});$('span.help-block').hide();});horizon.formset_table=(function(){'use strict';var module={};module.reenumerate_rows=function(table,prefix){var count=0;var input_name_re=new RegExp('^'+prefix+'-(\\d+|__prefix__)-');var input_id_re=new RegExp('^id_'+prefix+'-(\\d+|__prefix__)-');table.find('tbody tr').each(function(){$(this).find('input').each(function(){var input=$(this);input.attr('name',input.attr('name').replace(input_name_re,prefix+'-'+count+'-'));input.attr('id',input.attr('id').replace(input_id_re,'id_'+prefix+'-'+count+'-'));});count+=1;});$('#id_'+prefix+'-TOTAL_FORMS').val(count);};module.delete_row=function(e){$(this).closest('tr').hide();$(this).prev('input[name$="-DELETE"]').attr('checked',true);};module.replace_delete=function(where){where.find('input[name$="-DELETE"]').hide().after($('<a href="#" class="close">×</a>').click(module.delete_row));};module.add_row=function(table,prefix,empty_row_html){var new_row=$(empty_row_html);module.replace_delete(new_row);table.find('tbody').append(new_row);module.reenumerate_rows(table,prefix);};module.init=function(prefix,empty_row_html,add_label){var table=$('table#'+prefix);module.replace_delete(table);if(add_label){var button=$('<a href="#" class="btn btn-small pull-right">'+
add_label+'</a>');table.find('tfoot td').append(button);button.click(function(){module.add_row(table,prefix,empty_row_html);});}
var initial_forms=+$('#id_'+prefix+'-INITIAL_FORMS').val();var total_forms=+$('#id_'+prefix+'-TOTAL_FORMS').val();if(table.find('tbody tr').length>1&&table.find('tbody td.error').length===0&&total_forms>initial_forms){table.find('tbody tr').each(function(index){if(index>=initial_forms){$(this).remove();}});module.reenumerate_rows(table,prefix);$('#id_'+prefix+'-INITIAL_FORMS').val($('#id_'+prefix+'-TOTAL_FORMS').val());}
table.find('td.error[title]').tooltip();};return module;}());horizon.instances={user_decided_length:false,networks_selected:[],networks_available:[],getConsoleLog:function(via_user_submit){var form_element=$("#tail_length"),data;if(!via_user_submit){via_user_submit=false;}
if(this.user_decided_length){data=$(form_element).serialize();}else{data="length=35";}
$.ajax({url:$(form_element).attr('action'),data:data,method:'get',success:function(response_body){$('pre.logs').text(response_body);},error:function(response){if(via_user_submit){horizon.clearErrorMessages();horizon.alert('error',gettext('There was a problem communicating with the server, please try again.'));}}});},get_network_element:function(network_id){return $('li > label[for^="id_network_'+network_id+'"]');},init_network_list:function(){horizon.instances.networks_selected=[];horizon.instances.networks_available=[];$(this.get_network_element("")).each(function(){var $this=$(this);var $input=$this.children("input");var network_property={name:$this.text().replace(/^\s+/,""),id:$input.attr("id"),value:$input.attr("value")};if($input.is(':checked')){horizon.instances.networks_selected.push(network_property);}else{horizon.instances.networks_available.push(network_property);}});},generate_network_element:function(name,id,value){var $li=$('<li>');$li.attr('name',value).html(name+'<em class="network_id">('+value+')</em><a href="#" class="btn btn-primary"></a>');return $li;},generate_networklist_html:function(){var self=this;var updateForm=function(){var lists=$("#networkListId div.input li").attr('data-index',100);var active_networks=$("#selected_network > li").map(function(){return $(this).attr("name");});$("#networkListId div.input input:checkbox").removeAttr('checked');active_networks.each(function(index,value){$("#networkListId div.input input:checkbox[value="+value+"]").attr('checked','checked').parents("li").attr('data-index',index);});$("#networkListId div.input ul").html(lists.sort(function(a,b){if($(a).data("index")<$(b).data("index")){return-1;}
if($(a).data("index")>$(b).data("index")){return 1;}
return 0;}));};$("#networkListSortContainer").show();$("#networkListIdContainer").hide();self.init_network_list();$("#available_network").empty();$.each(self.networks_available,function(index,value){$("#available_network").append(self.generate_network_element(value.name,value.id,value.value));});$("#selected_network").empty();$.each(self.networks_selected,function(index,value){$("#selected_network").append(self.generate_network_element(value.name,value.id,value.value));});$(".networklist > li > a.btn").click(function(e){var $this=$(this);e.preventDefault();e.stopPropagation();if($this.parents("ul#available_network").length>0){$this.parent().appendTo($("#selected_network"));}else if($this.parents("ul#selected_network").length>0){$this.parent().appendTo($("#available_network"));}
updateForm();});if($("#networkListId > div.control-group.error").length>0){var errortext=$("#networkListId > div.control-group.error").find("span.help-inline").text();$("#selected_network_label").before($('<div class="dynamic-error">').html(errortext));}
$(".networklist").sortable({connectWith:"ul.networklist",placeholder:"ui-state-highlight",distance:5,start:function(e,info){$("#selected_network").addClass("dragging");},stop:function(e,info){$("#selected_network").removeClass("dragging");updateForm();}}).disableSelection();},workflow_init:function(modal){horizon.instances.generate_networklist_html();}};horizon.addInitFunction(function(){$(document).on('submit','#tail_length',function(evt){horizon.instances.user_decided_length=true;horizon.instances.getConsoleLog(true);evt.preventDefault();});function update_launch_source_displayed_fields(field){var $this=$(field),base_type=$this.val();$this.closest(".control-group").nextAll().hide();switch(base_type){case"image_id":$("#id_image_id").closest(".control-group").show();break;case"instance_snapshot_id":$("#id_instance_snapshot_id").closest(".control-group").show();break;case"volume_id":$("#id_volume_id").closest(".control-group").show();break;case"volume_image_id":$("#id_image_id, #id_volume_size, #id_device_name, , #id_delete_on_terminate").closest(".control-group").show();break;case"volume_snapshot_id":$("#id_volume_snapshot_id, #id_device_name, #id_delete_on_terminate").closest(".control-group").show();break;}}
$(document).on('change','.workflow #id_source_type',function(evt){update_launch_source_displayed_fields(this);});$('.workflow #id_source_type').change();horizon.modals.addModalInitFunction(function(modal){$(modal).find("#id_source_type").change();});function update_image_id_fields(field){var $this=$(field),volume_opt=$this.val();var $option=$this.find("option:selected");var $form=$this.closest('form');var $volSize=$form.find('input#id_volume_size');$volSize.val($option.data("volume_size"));}
$(document).on('change','.workflow #id_image_id',function(evt){update_image_id_fields(this);});horizon.instances.decrypt_password=function(encrypted_password,private_key){var crypt=new JSEncrypt();crypt.setKey(private_key);return crypt.decrypt(encrypted_password);};$(document).on('change','#id_private_key_file',function(evt){var file=evt.target.files[0];var reader=new FileReader();if(file){reader.onloadend=function(event){$("#id_private_key").val(event.target.result);};reader.onerror=function(event){horizon.clearErrorMessages();horizon.alert('error',gettext('Could not read the file'));};reader.readAsText(file);}
else{horizon.clearErrorMessages();horizon.alert('error',gettext('Could not decrypt the password'));}});$(document).on('show','#password_instance_modal',function(evt){$("#id_decrypted_password").css("font-family","monospace");$("#id_decrypted_password").css("cursor","text");$("#id_encrypted_password").css("cursor","text");$("#id_keypair_name").css("cursor","text");});$(document).on('click','#decryptpassword_button',function(evt){encrypted_password=$("#id_encrypted_password").val();private_key=$('#id_private_key').val();if(!private_key){evt.preventDefault();$(this).closest('.modal').modal('hide');}
else{if(private_key.length>0){evt.preventDefault();decrypted_password=horizon.instances.decrypt_password(encrypted_password,private_key);if(decrypted_password===false||decrypted_password===null){horizon.clearErrorMessages();horizon.alert('error',gettext('Could not decrypt the password'));}
else{$("#id_decrypted_password").val(decrypted_password);$("#decryptpassword_button").hide();}}}});});horizon.alert=function(type,message,extra_tags){safe=false;if(typeof(extra_tags)!=="undefined"&&$.inArray('safe',extra_tags.split(' '))!==-1){safe=true;}
var template=horizon.templates.compiled_templates["#alert_message_template"],params={"type":type,"type_display":{'danger':gettext("Danger: "),'warning':gettext("Warning: "),'info':gettext("Notice: "),'success':gettext("Success: "),'error':gettext("Error: ")}[type],"message":message,"safe":safe};return $(template.render(params)).hide().prependTo("#main_content .messages").fadeIn(100);};horizon.clearErrorMessages=function(){$('#main_content .messages .alert.alert-error').remove();};horizon.clearSuccessMessages=function(){$('#main_content .messages .alert.alert-success').remove();};horizon.clearAllMessages=function(){horizon.clearErrorMessages();horizon.clearSuccessMessages();};horizon.autoDismissAlerts=function(){var $alerts=$('#main_content .messages .alert');$alerts.each(function(index,alert){var $alert=$(this),types=$alert.attr('class').split(' '),intersection=$.grep(types,function(value){return $.inArray(value,horizon.conf.auto_fade_alerts.types)!==-1;});if(intersection.length>0){setTimeout(function(){$alert.fadeOut(horizon.conf.auto_fade_alerts.fade_duration);},horizon.conf.auto_fade_alerts.delay);}});};horizon.addInitFunction(function(){$("body").ajaxComplete(function(event,request,settings){var message_array=$.parseJSON(horizon.ajax.get_messages(request));$(message_array).each(function(index,item){horizon.alert(item[0],item[1],item[2]);});});$('a.ajax-modal').click(function(){horizon.clearAllMessages();});$(".alert").alert();horizon.autoDismissAlerts();});horizon.modals={_request:null,spinner:null,_init_functions:[]};horizon.modals.addModalInitFunction=function(f){horizon.modals._init_functions.push(f);};horizon.modals.initModal=function(modal){$(horizon.modals._init_functions).each(function(index,f){f(modal);});};horizon.modals.create=function(title,body,confirm,cancel){if(!cancel){cancel=gettext("Cancel");}
var template=horizon.templates.compiled_templates["#modal_template"],params={title:title,body:body,confirm:confirm,cancel:cancel},modal=$(template.render(params)).appendTo("#modal_wrapper");return modal;};horizon.modals.success=function(data,textStatus,jqXHR){var modal;$('#modal_wrapper').append(data);$('.modal span.help-block').hide();modal=$('.modal:last');modal.modal();$(modal).trigger("new_modal",modal);return modal;};horizon.modals.modal_spinner=function(text){var template=horizon.templates.compiled_templates["#spinner-modal"];horizon.modals.spinner=$(template.render({text:text}));horizon.modals.spinner.appendTo("#modal_wrapper");horizon.modals.spinner.modal({backdrop:'static'});horizon.modals.spinner.spin(horizon.conf.spinner_options.modal);};horizon.addInitFunction(function(){$('#modal_wrapper').on('new_modal',function(evt,modal){horizon.modals.initModal(modal);});$(document).on('click','.modal .cancel',function(evt){$(this).closest('.modal').modal('hide');evt.preventDefault();});$(document).on('submit','.modal form',function(evt){var $form=$(this),$button=$form.find(".modal-footer .btn-primary"),update_field_id=$form.attr("data-add-to-field"),headers={};if($form.attr("enctype")==="multipart/form-data"){return;}
evt.preventDefault();$button.prop("disabled",true);if(update_field_id){headers["X-Horizon-Add-To-Field"]=update_field_id;}
$.ajax({type:"POST",url:$form.attr('action'),headers:headers,data:$form.serialize(),beforeSend:function(){$("#modal_wrapper .modal").last().modal("hide");horizon.modals.modal_spinner(gettext("Working"));},complete:function(){horizon.modals.spinner.modal('hide');$("#modal_wrapper .modal").last().modal("show");$button.prop("disabled",false);},success:function(data,textStatus,jqXHR){var redirect_header=jqXHR.getResponseHeader("X-Horizon-Location"),add_to_field_header=jqXHR.getResponseHeader("X-Horizon-Add-To-Field"),json_data,field_to_update;$form.closest(".modal").modal("hide");if(redirect_header){location.href=redirect_header;}
else if(add_to_field_header){json_data=$.parseJSON(data);field_to_update=$("#"+add_to_field_header);field_to_update.append("<option value='"+json_data[0]+"'>"+json_data[1]+"</option>");field_to_update.change();field_to_update.val(json_data[0]);}else{horizon.modals.success(data,textStatus,jqXHR);}},error:function(jqXHR,status,errorThrown){if(jqXHR.getResponseHeader('logout')){location.href=jqXHR.getResponseHeader("X-Horizon-Location");}else{$form.closest(".modal").modal("hide");horizon.alert("error",gettext("There was an error submitting the form. Please try again."));}}});});$(document).on('show','.modal',function(evt){if($(evt.target).hasClass("modal")){var scrollShift=$('body').scrollTop()||$('html').scrollTop(),$this=$(this),topVal=$this.css('top');$this.css('top',scrollShift+parseInt(topVal,10));}
$("select",evt.target).keyup(function(e){if(e.keyCode===27){e.target.blur();e.stopPropagation();}});});horizon.modals.addModalInitFunction(function(modal){$(modal).find(":text, select, textarea").filter(":visible:first").focus();});horizon.modals.addModalInitFunction(function(modal){var _max_visited_step=0;var _validate_steps=function(start,end){var $form=$('.workflow > form'),response={};if(typeof end==='undefined'){end=start;}
$form.find('td.actions div.alert-error').remove();$form.find('.control-group.error').each(function(){var $group=$(this);$group.removeClass('error');$group.find('span.help-inline.error').remove();});$.ajax({type:'POST',url:$form.attr('action'),headers:{'X-Horizon-Validate-Step-Start':start,'X-Horizon-Validate-Step-End':end},data:$form.serialize(),dataType:'json',async:false,success:function(data){response=data;}});if(response.has_errors){var first_field=true;$.each(response.errors,function(step_slug,step_errors){var step_id=response.workflow_slug+'__'+step_slug,$fieldset=$form.find('#'+step_id);$.each(step_errors,function(field,errors){var $field;if(field==='__all__'){$.each(errors,function(index,error){$fieldset.find('td.actions').prepend('<div class="alert alert-message alert-error">'+
error+'</div>');});$fieldset.find('input,  select, textarea').first().focus();return;}
$field=$fieldset.find('[name="'+field+'"]');$field.closest('.control-group').addClass('error');$.each(errors,function(index,error){$field.before('<span class="help-inline error">'+
error+'</span>');});if(first_field){$field.focus();first_field=false;}});});return false;}};$('.workflow.wizard').bootstrapWizard({tabClass:'wizard-tabs',nextSelector:'.button-next',previousSelector:'.button-previous',onTabShow:function(tab,navigation,index){var $navs=navigation.find('li');var total=$navs.length;var current=index;var $footer=$('.modal-footer');_max_visited_step=Math.max(_max_visited_step,current);if(current+1>=total){$footer.find('.button-next').hide();$footer.find('.button-final').show();}else{$footer.find('.button-next').show();$footer.find('.button-final').hide();}
$navs.each(function(i){$this=$(this);if(i<=_max_visited_step){$this.addClass('done');}else{$this.removeClass('done');}});},onNext:function($tab,$nav,index){return _validate_steps(index-1);},onTabClick:function($tab,$nav,current,index){return(index<=current||_validate_steps(current,index-1)!==false);}});});horizon.modals.addModalInitFunction(horizon.datatables.validate_button);$(document).on('click','.ajax-modal',function(evt){var $this=$(this);if(horizon.modals._request&&typeof(horizon.modals._request.abort)!==undefined){horizon.modals._request.abort();}
horizon.modals._request=$.ajax($this.attr('href'),{beforeSend:function(){horizon.modals.modal_spinner(gettext("Loading"));},complete:function(){horizon.modals._request=null;horizon.modals.spinner.modal('hide');},error:function(jqXHR,status,errorThrown){if(jqXHR.status===401){var redir_url=jqXHR.getResponseHeader("X-Horizon-Location");if(redir_url){location.href=redir_url;}else{location.reload(true);}}
else{if(!horizon.ajax.get_messages(jqXHR)){horizon.alert("error",gettext("An error occurred. Please try again later."));}}},success:function(data,textStatus,jqXHR){var update_field_id=$this.attr('data-add-to-field'),modal,form;modal=horizon.modals.success(data,textStatus,jqXHR);if(update_field_id){form=modal.find("form");if(form.length){form.attr("data-add-to-field",update_field_id);}}}});evt.preventDefault();});$(document).on("show",".modal",function(){var container=$("#modal_wrapper"),modal_stack=container.find(".modal"),$this=$(this);modal_stack.splice(modal_stack.length-1,1);modal_stack.modal("hide");horizon.utils.loadAngular(container);});$(document).on('hidden','.modal',function(){var $this=$(this),modal_stack=$("#modal_wrapper .modal");if($this[0]===modal_stack.last()[0]||$this.hasClass("loading")){$this.remove();if(!$this.hasClass("loading")){$("#modal_wrapper .modal").last().modal("show");}}});});horizon.Quota={is_flavor_quota:false,user_value_progress_bars:[],auto_value_progress_bars:[],flavor_progress_bars:[],user_value_form_inputs:[],selected_flavor:null,flavors:[],init:function(){this.user_value_progress_bars=$('div[data-progress-indicator-for]');this.auto_value_progress_bars=$('div[data-progress-indicator-step-by]');this.user_value_form_inputs=$($.map(this.user_value_progress_bars,function(elm){return('#'+$(elm).attr('data-progress-indicator-for'));}));this._initialCreation(this.user_value_progress_bars);this._initialCreation(this.auto_value_progress_bars);this._initialCreation(this.flavor_progress_bars);this._initialAnimations();this._attachInputHandlers();},belowMinimum:function(minimum,actual){return parseInt(minimum,10)>parseInt(actual,10);},imageFitsFlavor:function(image,flavor){if(image===undefined){return true;}else{overDisk=horizon.Quota.belowMinimum(image.min_disk,flavor.disk);overRAM=horizon.Quota.belowMinimum(image.min_ram,flavor.ram);return!(overDisk||overRAM);}},noteDisabledFlavors:function(allDisabled){if($('#some_flavors_disabled').length===0){message=allDisabled?horizon.Quota.allFlavorsDisabledMessage:horizon.Quota.disabledFlavorMessage;$('#id_flavor').parent().append("<span id='some_flavors_disabled'>"+
message+'</span>');}},resetFlavors:function(){if($('#some_flavors_disabled')){$('#some_flavors_disabled').remove();$('#id_flavor option').each(function(){$(this).attr('disabled',false);});}},findImageById:function(id){_image=undefined;$.each(horizon.Quota.images,function(i,image){if(image.id===id){_image=image;}});return _image;},getSelectedImage:function(){selected=$('#id_image_id option:selected').val();return horizon.Quota.findImageById(selected);},disableFlavorsForImage:function(image){image=horizon.Quota.getSelectedImage();to_disable=[];horizon.Quota.resetFlavors();$.each(horizon.Quota.flavors,function(i,flavor){if(!horizon.Quota.imageFitsFlavor(image,flavor)){to_disable.push(flavor.name);}});flavors=$('#id_flavor option');$.each(to_disable,function(i,flavor_name){flavors.each(function(){if($(this).text()===flavor_name){$(this).attr('disabled','disabled');}});});if(to_disable.length>0){selected=($('#id_flavor option').filter(':selected'))[0];if(to_disable.length<flavors.length&&selected.disabled){flavors.each(function(index,element){if(!element.disabled){$('#id_flavor').val(element.value);$('#id_flavor').change();return false;}});}
horizon.Quota.noteDisabledFlavors(to_disable.length===flavors.length);}},initWithImages:function(images,disabledMessage,allDisabledMessage){this.images=images;this.disabledFlavorMessage=disabledMessage;this.allFlavorsDisabledMessage=allDisabledMessage;horizon.Quota.disableFlavorsForImage();},initWithFlavors:function(flavors){this.is_flavor_quota=true;this.flavor_progress_bars=$('div[data-progress-indicator-flavor]');this.flavors=flavors;this.init();this.showFlavorDetails();this.updateFlavorUsage();},getSelectedFlavor:function(){if(this.is_flavor_quota){this.selected_flavor=$.grep(this.flavors,function(flavor){return flavor.id===$("#id_flavor").children(":selected").val();})[0];}else{this.selected_flavor=null;}
return this.selected_flavor;},showFlavorDetails:function(){this.getSelectedFlavor();if(this.selected_flavor){var name=horizon.utils.truncate(this.selected_flavor.name,14,true);var vcpus=horizon.utils.humanizeNumbers(this.selected_flavor.vcpus);var disk=horizon.utils.humanizeNumbers(this.selected_flavor.disk);var ephemeral=horizon.utils.humanizeNumbers(this.selected_flavor["OS-FLV-EXT-DATA:ephemeral"]);var disk_total=this.selected_flavor.disk+this.selected_flavor["OS-FLV-EXT-DATA:ephemeral"];var disk_total_display=horizon.utils.humanizeNumbers(disk_total);var ram=horizon.utils.humanizeNumbers(this.selected_flavor.ram);$("#flavor_name").html(name);$("#flavor_vcpus").text(vcpus);$("#flavor_disk").text(disk);$("#flavor_ephemeral").text(ephemeral);$("#flavor_disk_total").text(disk_total_display);$("#flavor_ram").text(ram);}},updateFlavorUsage:function(){if(!this.is_flavor_quota){return;}
var scope=this;var instance_count=(parseInt($("#id_count").val(),10)||1);var update_amount=0;this.getSelectedFlavor();$(this.flavor_progress_bars).each(function(index,element){var element_id=$(element).attr('id');var progress_stat=element_id.match(/^quota_(.+)/)[1];if(progress_stat===undefined){return;}else if(progress_stat==='instances'){update_amount=instance_count;}else if(scope.selected_flavor){update_amount=(scope.selected_flavor[progress_stat]*instance_count);}
scope.updateUsageFor(element,update_amount);});},updateUsageFor:function(progress_element,increment_by){progress_element=$(progress_element);var quota_limit=parseInt(progress_element.attr('data-quota-limit'),10);var quota_used=parseInt(progress_element.attr('data-quota-used'),10);var percentage_to_update=((increment_by/quota_limit)*100);var percentage_used=((quota_used/quota_limit)*100);this.update($(progress_element).attr('id'),percentage_to_update);},drawUsed:function(element,used){var w="100%";var h=20;var lvl_curve=4;var bkgrnd="#F2F2F2";var frgrnd="#006CCF";var full="#D0342B";var addition="#00D300";var nearlyfull="orange";var bar=d3.select("#"+element).append("svg:svg").attr("class","chart").attr("width",w).attr("height",h).style("background-color","white").append("g");bar.append("rect").attr("y",0).attr("width",w).attr("height",h).attr("rx",lvl_curve).attr("ry",lvl_curve).style("fill",bkgrnd).style("stroke","#CCCCCC").style("stroke-width",1);bar.append("rect").attr("y",0).attr("class","newbar").attr("width",0).attr("height",h).attr("rx",lvl_curve).attr("ry",lvl_curve).style("fill",function(){return addition;});var used_bar=bar.insert("rect").attr("class","usedbar").attr("y",0).attr("id","test").attr("width",0).attr("height",h).attr("rx",lvl_curve).attr("ry",lvl_curve).style("fill",function(){return frgrnd;}).attr("d",used).transition().duration(500).attr("width",used+"%").style("fill",function(){if(used>=100){return full;}
else if(used>=80){return nearlyfull;}
else{return frgrnd;}});},update:function(element,value){var full="#D0342B";var addition="#00D300";var already_used=parseInt(d3.select("#"+element).select(".usedbar").attr("d"));d3.select("#"+element).select(".newbar").transition().duration(500).attr("width",function(){if((value+already_used)>=100){return"100%";}else{return(value+already_used)+"%";}}).style("fill",function(){if(value>(100-already_used)){return full;}else{return addition;}});},_attachInputHandlers:function(){var scope=this;if(this.is_flavor_quota){var eventCallback=function(evt){scope.showFlavorDetails();scope.updateFlavorUsage();};var imageChangeCallback=function(event){scope.disableFlavorsForImage();};$('#id_flavor').on('change',eventCallback);$('#id_count').on('keyup',eventCallback);$('#id_image_id').on('change',imageChangeCallback);}
$(this.user_value_form_inputs).each(function(index,element){$(element).on('keyup',function(evt){var progress_element=$('div[data-progress-indicator-for='+$(evt.target).attr('id')+']');var integers_in_input=$(evt.target).val().match(/\d+/g);var user_integer;if(integers_in_input===null){user_integer=0;}else if(integers_in_input.length>1){user_integer=integers_in_input.join('');}else if(integers_in_input.length===1){user_integer=integers_in_input[0];}
var progress_amount=parseInt(user_integer,10);scope.updateUsageFor(progress_element,progress_amount);});});},_initialAnimations:function(){var scope=this;$(this.auto_value_progress_bars).each(function(index,element){var auto_progress=$(element);var update_amount=parseInt(auto_progress.attr('data-progress-indicator-step-by'),10);scope.updateUsageFor(auto_progress,update_amount);});},_initialCreation:function(bars){var scope=this;$(bars).each(function(index,element){var progress_element=$(element);var quota_limit=parseInt(progress_element.attr('data-quota-limit'),10);var quota_used=parseInt(progress_element.attr('data-quota-used'),10);var percentage_used=0;if(!isNaN(quota_limit)&&!isNaN(quota_used)){percentage_used=(quota_used/quota_limit)*100;}
scope.drawUsed($(element).attr('id'),percentage_used);});}};horizon.datatables={update:function(){var $rows_to_update=$('tr.status_unknown.ajax-update');if($rows_to_update.length){var interval=$rows_to_update.attr('data-update-interval'),$table=$rows_to_update.closest('table'),decay_constant=$table.attr('decay_constant');if($rows_to_update.find('.actions_column .btn-group.open').length){setTimeout(horizon.datatables.update,interval);$table.removeAttr('decay_constant');return;}
$rows_to_update.each(function(index,row){var $row=$(this),$table=$row.closest('table.datatable');horizon.ajax.queue({url:$row.attr('data-update-url'),error:function(jqXHR,textStatus,errorThrown){switch(jqXHR.status){case 404:var $footer,row_count,footer_text,colspan,template,params,$empty_row;row_count=horizon.datatables.update_footer_count($table,-1);if(row_count===0){colspan=$table.find('th[colspan]').attr('colspan');template=horizon.templates.compiled_templates["#empty_row_template"];params={"colspan":colspan,no_items_label:gettext("No items to display.")};empty_row=template.render(params);$row.replaceWith(empty_row);}else{$row.remove();}
$table.trigger("update");break;default:horizon.utils.log(gettext("An error occurred while updating."));$row.removeClass("ajax-update");$row.find("i.ajax-updating").remove();break;}},success:function(data,textStatus,jqXHR){var $new_row=$(data);if($new_row.hasClass('status_unknown')){var spinner_elm=$new_row.find("td.status_unknown:last");if($new_row.find('.btn-action-required').length>0){spinner_elm.prepend($("<div />").addClass("action_required_img").append($("<img />").attr("src","/static/dashboard/img/action_required.png")));}else{spinner_elm.prepend($("<div />").addClass("loading_gif").append($("<img />").attr("src","/static/dashboard/img/loading.gif")));}}
if($new_row.html()!==$row.html()){if($row.find('.table-row-multi-select:checkbox').is(':checked')){$new_row.find('.table-row-multi-select:checkbox').prop('checked',true);}
$row.replaceWith($new_row);$table.trigger("update");$table.removeAttr('decay_constant');}},complete:function(jqXHR,textStatus){horizon.datatables.validate_button();if(decay_constant===undefined){decay_constant=1;}else{decay_constant++;}
$table.attr('decay_constant',decay_constant);next_poll=interval*decay_constant;if(next_poll>30*1000){next_poll=30*1000;}
setTimeout(horizon.datatables.update,next_poll);}});});}},validate_button:function(){$("form").each(function(i){var checkboxes=$(this).find(".table-row-multi-select:checkbox");var action_buttons=$(this).find(".table_actions button.btn-danger");action_buttons.toggleClass("disabled",!checkboxes.filter(":checked").length);});}};horizon.datatables.confirm=function(action){var $action=$(action),$modal_parent=$(action).closest('.modal'),name_array=[],closest_table_id,action_string,name_string,title,body,modal,form;if($action.hasClass("disabled")){return;}
action_string=$action.text();name_string="";closest_table_id=$(action).closest("table").attr("id");if($("#"+closest_table_id+" tr[data-display]").length>0){if($(action).closest("div").hasClass("table_actions")){$("#"+closest_table_id+" tr[data-display]").has(".table-row-multi-select:checkbox:checked").each(function(){name_array.push(" \""+$(this).attr("data-display")+"\"");});name_array.join(", ");name_string=name_array.toString();}else{name_string=" \""+$(action).closest("tr").attr("data-display")+"\"";}
name_string=interpolate(gettext("You have selected %s. "),[name_string]);}
title=interpolate(gettext("Confirm %s"),[action_string]);body=name_string+gettext("Please confirm your selection. This action cannot be undone.");modal=horizon.modals.create(title,body,action_string);modal.modal();if($modal_parent.length){var child_backdrop=modal.next('.modal-backdrop');child_backdrop.css('z-index',$modal_parent.css('z-index')+10);modal.css('z-index',child_backdrop.css('z-index')+10);}
modal.find('.btn-primary').click(function(evt){form=$action.closest('form');form.append("<input type='hidden' name='"+$action.attr('name')+"' value='"+$action.attr('value')+"'/>");form.submit();modal.modal('hide');horizon.modals.modal_spinner(gettext("Working"));return false;});return modal;};$.tablesorter.addParser({id:'sizeSorter',is:function(s){return false;},format:function(s){var sizes={BYTE:0,B:0,KB:1,MB:2,GB:3,TB:4,PB:5};var regex=/([\d\.,]+)\s*(byte|B|KB|MB|GB|TB|PB)+/i;var match=s.match(regex);if(match&&match.length===3){return parseFloat(match[1])*Math.pow(1024,sizes[match[2].toUpperCase()]);}
return parseInt(s,10);},type:'numeric'});$.tablesorter.addParser({id:'timesinceSorter',is:function(s){return false;},format:function(s,table,cell,cellIndex){return $(cell).find('span').data('seconds');},type:'numeric'});horizon.datatables.disable_buttons=function(){$("table .table_actions").on("click",".btn.disabled",function(event){event.preventDefault();event.stopPropagation();});};horizon.datatables.update_footer_count=function(el,modifier){var $el=$(el),$browser,$footer,row_count,footer_text_template,footer_text;if(!modifier){modifier=0;}
$browser=$el.closest("#browser_wrapper");if($browser.length){$footer=$browser.find('.tfoot span.content_table_count');}
else{$footer=$el.find('tfoot span.table_count');}
row_count=$el.find('tbody tr:visible').length+modifier-$el.find('.empty').length;footer_text_template=ngettext("Displaying %s item","Displaying %s items",row_count);footer_text=interpolate(footer_text_template,[row_count]);$footer.text(footer_text);return row_count;};horizon.datatables.add_no_results_row=function(table){template=horizon.templates.compiled_templates["#empty_row_template"];if(!table.find("tbody tr:visible").length&&typeof(template)!=="undefined"){colspan=table.find("th[colspan]").attr('colspan');params={"colspan":colspan,no_items_label:gettext("No items to display.")};table.find("tbody").append(template.render(params));}};horizon.datatables.remove_no_results_row=function(table){table.find("tr.empty").remove();};horizon.datatables.fix_row_striping=function(table){table.trigger('applyWidgetId',['zebra']);};horizon.datatables.set_table_sorting=function(parent){$(parent).find("table.datatable").each(function(){var $table=$(this),header_options={};if($table.find('tbody tr').not('.empty').length>1){$table.find("thead th[class!='table_header']").each(function(i,val){$th=$(this);if(!$th.hasClass('sortable')){header_options[i]={sorter:false};}else if($th.data('type')==='size'){header_options[i]={sorter:'sizeSorter'};}else if($th.data('type')==='ip'){header_options[i]={sorter:'ipAddress'};}else if($th.data('type')==='timesince'){header_options[i]={sorter:'timesinceSorter'};}});$table.tablesorter({headers:header_options,widgets:['zebra'],selectorHeaders:"thead th[class!='table_header']",cancelSelection:false});}});};horizon.datatables.add_table_checkboxes=function(parent){$(parent).find('table thead .multi_select_column').each(function(index,thead){if(!$(thead).find('.table-row-multi-select:checkbox').length&&$(thead).parents('table').find('tbody .table-row-multi-select:checkbox').length){$(thead).append('<input type="checkbox" class="table-row-multi-select">');}});};horizon.datatables.set_table_query_filter=function(parent){$(parent).find('table').each(function(index,elm){var input=$($(elm).find('div.table_search.client input')),table_selector;if(input.length>0){input.on('keypress',function(evt){if(evt.keyCode===13){return false;}});input.next('button.btn-search').on('click keypress',function(evt){return false;});table_selector='table#'+$(elm).attr('id');input.quicksearch(table_selector+' tbody tr',{'delay':300,'loader':'span.loading','bind':'keyup click','show':this.show,'hide':this.hide,onBefore:function(){var table=$(table_selector);horizon.datatables.remove_no_results_row(table);},onAfter:function(){var template,table,colspan,params;table=$(table_selector);horizon.datatables.update_footer_count(table);horizon.datatables.add_no_results_row(table);horizon.datatables.fix_row_striping(table);},prepareQuery:function(val){return new RegExp(val,"i");},testQuery:function(query,txt,_row){return query.test($(_row).find('td:not(.hidden):not(.actions_column)').text());}});}});};horizon.datatables.set_table_fixed_filter=function(parent){$(parent).find('table.datatable').each(function(index,elm){$(elm).on('click','div.table_filter button',function(evt){var table=$(elm);var category=$(this).val();evt.preventDefault();horizon.datatables.remove_no_results_row(table);table.find('tbody tr').hide();table.find('tbody tr.category-'+category).show();horizon.datatables.update_footer_count(table);horizon.datatables.add_no_results_row(table);horizon.datatables.fix_row_striping(table);});$(elm).find('div.table_filter button').each(function(i,button){if($(button).text().indexOf(' (0)')===-1){$(button).addClass('active');$(button).trigger('click');return false;}});});};horizon.addInitFunction(function(){horizon.datatables.validate_button();horizon.datatables.disable_buttons();$('table.datatable').each(function(idx,el){horizon.datatables.update_footer_count($(el),0);});$('div.table_wrapper, #modal_wrapper').on('click','table thead .multi_select_column .table-row-multi-select:checkbox',function(evt){var $this=$(this),$table=$this.closest('table'),is_checked=$this.prop('checked'),checkboxes=$table.find('tbody .table-row-multi-select:visible:checkbox');checkboxes.prop('checked',is_checked);});$("div.table_wrapper, #modal_wrapper").on("click",'table tbody .table-row-multi-select:checkbox',function(evt){var $table=$(this).closest('table');var $multi_select_checkbox=$table.find('thead .multi_select_column .table-row-multi-select:checkbox');var any_unchecked=$table.find("tbody .table-row-multi-select:checkbox").not(":checked");$multi_select_checkbox.prop('checked',any_unchecked.length===0);});$("div.table_wrapper, #modal_wrapper").on("click",'.table-row-multi-select:checkbox',function(evt){var $form=$(this).closest("form");var any_checked=$form.find("tbody .table-row-multi-select:checkbox").is(":checked");if(any_checked){$form.find(".table_actions button.btn-danger").removeClass("disabled");}else{$form.find(".table_actions button.btn-danger").addClass("disabled");}});horizon.datatables.add_table_checkboxes($('body'));horizon.datatables.set_table_sorting($('body'));horizon.datatables.set_table_query_filter($('body'));horizon.datatables.set_table_fixed_filter($('body'));horizon.modals.addModalInitFunction(horizon.datatables.add_table_checkboxes);horizon.modals.addModalInitFunction(horizon.datatables.set_table_sorting);horizon.modals.addModalInitFunction(horizon.datatables.set_table_query_filter);horizon.modals.addModalInitFunction(horizon.datatables.set_table_fixed_filter);horizon.tabs.addTabLoadFunction(horizon.datatables.add_table_checkboxes);horizon.tabs.addTabLoadFunction(horizon.datatables.set_table_sorting);horizon.tabs.addTabLoadFunction(horizon.datatables.set_table_query_filter);horizon.tabs.addTabLoadFunction(horizon.datatables.set_table_fixed_filter);horizon.datatables.update();});horizon.inline_edit={get_cell_id:function(td_element){return[td_element.parents("tr").first().data("object-id"),"__",td_element.data("cell-name")].join('');},get_object_container:function(td_element){if(!window.cell_object_container){window.cell_object_container=[];}
return window.cell_object_container;},get_cell_object:function(td_element){var cell_id=horizon.inline_edit.get_cell_id(td_element);var id="cell__"+cell_id;var container=horizon.inline_edit.get_object_container(td_element);var cell_object;if(container&&container[id]){cell_object=container[id];cell_object.reset_with(td_element);return cell_object;}else{cell_object=new horizon.inline_edit.Cell(td_element);container[id]=cell_object;return cell_object;}},Cell:function(td_element){var self=this;self.reset_with=function(td_element){self.td_element=td_element;self.form_element=td_element.find("input, textarea");self.url=td_element.data('update-url');self.inline_edit_mod=false;self.successful_update=false;};self.reset_with(td_element);self.refresh=function(){horizon.ajax.queue({url:self.url,data:{'inline_edit_mod':self.inline_edit_mod},beforeSend:function(){self.start_loading();},complete:function(){$(".tooltip.fade.top.in").remove();self.stop_loading();if(self.successful_update){var success=$('<div class="success"></div>');self.td_element.find('.inline-edit-status').append(success);var background_color=self.td_element.css('background-color');self.td_element.addClass("no-transition");self.td_element.addClass("success");self.td_element.removeClass("no-transition");self.td_element.removeClass("inline_edit_available");success.fadeOut(1300,function(){self.td_element.addClass("inline_edit_available");self.td_element.removeClass("success");});}},error:function(jqXHR,status,errorThrown){if(jqXHR.status===401){var redir_url=jqXHR.getResponseHeader("X-Horizon-Location");if(redir_url){location.href=redir_url;}else{horizon.alert("error",gettext("Not authorized to do this operation."));}}
else{if(!horizon.ajax.get_messages(jqXHR)){horizon.alert("error",gettext("An error occurred. Please try again later."));}}},success:function(data,textStatus,jqXHR){var td_element=$(data);self.form_element=self.get_form_element(td_element);if(self.inline_edit_mod){var table_cell_wrapper=td_element.find(".table_cell_wrapper");width=self.td_element.outerWidth();height=self.td_element.outerHeight();td_element.width(width);td_element.height(height);td_element.css('margin',0).css('padding',0);table_cell_wrapper.css('margin',0).css('padding',0);if(self.form_element.attr('type')==='checkbox'){var inline_edit_form=td_element.find(".inline-edit-form");inline_edit_form.css('padding-top','11px').css('padding-left','4px');inline_edit_form.width(width-40);}else{self.form_element.width(width-40);self.form_element.height(height-2);self.form_element.css('margin',0).css('padding',0);}}
self.cached_presentation_view=self.td_element;self.rewrite_cell(td_element);if(self.inline_edit_mod){self.form_element.focus();}}});};self.update=function(post_data){horizon.ajax.queue({type:'POST',url:self.url,data:post_data,beforeSend:function(){self.start_loading();},complete:function(){if(!self.successful_update){self.stop_loading();}},error:function(jqXHR,status,errorThrown){if(jqXHR.status===400){if(self.td_element.find(".inline-edit-error .error").length<=0){self.form_element.css('padding-left','20px');self.form_element.width(self.form_element.width()-20);}
error_message=$.parseJSON(jqXHR.responseText).message;var error=$('<div title="'+error_message+'" class="error"></div>');self.td_element.find(".inline-edit-error").html(error);error.tooltip({'placement':'top'});}
else if(jqXHR.status===401){var redir_url=jqXHR.getResponseHeader("X-Horizon-Location");if(redir_url){location.href=redir_url;}else{horizon.alert("error",gettext("Not authorized to do this operation."));}}
else{if(!horizon.ajax.get_messages(jqXHR)){horizon.alert("error",gettext("An error occurred. Please try again later."));}}},success:function(data,textStatus,jqXHR){self.successful_update=true;self.refresh();}});};self.cancel=function(){self.rewrite_cell(self.cached_presentation_view);self.stop_loading();};self.get_form_element=function(td_element){return td_element.find("input, textarea");};self.rewrite_cell=function(td_element){self.td_element.replaceWith(td_element);self.td_element=td_element;};self.start_loading=function(){self.td_element.addClass("no-transition");var spinner=$('<div class="loading"></div>');self.td_element.find('.inline-edit-status').append(spinner);self.td_element.addClass("loading");self.td_element.removeClass("inline_edit_available");self.get_form_element(self.td_element).attr("disabled","disabled");};self.stop_loading=function(){self.td_element.find('div.inline-edit-status div.loading').remove();self.td_element.removeClass("loading");self.td_element.addClass("inline_edit_available");self.get_form_element(self.td_element).removeAttr("disabled");};}};horizon.addInitFunction(function(){$('table').on('click','.ajax-inline-edit',function(evt){var $this=$(this);var td_element=$this.parents('td').first();var cell=horizon.inline_edit.get_cell_object(td_element);cell.inline_edit_mod=true;cell.refresh();evt.preventDefault();});var submit_form=function(evt,el){var $submit=$(el);var td_element=$submit.parents('td').first();var post_data=$submit.parents('form').first().serialize();var cell=horizon.inline_edit.get_cell_object(td_element);cell.update(post_data);evt.preventDefault();};$('table').on('click','.inline-edit-submit',function(evt){submit_form(evt,this);});$('table').on('keypress','.inline-edit-form',function(evt){if(evt.which===13&&!evt.shiftKey){submit_form(evt,this);}});$('table').on('click','.inline-edit-cancel',function(evt){var $cancel=$(this);var td_element=$cancel.parents('td').first();var cell=horizon.inline_edit.get_cell_object(td_element);cell.cancel();evt.preventDefault();});$('table').on('mouseenter','.inline_edit_available',function(evt){$(this).find(".table_cell_action").fadeIn(100);});$('table').on('mouseleave','.inline_edit_available',function(evt){$(this).find(".table_cell_action").fadeOut(200);});$('table').on('mouseenter','.table_cell_action',function(evt){$(this).addClass("hovered");});$('table').on('mouseleave','.table_cell_action',function(evt){$(this).removeClass("hovered");});});horizon.tabs={_init_load_functions:[]};horizon.tabs.addTabLoadFunction=function(f){horizon.tabs._init_load_functions.push(f);};horizon.tabs.initTabLoad=function(tab){$(horizon.tabs._init_load_functions).each(function(index,f){f(tab);});};horizon.tabs.load_tab=function(evt){var $this=$(this),tab_id=$this.attr('data-target'),tab_pane=$(tab_id);tab_pane.append("<span style='margin-left: 30px;'>"+gettext("Loading")+"&hellip;</span>");tab_pane.spin(horizon.conf.spinner_options.inline);$(tab_pane.data().spinner.el).css('top','9px');$(tab_pane.data().spinner.el).css('left','15px');if(window.location.search.length>0){tab_pane.load(window.location.search+"&tab="+tab_id.replace('#',''),function(){horizon.tabs.initTabLoad(tab_pane);});}else{tab_pane.load("?tab="+tab_id.replace('#',''),function(){horizon.tabs.initTabLoad(tab_pane);});}
$this.attr("data-loaded","true");evt.preventDefault();};horizon.addInitFunction(function(){var data=horizon.cookies.read('tabs');$(".tab-content").find(".js-tab-pane").addClass("tab-pane");horizon.modals.addModalInitFunction(function(el){$(el).find(".js-tab-pane").addClass("tab-pane");});$(document).on("show",".ajax-tabs a[data-loaded='false']",horizon.tabs.load_tab);$(document).on("shown",".nav-tabs a[data-toggle='tab']",function(evt){var $tab=$(evt.target),$content=$($(evt.target).attr('data-target'));$content.find("table.datatable").each(function(){horizon.datatables.update_footer_count($(this));});horizon.cookies.update("tabs",$tab.closest(".nav-tabs").attr("id"),$tab.attr('data-target'));});$(".nav-tabs[data-sticky-tabs='sticky']").each(function(index,item){var $this=$(this),id=$this.attr("id"),active_tab=data[id];if(active_tab&&window.location.search.indexOf("tab=")<0){$this.find("a[data-target='"+active_tab+"']").tab('show');}});$(document).on("keydown",".tab-pane :input:visible:last",function(evt){var $this=$(this),next_pane=$this.closest(".tab-pane").next(".tab-pane");if(evt.which===9&&!event.shiftKey&&next_pane.length){evt.preventDefault();$(".nav-tabs a[data-target='#"+next_pane.attr("id")+"']").tab('show');}});$(document).on("keydown",".tab-pane :input:visible:first",function(evt){var $this=$(this),prev_pane=$this.closest(".tab-pane").prev(".tab-pane");if(event.shiftKey&&evt.which===9&&prev_pane.length){evt.preventDefault();$(".nav-tabs a[data-target='#"+prev_pane.attr("id")+"']").tab('show');prev_pane.find(":input:last").focus();console.log(prev_pane);}});$(document).on("focus",".tab-content :input",function(){var $this=$(this),tab_pane=$this.closest(".tab-pane"),tab_id=tab_pane.attr('id');if(!tab_pane.hasClass("active")){$(".nav-tabs a[data-target='#"+tab_id+"']").tab('show');}});});horizon.templates={template_ids:["#modal_template","#empty_row_template","#alert_message_template","#spinner-modal","#membership_template"],compiled_templates:{}};horizon.templates.compile_templates=function(){$.each(horizon.templates.template_ids,function(ind,template_id){horizon.templates.compiled_templates[template_id]=Hogan.compile($(template_id).html());});};horizon.addInitFunction(function(){horizon.templates.compile_templates();});horizon.user={init:function(){$("#id_password").change(function(){if($("#id_confirm_password").val()!==""){horizon.user.check_passwords_match();}});$("#id_confirm_password").change(function(){horizon.user.check_passwords_match();});},check_passwords_match:function(){var row=$("label[for='id_confirm_password']");var error_id="id_confirm_password_error";var msg="<span id='"+error_id+"' class='help-inline'>"+gettext("Passwords do not match.")+"</span>";var password=$("#id_password").val();var confirm_password=$("#id_confirm_password").val();if(password!==confirm_password&&$("#"+error_id).length===0){$(row).parent().addClass("error");$(row).after(msg);}else if(password===confirm_password){$(row).parent().removeClass("error");$("#"+error_id).remove();}}};horizon.membership={current_membership:[],data:[],roles:[],has_roles:[],default_role_id:[],get_field_id:function(id_string){return id_string.slice(id_string.lastIndexOf("_")+1);},get_role_element:function(step_slug,role_id){return $('select[id^="id_'+step_slug+'_role_'+role_id+'"]');},get_member_element:function(step_slug,data_id){return $('li[data-'+step_slug+'-id$='+data_id+']').parent();},init_properties:function(step_slug){horizon.membership.has_roles[step_slug]=$("."+step_slug+"_membership").data('show-roles')!=="False";horizon.membership.default_role_id[step_slug]=$('#id_default_'+step_slug+'_role').attr('value');horizon.membership.init_data_list(step_slug);horizon.membership.init_role_list(step_slug);horizon.membership.init_current_membership(step_slug);},init_data_list:function(step_slug){horizon.membership.data[step_slug]=[];angular.forEach($(this.get_role_element(step_slug,"")).find("option"),function(option){horizon.membership.data[step_slug][option.value]=option.text;});},init_role_list:function(step_slug){horizon.membership.roles[step_slug]=[];angular.forEach($('label[for^="id_'+step_slug+'_role_"]'),function(role){var id=horizon.membership.get_field_id($(role).attr('for'));horizon.membership.roles[step_slug][id]=$(role).text();});},init_current_membership:function(step_slug){horizon.membership.current_membership[step_slug]=[];var members_list=[];var role_name,role_id,selected_members;angular.forEach(this.get_role_element(step_slug,''),function(value,key){role_id=horizon.membership.get_field_id($(value).attr('id'));role_name=$('label[for="id_'+step_slug+'_role_'+role_id+'"]').text();selected_members=$(value).find("option:selected");members_list=[];if(selected_members){angular.forEach(selected_members,function(member){members_list.push(member.value);});}
horizon.membership.current_membership[step_slug][role_id]=members_list;});},get_member_roles:function(step_slug,data_id){var roles=[];for(var role in horizon.membership.current_membership[step_slug]){if($.inArray(data_id,horizon.membership.current_membership[step_slug][role])!==-1){roles.push(role);}}
return roles;},update_role_lists:function(step_slug,role_id,new_list){this.get_role_element(step_slug,role_id).val(new_list);horizon.membership.current_membership[step_slug][role_id]=new_list;},remove_member:function(step_slug,data_id,role_id,role_list){var index=role_list.indexOf(data_id);if(index>=0){role_list.splice(index,1);horizon.membership.update_role_lists(step_slug,role_id,role_list);}},remove_member_from_role:function(step_slug,data_id,role_id){var role,membership=horizon.membership.current_membership[step_slug];if(role_id){horizon.membership.remove_member(step_slug,data_id,role_id,membership[role_id]);}
else{for(role in membership){if(membership.hasOwnProperty(role)){horizon.membership.remove_member(step_slug,data_id,role,membership[role]);}}}},add_member_to_role:function(step_slug,data_id,role_id){var role_list=horizon.membership.current_membership[step_slug][role_id];role_list.push(data_id);horizon.membership.update_role_lists(step_slug,role_id,role_list);},update_member_role_dropdown:function(step_slug,data_id,role_ids,member_el){if(typeof(role_ids)==='undefined'){role_ids=horizon.membership.get_member_roles(step_slug,data_id);}
if(typeof(member_el)==='undefined'){member_el=horizon.membership.get_member_element(step_slug,data_id);}
var $dropdown=member_el.find("li.member").siblings('.dropdown');var $role_items=$dropdown.children('.role_dropdown').children('li');$role_items.each(function(idx,el){if($.inArray(($(el).data('role-id')),role_ids)!==-1){$(el).addClass('selected');}else{$(el).removeClass('selected');}});var $roles_display=$dropdown.children('.dropdown-toggle').children('.roles_display');var roles_to_display=[];for(var i=0;i<role_ids.length;i++){if(i===2){roles_to_display.push('...');break;}
roles_to_display.push(horizon.membership.roles[step_slug][role_ids[i]]);}
text=roles_to_display.join(', ');if(text.length===0){text=gettext('No roles');}
$roles_display.text(text);},generate_member_element:function(step_slug,display_name,data_id,role_ids,text){var roles=[],that=this,membership_roles=that.roles[step_slug],r;for(r in membership_roles){if(membership_roles.hasOwnProperty(r)){roles.push({role_id:r,role_name:membership_roles[r]});}}
var template=horizon.templates.compiled_templates["#membership_template"],params={data_id:"id_"+step_slug+"_"+data_id,step_slug:step_slug,default_role:that.roles[that.default_role_id[step_slug]],display_name:display_name,text:text,roles:roles,roles_label:gettext("Roles")},member_el=$(template.render(params));this.update_member_role_dropdown(step_slug,params.data_id,role_ids,member_el);return $(member_el);},generate_html:function(step_slug){var data_id,data=horizon.membership.data[step_slug];for(data_id in data){if(data.hasOwnProperty(data_id)){var display_name=data[data_id];var role_ids=this.get_member_roles(step_slug,data_id);if(role_ids.length>0){$("."+step_slug+"_members").append(this.generate_member_element(step_slug,display_name,data_id,role_ids,"-"));}
else{$(".available_"+step_slug).append(this.generate_member_element(step_slug,display_name,data_id,role_ids,"+"));}}}
horizon.membership.detect_no_results(step_slug);},update_membership:function(step_slug){$(".available_"+step_slug+", ."+step_slug+"_members").on('click',".btn-group a[href='#add_remove']",function(evt){evt.preventDefault();var available=$(".available_"+step_slug).has($(this)).length;var data_id=horizon.membership.get_field_id($(this).parent().siblings().attr('data-'+step_slug+'-id'));var member_el=$(this).parent().parent();if(available){var default_role=horizon.membership.default_role_id[step_slug];$(this).text("-");$("."+step_slug+"_members").append(member_el);horizon.membership.add_member_to_role(step_slug,data_id,default_role);if(horizon.membership.has_roles[step_slug]){$(this).parent().siblings(".role_options").show();horizon.membership.update_member_role_dropdown(step_slug,data_id,[default_role],member_el);}}
else{$(this).text("+");$(this).parent().siblings(".role_options").hide();$(".available_"+step_slug).append(member_el);horizon.membership.remove_member_from_role(step_slug,data_id);}
horizon.membership.list_filtering(step_slug);horizon.membership.detect_no_results(step_slug);$("input."+step_slug+"_filter").val("");});},detect_no_results:function(step_slug){$('.'+step_slug+'_filterable').each(function(){var css_class=$(this).find('ul').attr('class');var filter=$.grep(css_class.split(' '),function(val){return val.indexOf(step_slug)!==-1;})[0];if(!$('.'+filter).children('ul').length){$('#no_'+filter).show();$("input[id='"+filter+"']").attr('disabled','disabled');}
else{$('#no_'+filter).hide();$("input[id='"+filter+"']").removeAttr('disabled');}});},select_member_role:function(step_slug){$(".available_"+step_slug+", ."+step_slug+"_members").on('click','.role_dropdown li',function(evt){evt.preventDefault();evt.stopPropagation();var new_role_id=$(this).attr("data-role-id");var id_str=$(this).parent().parent().siblings(".member").attr("data-"+step_slug+"-id");var data_id=horizon.membership.get_field_id(id_str);if($(this).hasClass('selected')){$(this).removeClass('selected');horizon.membership.remove_member_from_role(step_slug,data_id,new_role_id);}else{$(this).addClass('selected');horizon.membership.add_member_to_role(step_slug,data_id,new_role_id);}
horizon.membership.update_member_role_dropdown(step_slug,data_id);});},add_new_member:function(step_slug){$("select[id='id_new_"+step_slug+"']").on('change',function(evt){var display_name=$(this).find("option").text();var data_id=$(this).find("option").attr("value");var default_role_id=horizon.membership.default_role_id[step_slug];$("."+step_slug+"_members").append(horizon.membership.generate_member_element(step_slug,display_name,data_id,[default_role_id],"-"));horizon.membership.data[step_slug][data_id]=display_name;$("select[multiple='multiple']").append("<option value='"+data_id+"'>"+horizon.membership.data[step_slug][data_id]+"</option>");horizon.membership.add_member_to_role(step_slug,data_id,default_role_id);$(this).text("");horizon.membership.list_filtering(step_slug);horizon.membership.detect_no_results(step_slug);$("input.filter").val("");$("."+step_slug+"_members .btn-group").removeClass('last_stripe');$("."+step_slug+"_members .btn-group:last").addClass('last_stripe');});},add_new_member_styling:function(step_slug){var add_member_el=$("label[for='id_new_"+step_slug+"']").parent();$(add_member_el).find("select").hide();$("#add_"+step_slug).append($(add_member_el));$(add_member_el).addClass("add_"+step_slug);$(add_member_el).find("label, .input").addClass("add_"+step_slug+"_btn");},fix_stripes:function(step_slug){$('.fake_'+step_slug+'_table').each(function(){var filter="."+$(this).attr('id');var visible=" .btn-group:visible";var even=" .btn-group:visible:even";var last=" .btn-group:visible:last";$(filter+visible).removeClass('dark_stripe');$(filter+visible).addClass('light_stripe');$(filter+even).removeClass('light_stripe');$(filter+even).addClass('dark_stripe');$(filter+visible).removeClass('last_stripe');$(filter+last).addClass('last_stripe');});},list_filtering:function(step_slug){$('input.'+step_slug+'_filter').unbind();$('.'+step_slug+'_filterable').each(function(){var css_class=$(this).children().children('ul').attr('class');var filter=$.grep(css_class.split(' '),function(val){return val.indexOf(step_slug)!==-1;})[0];var input=$("input[id='"+filter+"']");input.quicksearch('ul.'+filter+' ul li span.display_name',{'delay':200,'loader':'span.loading','show':function(){$(this).parent().parent().show();if(filter==="available_"+step_slug){$(this).parent('.dropdown-toggle').hide();}},'hide':function(){$(this).parent().parent().hide();},'noResults':'ul#no_'+filter,'onAfter':function(){horizon.membership.fix_stripes(step_slug);},'prepareQuery':function(val){return new RegExp(val,"i");},'testQuery':function(query,txt,span){if($(input).attr('id')===filter){$(input).prev().removeAttr('disabled');return query.test($(span).text());}else{return true;}}});});},workflow_init:function(modal,step_slug,step_id){$(".tab-content, .workflow").addClass("dropdown_fix");$(modal).find('form').each(function(){var $form=$(this);if($form.find('div.'+step_slug+'_membership').length===0){return;}
horizon.membership.init_properties(step_slug);horizon.membership.generate_html(step_slug);horizon.membership.update_membership(step_slug);horizon.membership.select_member_role(step_slug);horizon.membership.add_new_member(step_slug);$form.find(".available_"+step_slug+" .role_options").hide();if(!horizon.membership.has_roles[step_slug]){$form.find("."+step_slug+"_members .role_options").hide();}
if(step_id.indexOf('update')===0){$form.find("#"+step_id+" input").blur();}
$form.find('.'+step_slug+'_membership').keydown(function(event){if(event.keyCode===13){event.preventDefault();return false;}});horizon.membership.add_new_member_styling(step_slug);horizon.membership.list_filtering(step_slug);horizon.membership.detect_no_results(step_slug);$form.find('.fake_'+step_slug+'_table').each(function(){var filter="."+$(this).attr('id');$(filter+' .btn-group:even').addClass('dark_stripe');$(filter+' .btn-group:last').addClass('last_stripe');});});}};horizon.network_topology={model:null,svg:'#topology_canvas',svg_container:'#topologyCanvasContainer',post_messages:'#topologyMessages',network_tmpl:{small:'#topology_template > .network_container_small',normal:'#topology_template > .network_container_normal'},router_tmpl:{small:'#topology_template > .router_small',normal:'#topology_template > .router_normal'},instance_tmpl:{small:'#topology_template > .instance_small',normal:'#topology_template > .instance_normal'},balloon_tmpl:null,balloon_device_tmpl:null,balloon_port_tmpl:null,network_index:{},balloon_id:null,reload_duration:10000,draw_mode:'normal',network_height:0,previous_message:null,element_properties:{normal:{network_width:270,network_min_height:500,top_margin:80,default_height:50,margin:20,device_x:98.5,device_width:90,port_margin:16,port_height:6,port_width:82,port_text_margin:{x:6,y:-4},texts_bg_y:32,type_y:46,balloon_margin:{x:12,y:-12}},small:{network_width:100,network_min_height:400,top_margin:50,default_height:20,margin:30,device_x:47.5,device_width:20,port_margin:5,port_height:3,port_width:32.5,port_text_margin:{x:0,y:0},texts_bg_y:0,type_y:0,balloon_margin:{x:12,y:-30}},cidr_margin:5,device_name_max_size:9,device_name_suffix:'..'},init:function(){var self=this;$(self.svg_container).spin(horizon.conf.spinner_options.modal);if($('#networktopology').length===0){return;}
self.color=d3.scale.category10();self.balloon_tmpl=Hogan.compile($('#balloon_container').html());self.balloon_device_tmpl=Hogan.compile($('#balloon_device').html());self.balloon_port_tmpl=Hogan.compile($('#balloon_port').html());$(document).on('click','a.closeTopologyBalloon',function(e){e.preventDefault();self.delete_balloon();}).on('click','.topologyBalloon',function(e){e.stopPropagation();}).on('click','a.vnc_window',function(e){e.preventDefault();var vnc_window=window.open($(this).attr('href'),vnc_window,'width=760,height=560');self.delete_balloon();}).click(function(){self.delete_balloon();});$('.toggleView > .btn').click(function(){self.draw_mode=$(this).data('value');$('g.network').remove();$.cookie('ntp_draw_mode',self.draw_mode);self.data_convert();});$(window).on('message',function(e){var message=$.parseJSON(e.originalEvent.data);if(self.previous_message!==message.message){horizon.alert(message.type,message.message);horizon.autoDismissAlerts();self.previous_message=message.message;self.delete_post_message(message.iframe_id);self.load_network_info();setTimeout(function(){self.previous_message=null;},10000);}});self.load_network_info();},load_network_info:function(){var self=this;if($('#networktopology').length===0){return;}
$.getJSON($('#networktopology').data('networktopology')+'?'+$.now(),function(data){self.model=data;self.data_convert();setTimeout(function(){self.load_network_info();},self.reload_duration);});},select_draw_mode:function(){var self=this;var draw_mode=$.cookie('ntp_draw_mode');if(draw_mode&&(draw_mode==='normal'||draw_mode==='small')){self.draw_mode=draw_mode;}else{if(self.model.networks.length*self.element_properties.normal.network_width>$('#topologyCanvas').width()){self.draw_mode='small';}else{self.draw_mode='normal';}
$.cookie('ntp_draw_mode',self.draw_mode);}
$('.toggleView > .btn').each(function(){var $this=$(this);if($this.hasClass(self.draw_mode)){$this.addClass('active');}});},data_convert:function(){var self=this;var model=self.model;$.each(model.networks,function(index,network){self.network_index[network.id]=index;});self.select_draw_mode();var element_properties=self.element_properties[self.draw_mode];self.network_height=element_properties.top_margin;$.each([{model:model.routers,type:'router'},{model:model.servers,type:'instance'}],function(index,devices){var type=devices.type;var model=devices.model;$.each(model,function(index,device){device.type=type;device.ports=self.select_port(device.id);var hasports=(device.ports.length<=0)?false:true;device.parent_network=(hasports)?self.select_main_port(device.ports).network_id:self.model.networks[0].id;var height=element_properties.port_margin*(device.ports.length-1);device.height=(self.draw_mode==='normal'&&height>element_properties.default_height)?height:element_properties.default_height;device.pos_y=self.network_height;device.port_height=(self.draw_mode==='small'&&height>device.height)?1:element_properties.port_height;device.port_margin=(self.draw_mode==='small'&&height>device.height)?device.height/device.ports.length:element_properties.port_margin;self.network_height+=device.height+element_properties.margin;});});$.each(model.networks,function(index,network){network.devices=[];$.each([model.routers,model.servers],function(index,devices){$.each(devices,function(index,device){if(network.id===device.parent_network){network.devices.push(device);}});});});self.network_height+=element_properties.top_margin;self.network_height=(self.network_height>element_properties.network_min_height)?self.network_height:element_properties.network_min_height;self.draw_topology();},draw_topology:function(){var self=this;$(self.svg_container).spin(false);$(self.svg_container).removeClass('noinfo');if(self.model.networks.length<=0){$('g.network').remove();$(self.svg_container).addClass('noinfo');return;}
var svg=d3.select(self.svg);var element_properties=self.element_properties[self.draw_mode];svg.attr('width',self.model.networks.length*element_properties.network_width).attr('height',self.network_height);var network=svg.selectAll('g.network').data(self.model.networks);var network_enter=network.enter().append('g').attr('class','network').each(function(d,i){this.appendChild(d3.select(self.network_tmpl[self.draw_mode]).node().cloneNode(true));var $this=d3.select(this).select('.network-rect');if(d.url){$this.on('mouseover',function(){$this.transition().style('fill',function(){return d3.rgb(self.get_network_color(d.id)).brighter(0.5);});}).on('mouseout',function(){$this.transition().style('fill',function(){return self.get_network_color(d.id);});}).on('click',function(){window.location.href=d.url;});}else{$this.classed('nourl',true);}});network.attr('id',function(d){return'id_'+d.id;}).attr('transform',function(d,i){return'translate('+element_properties.network_width*i+','+0+')';}).select('.network-rect').attr('height',function(d){return self.network_height;}).style('fill',function(d){return self.get_network_color(d.id);});network.select('.network-name').attr('x',function(d){return self.network_height/2;}).text(function(d){return d.name;});network.select('.network-cidr').attr('x',function(d){return self.network_height-self.element_properties.cidr_margin;}).text(function(d){var cidr=$.map(d.subnets,function(n,i){return n.cidr;});return cidr.join(', ');});network.exit().remove();var device=network.selectAll('g.device').data(function(d){return d.devices;});var device_enter=device.enter().append("g").attr('class','device').each(function(d,i){var device_template=self[d.type+'_tmpl'][self.draw_mode];this.appendChild(d3.select(device_template).node().cloneNode(true));});device_enter.on('mouseenter',function(d){var $this=$(this);self.show_balloon(d,$this);}).on('click',function(){d3.event.stopPropagation();});device.attr('id',function(d){return'id_'+d.id;}).attr('transform',function(d,i){return'translate('+element_properties.device_x+','+d.pos_y+')';}).select('.frame').attr('height',function(d){return d.height;});device.select('.texts_bg').attr('y',function(d){return element_properties.texts_bg_y+d.height-element_properties.default_height;});device.select('.type').attr('y',function(d){return element_properties.type_y+d.height-element_properties.default_height;});device.select('.name').text(function(d){return self.string_truncate(d.name);});device.each(function(d){if(d.status==='BUILD'){d3.select(this).classed('loading',true);}else if(d.task==='deleting'){d3.select(this).classed('loading',true);if('bl_'+d.id===self.balloon_id){self.delete_balloon();}}else{d3.select(this).classed('loading',false);if('bl_'+d.id===self.balloon_id){var $this=$(this);self.show_balloon(d,$this);}}});device.exit().each(function(d){if('bl_'+d.id===self.balloon_id){self.delete_balloon();}}).remove();var port=device.select('g.ports').selectAll('g.port').data(function(d){return d.ports;});var port_enter=port.enter().append('g').attr('class','port').attr('id',function(d){return'id_'+d.id;});port_enter.append('line').attr('class','port_line');port_enter.append('text').attr('class','port_text');device.select('g.ports').each(function(d,i){this._portdata={};this._portdata.ports_length=d.ports.length;this._portdata.parent_network=d.parent_network;this._portdata.device_height=d.height;this._portdata.port_height=d.port_height;this._portdata.port_margin=d.port_margin;this._portdata.left=0;this._portdata.right=0;$(this).mouseenter(function(e){e.stopPropagation();});});port.each(function(d,i){var index_diff=self.get_network_index(this.parentNode._portdata.parent_network)-
self.get_network_index(d.network_id);this._index_diff=index_diff=(index_diff>=0)?++index_diff:index_diff;this._direction=(this._index_diff<0)?'right':'left';this._index=this.parentNode._portdata[this._direction]++;});port.attr('transform',function(d,i){var x=(this._direction==='left')?0:element_properties.device_width;var ports_length=this.parentNode._portdata[this._direction];var distance=this.parentNode._portdata.port_margin;var y=(this.parentNode._portdata.device_height-
(ports_length-1)*distance)/2+this._index*distance;return'translate('+x+','+y+')';});port.select('.port_line').attr('stroke-width',function(d,i){return this.parentNode.parentNode._portdata.port_height;}).attr('stroke',function(d,i){return self.get_network_color(d.network_id);}).attr('x1',0).attr('y1',0).attr('y2',0).attr('x2',function(d,i){var parent=this.parentNode;var width=(Math.abs(parent._index_diff)-1)*element_properties.network_width+
element_properties.port_width;return(parent._direction==='left')?-1*width:width;});port.select('.port_text').attr('x',function(d){var parent=this.parentNode;if(parent._direction==='left'){d3.select(this).classed('left',true);return element_properties.port_text_margin.x*-1;}else{d3.select(this).classed('left',false);return element_properties.port_text_margin.x;}}).attr('y',function(d){return element_properties.port_text_margin.y;}).text(function(d){var ip_label=[];$.each(d.fixed_ips,function(){ip_label.push(this.ip_address);});return ip_label.join(',');});port.exit().remove();},get_network_color:function(network_id){return this.color(this.get_network_index(network_id));},get_network_index:function(network_id){return this.network_index[network_id];},select_port:function(device_id){return $.map(this.model.ports,function(port,index){if(port.device_id===device_id){return port;}});},select_main_port:function(ports){var _self=this;var main_port_index=0;var MAX_INT=4294967295;var min_port_length=MAX_INT;$.each(ports,function(index,port){var port_length=_self.sum_port_length(port.network_id,ports);if(port_length<min_port_length){min_port_length=port_length;main_port_index=index;}});return ports[main_port_index];},sum_port_length:function(network_id,ports){var self=this;var sum_port_length=0;var base_index=self.get_network_index(network_id);$.each(ports,function(index,port){sum_port_length+=base_index-self.get_network_index(port.network_id);});return sum_port_length;},string_truncate:function(string){var self=this;var str=string;var max_size=self.element_properties.device_name_max_size;var suffix=self.element_properties.device_name_suffix;var bytes=0;for(var i=0;i<str.length;i++){bytes+=str.charCodeAt(i)<=255?1:2;if(bytes>max_size){str=str.substr(0,i)+suffix;break;}}
return str;},delete_device:function(type,device_id){var self=this;var message={id:device_id};self.post_message(device_id,type,message);},delete_port:function(router_id,port_id){var self=this;var message={id:port_id};self.post_message(port_id,'router/'+router_id+'/',message);},show_balloon:function(d,element){var self=this;var element_properties=self.element_properties[self.draw_mode];if(self.balloon_id){self.delete_balloon();}
var balloon_tmpl=self.balloon_tmpl;var device_tmpl=self.balloon_device_tmpl;var port_tmpl=self.balloon_port_tmpl;var balloon_id='bl_'+d.id;var ports=[];$.each(d.ports,function(i,port){var object={};object.id=port.id;object.router_id=port.device_id;object.url=port.url;object.port_status=port.status;object.port_status_css=(port.status==="ACTIVE")?'active':'down';var ip_address='';try{ip_address=port.fixed_ips[0].ip_address;}catch(e){ip_address='no info';}
var device_owner='';try{device_owner=port.device_owner.replace('network:','');}catch(e){device_owner='no info';}
object.ip_address=ip_address;object.device_owner=device_owner;object.is_interface=(device_owner==='router_interface')?true:false;ports.push(object);});var html_data={balloon_id:balloon_id,id:d.id,url:d.url,name:d.name,type:d.type,type_capital:d.type.replace(/^\w/,function($0){return $0.toUpperCase();}),status:d.status,status_class:(d.status==="ACTIVE")?'active':'down',status_label:gettext("STATUS"),id_label:gettext("ID"),interfaces_label:gettext("Interfaces"),interface_label:gettext("Interface"),open_console_label:gettext("open console"),view_details_label:interpolate(gettext("view %s details"),[d.type])};if(d.type==='router'){html_data.port=ports;html=balloon_tmpl.render(html_data,{table1:device_tmpl,table2:port_tmpl});}else if(d.type==='instance'){html_data.console_id=d.id;html_data.console=d.console;html=balloon_tmpl.render(html_data,{table1:device_tmpl});}else{return;}
$(self.svg_container).append(html);var device_position=element.find('.frame');var x=device_position.position().left+
element_properties.device_width+
element_properties.balloon_margin.x;var y=device_position.position().top+
element_properties.balloon_margin.y;$('#'+balloon_id).css({'left':x+'px','top':y+'px'}).show();var $balloon=$('#'+balloon_id);if($balloon.offset().left+$balloon.outerWidth()>$(window).outerWidth()){$balloon.css({'left':0+'px'}).css({'left':(device_position.position().left-$balloon.outerWidth()-
element_properties.balloon_margin.x+'px')}).addClass('leftPosition');}
$balloon.find('.delete-device').click(function(e){var $this=$(this);$this.addClass('deleting');d3.select('#id_'+$this.data('device-id')).classed('loading',true);self.delete_device($this.data('type'),$this.data('device-id'));});$balloon.find('.delete-port').click(function(e){var $this=$(this);self.delete_port($this.data('router-id'),$this.data('port-id'));});self.balloon_id=balloon_id;},delete_balloon:function(){var self=this;if(self.balloon_id){$('#'+self.balloon_id).remove();self.balloon_id=null;}},post_message:function(id,url,message){var self=this;var iframe_id='ifr_'+id;var iframe=$('<iframe width="500" height="300" />').attr('id',iframe_id).attr('src',url).appendTo(self.post_messages);iframe.on('load',function(){$(this).get(0).contentWindow.postMessage(JSON.stringify(message,null,2),'*');});},delete_post_message:function(id){$('#'+id).remove();}};var WIDTH=100;var HEIGHT=100;var RADIUS=45;var BKGRND="#F2F2F2";var FRGRND="#006CCF";var FULL="#D0342B";var NEARLY_FULL="#FFA500";var STROKE="#CCCCCC";function create_vis(chart){return d3.select(chart).append("svg:svg").attr("class","chart").attr("width",WIDTH).attr("height",HEIGHT).append("g").attr("transform","translate("+(RADIUS+2)+","+(RADIUS+2)+")");}
function create_arc(){return d3.svg.arc().outerRadius(RADIUS).innerRadius(0);}
function create_pie(param){return d3.layout.pie().sort(null).value(function(d){return d[param];});}
horizon.d3_pie_chart_usage={init:function(){var self=this;var pie_chart_data=$(".d3_pie_chart_usage");self.chart=d3.selectAll(".d3_pie_chart_usage");for(var i=0;i<pie_chart_data.length;i++){var used=Math.min(parseInt($(pie_chart_data[i]).data("used")),100);self.data=[{"percentage":used},{"percentage":100-used}];self.pieChart(i);}},pieChart:function(i){var self=this;var vis=create_vis(self.chart[0][i]);var arc=create_arc();var pie=create_pie("percentage");vis.selectAll(".arc").data(pie([{"percentage":10}])).enter().append("path").attr("class","arc").attr("d",arc).style("fill",BKGRND).style("stroke",STROKE).style("stroke-width",1);var animate=function(data){vis.selectAll(".arc").data(pie(data)).enter().append("path").attr("class","arc").attr("d",arc).style("fill",function(){if(self.data[0].percentage>=100){return FULL;}else if(self.data[0].percentage>=80){return NEARLY_FULL;}else{return FRGRND;}}).style("stroke",STROKE).style("stroke-width",function(){if(self.data[0].percentage<=0||self.data[0].percentage>=100){return 0;}else{return 1;}}).transition().duration(500).attrTween("d",function(start){start.endAngle=start.startAngle=0;var end={startAngle:0,endAngle:2*Math.PI*(100-start.value)/100};var tween=d3.interpolate(start,end);return function(t){return arc(tween(t));};});};animate(self.data);}};horizon.d3_pie_chart_distribution={colors:d3.scale.category20(),init:function(){var self=this;var pie_chart_data=$(".d3_pie_chart_distribution");self.chart=d3.selectAll(".d3_pie_chart_distribution");for(var i=0;i<pie_chart_data.length;i++){var parts=$(pie_chart_data[i]).data("used").split("|");self.data=[];self.keys=[];for(var j=0;j<parts.length;j++){var key_value=parts[j].split("=");var d={};d["key"]=key_value[0];d["value"]=key_value[1];self.data.push(d);self.keys.push(key_value[0]);}
self.pieChart(i);}},pieChart:function(i){var self=this;var vis=create_vis(self.chart[0][i]);var arc=create_arc();var pie=create_pie("value");var total=0;for(var j=0;j<self.data.length;j++){total=total+parseInt(self.data[j]["value"]);}
var initial_data=[];if(total===0){initial_data=[{"value":1}];}
vis.selectAll(".arc").data(pie(initial_data)).enter().append("path").attr("class","arc").attr("d",arc).style("fill",BKGRND).style("stroke",STROKE).style("stroke-width",1);var animate=function(data){vis.selectAll(".arc").data(pie(data)).enter().append("path").attr("class","arc").attr("d",arc).style("fill",function(d){return self.colors(d.data.key);}).style("stroke",STROKE).style("stroke-width",1).transition().duration(500).attrTween("d",function(start){start.endAngle=start.startAngle;var end=jQuery.extend({},start);end.endAngle=end.startAngle+2*Math.PI/total*end.value;var tween=d3.interpolate(start,end);return function(t){return arc(tween(t));};});};if(total!==0){animate(self.data);}
var legend=d3.select(self.chart[0][i]).append("svg").attr("class","legend").attr("width",WIDTH*2).attr("height",self.data.length*18+20).selectAll("g").data(self.keys).enter().append("g").attr("transform",function(d,i){return"translate(0,"+i*20+")";});legend.append("rect").attr("width",18).attr("height",18).style("fill",self.colors);legend.append("text").attr("x",24).attr("y",9).attr("dy",".35em").text(function(d){if(total===0){return d+" 0%";}
var value=0;for(var j=0;j<self.data.length;j++){if(self.data[j]["key"]==d){value=self.data[j]["value"];break;}}
return d+" "+Math.round(value/total*100)+"%";});}};horizon.addInitFunction(function(){horizon.d3_pie_chart_usage.init();});horizon.addInitFunction(function(){horizon.d3_pie_chart_distribution.init();});var container="#heat_resource_topology";function update(){node=node.data(nodes,function(d){return d.name;});link=link.data(links);var nodeEnter=node.enter().append("g").attr("class","node").attr("node_name",function(d){return d.name;}).attr("node_id",function(d){return d.instance;}).call(force.drag);nodeEnter.append("image").attr("xlink:href",function(d){return d.image;}).attr("id",function(d){return"image_"+d.name;}).attr("x",function(d){return d.image_x;}).attr("y",function(d){return d.image_y;}).attr("width",function(d){return d.image_size;}).attr("height",function(d){return d.image_size;});node.exit().remove();link.enter().insert("svg:line","g.node").attr("class","link").style("stroke-width",function(d){return Math.sqrt(d.value);});link.exit().remove();node.on("mouseover",function(d){$("#info_box").html(d.info_box);current_info=d.name;});node.on("mouseout",function(d){$("#info_box").html('');});force.start();}
function tick(){link.attr("x1",function(d){return d.source.x;}).attr("y1",function(d){return d.source.y;}).attr("x2",function(d){return d.target.x;}).attr("y2",function(d){return d.target.y;});node.attr("transform",function(d){return"translate("+d.x+","+d.y+")";});}
function set_in_progress(stack,nodes){if(stack.in_progress===true){in_progress=true;}
for(var i=0;i<nodes.length;i++){var d=nodes[i];if(d.in_progress===true){in_progress=true;return false;}}}
function findNode(name){for(var i=0;i<nodes.length;i++){if(nodes[i].name===name){return nodes[i];}}}
function findNodeIndex(name){for(var i=0;i<nodes.length;i++){if(nodes[i].name===name){return i;}}}
function addNode(node){nodes.push(node);needs_update=true;}
function removeNode(name){var i=0;var n=findNode(name);while(i<links.length){if(links[i].source===n||links[i].target===n){links.splice(i,1);}else{i++;}}
nodes.splice(findNodeIndex(name),1);needs_update=true;}
function remove_nodes(old_nodes,new_nodes){for(var i=0;i<old_nodes.length;i++){var remove_node=true;for(var j=0;j<new_nodes.length;j++){if(old_nodes[i].name===new_nodes[j].name){remove_node=false;break;}}
if(remove_node===true){removeNode(old_nodes[i].name);}}}
function build_links(){for(var i=0;i<nodes.length;i++){build_node_links(nodes[i]);build_reverse_links(nodes[i]);}}
function build_node_links(node){for(var j=0;j<node.required_by.length;j++){var push_link=true;var target_idx='';var source_idx=findNodeIndex(node.name);try{target_idx=findNodeIndex(node.required_by[j]);}catch(err){console.log(err);push_link=false;}
for(var lidx=0;lidx<links.length;lidx++){if(links[lidx].source===source_idx&&links[lidx].target===target_idx){push_link=false;break;}}
if(push_link===true&&(source_idx&&target_idx)){links.push({'source':source_idx,'target':target_idx,'value':1});}}}
function build_reverse_links(node){for(var i=0;i<nodes.length;i++){if(nodes[i].required_by){for(var j=0;j<nodes[i].required_by.length;j++){var dependency=nodes[i].required_by[j];if(node.name===dependency){links.push({'source':findNodeIndex(nodes[i].name),'target':findNodeIndex(node.name),'value':1});}}}}}
function ajax_poll(poll_time){setTimeout(function(){$.getJSON(ajax_url,function(json){$("#d3_data").attr("data-d3_data",JSON.stringify(json));$("#stack_box").html(json.stack.info_box);set_in_progress(json.stack,json.nodes);needs_update=false;remove_nodes(nodes,json.nodes);json.nodes.forEach(function(d){current_node=findNode(d.name);if(current_node){current_node.status=d.status;if(current_node.image!==d.image){current_node.image=d.image;var this_image=d3.select("#image_"+current_node.name);this_image.transition().attr("x",function(d){return d.image_x+5;}).duration(100).transition().attr("x",function(d){return d.image_x-5;}).duration(100).transition().attr("x",function(d){return d.image_x+5;}).duration(100).transition().attr("x",function(d){return d.image_x-5;}).duration(100).transition().attr("xlink:href",d.image).transition().attr("x",function(d){return d.image_x;}).duration(100).ease("bounce");}
current_node.info_box=d.info_box;}else{addNode(d);build_links();}});if(needs_update===true){update();}});if(in_progress===false){poll_time=30000;}
else{poll_time=3000;}
ajax_poll(poll_time);},poll_time);}
if($(container).length){var width=$(container).width(),height=500,stack_id=$("#stack_id").data("stack_id"),ajax_url='/project/stacks/get_d3_data/'+stack_id+'/',graph=$("#d3_data").data("d3_data"),force=d3.layout.force().nodes(graph.nodes).links([]).gravity(0.1).charge(-2000).linkDistance(100).size([width,height]).on("tick",tick),svg=d3.select(container).append("svg").attr("width",width).attr("height",height),node=svg.selectAll(".node"),link=svg.selectAll(".link"),needs_update=false,nodes=force.nodes(),links=force.links();build_links();update();$("#stack_box").html(graph.stack.info_box);var in_progress=false;set_in_progress(graph.stack,node);var poll_time=0;if(in_progress===true){poll_time=3000;}
else{poll_time=30000;}
ajax_poll(poll_time);}
var Rickshaw={namespace:function(namespace,obj){var parts=namespace.split('.');var parent=Rickshaw;for(var i=1,length=parts.length;i<length;i++){var currentPart=parts[i];parent[currentPart]=parent[currentPart]||{};parent=parent[currentPart];}
return parent;},keys:function(obj){var keys=[];for(var key in obj)keys.push(key);return keys;},extend:function(destination,source){for(var property in source){destination[property]=source[property];}
return destination;},clone:function(obj){return JSON.parse(JSON.stringify(obj));}};if(typeof module!=='undefined'&&module.exports){var d3=require('d3');module.exports=Rickshaw;}
(function(globalContext){var _toString=Object.prototype.toString,NULL_TYPE='Null',UNDEFINED_TYPE='Undefined',BOOLEAN_TYPE='Boolean',NUMBER_TYPE='Number',STRING_TYPE='String',OBJECT_TYPE='Object',FUNCTION_CLASS='[object Function]';function isFunction(object){return _toString.call(object)===FUNCTION_CLASS;}
function extend(destination,source){for(var property in source)if(source.hasOwnProperty(property))
destination[property]=source[property];return destination;}
function keys(object){if(Type(object)!==OBJECT_TYPE){throw new TypeError();}
var results=[];for(var property in object){if(object.hasOwnProperty(property)){results.push(property);}}
return results;}
function Type(o){switch(o){case null:return NULL_TYPE;case(void 0):return UNDEFINED_TYPE;}
var type=typeof o;switch(type){case'boolean':return BOOLEAN_TYPE;case'number':return NUMBER_TYPE;case'string':return STRING_TYPE;}
return OBJECT_TYPE;}
function isUndefined(object){return typeof object==="undefined";}
var slice=Array.prototype.slice;function argumentNames(fn){var names=fn.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1].replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g,'').replace(/\s+/g,'').split(',');return names.length==1&&!names[0]?[]:names;}
function wrap(fn,wrapper){var __method=fn;return function(){var a=update([bind(__method,this)],arguments);return wrapper.apply(this,a);}}
function update(array,args){var arrayLength=array.length,length=args.length;while(length--)array[arrayLength+length]=args[length];return array;}
function merge(array,args){array=slice.call(array,0);return update(array,args);}
function bind(fn,context){if(arguments.length<2&&isUndefined(arguments[0]))return this;var __method=fn,args=slice.call(arguments,2);return function(){var a=merge(args,arguments);return __method.apply(context,a);}}
var emptyFunction=function(){};var Class=(function(){var IS_DONTENUM_BUGGY=(function(){for(var p in{toString:1}){if(p==='toString')return false;}
return true;})();function subclass(){};function create(){var parent=null,properties=[].slice.apply(arguments);if(isFunction(properties[0]))
parent=properties.shift();function klass(){this.initialize.apply(this,arguments);}
extend(klass,Class.Methods);klass.superclass=parent;klass.subclasses=[];if(parent){subclass.prototype=parent.prototype;klass.prototype=new subclass;try{parent.subclasses.push(klass)}catch(e){}}
for(var i=0,length=properties.length;i<length;i++)
klass.addMethods(properties[i]);if(!klass.prototype.initialize)
klass.prototype.initialize=emptyFunction;klass.prototype.constructor=klass;return klass;}
function addMethods(source){var ancestor=this.superclass&&this.superclass.prototype,properties=keys(source);if(IS_DONTENUM_BUGGY){if(source.toString!=Object.prototype.toString)
properties.push("toString");if(source.valueOf!=Object.prototype.valueOf)
properties.push("valueOf");}
for(var i=0,length=properties.length;i<length;i++){var property=properties[i],value=source[property];if(ancestor&&isFunction(value)&&argumentNames(value)[0]=="$super"){var method=value;value=wrap((function(m){return function(){return ancestor[m].apply(this,arguments);};})(property),method);value.valueOf=bind(method.valueOf,method);value.toString=bind(method.toString,method);}
this.prototype[property]=value;}
return this;}
return{create:create,Methods:{addMethods:addMethods}};})();if(globalContext.exports){globalContext.exports.Class=Class;}
else{globalContext.Class=Class;}})(Rickshaw);Rickshaw.namespace('Rickshaw.Compat.ClassList');Rickshaw.Compat.ClassList=function(){if(typeof document!=="undefined"&&!("classList"in document.createElement("a"))){(function(view){"use strict";var
classListProp="classList",protoProp="prototype",elemCtrProto=(view.HTMLElement||view.Element)[protoProp],objCtr=Object,strTrim=String[protoProp].trim||function(){return this.replace(/^\s+|\s+$/g,"");},arrIndexOf=Array[protoProp].indexOf||function(item){var
i=0,len=this.length;for(;i<len;i++){if(i in this&&this[i]===item){return i;}}
return-1;},DOMEx=function(type,message){this.name=type;this.code=DOMException[type];this.message=message;},checkTokenAndGetIndex=function(classList,token){if(token===""){throw new DOMEx("SYNTAX_ERR","An invalid or illegal string was specified");}
if(/\s/.test(token)){throw new DOMEx("INVALID_CHARACTER_ERR","String contains an invalid character");}
return arrIndexOf.call(classList,token);},ClassList=function(elem){var
trimmedClasses=strTrim.call(elem.className),classes=trimmedClasses?trimmedClasses.split(/\s+/):[],i=0,len=classes.length;for(;i<len;i++){this.push(classes[i]);}
this._updateClassName=function(){elem.className=this.toString();};},classListProto=ClassList[protoProp]=[],classListGetter=function(){return new ClassList(this);};DOMEx[protoProp]=Error[protoProp];classListProto.item=function(i){return this[i]||null;};classListProto.contains=function(token){token+="";return checkTokenAndGetIndex(this,token)!==-1;};classListProto.add=function(token){token+="";if(checkTokenAndGetIndex(this,token)===-1){this.push(token);this._updateClassName();}};classListProto.remove=function(token){token+="";var index=checkTokenAndGetIndex(this,token);if(index!==-1){this.splice(index,1);this._updateClassName();}};classListProto.toggle=function(token){token+="";if(checkTokenAndGetIndex(this,token)===-1){this.add(token);}else{this.remove(token);}};classListProto.toString=function(){return this.join(" ");};if(objCtr.defineProperty){var classListPropDesc={get:classListGetter,enumerable:true,configurable:true};try{objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc);}catch(ex){if(ex.number===-0x7FF5EC54){classListPropDesc.enumerable=false;objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc);}}}else if(objCtr[protoProp].__defineGetter__){elemCtrProto.__defineGetter__(classListProp,classListGetter);}}(window));}};if((typeof RICKSHAW_NO_COMPAT!=="undefined"&&!RICKSHAW_NO_COMPAT)||typeof RICKSHAW_NO_COMPAT==="undefined"){new Rickshaw.Compat.ClassList();}
Rickshaw.namespace('Rickshaw.Graph');Rickshaw.Graph=function(args){if(!args.element)throw"Rickshaw.Graph needs a reference to an element";this.element=args.element;this.series=args.series;this.defaults={interpolation:'cardinal',offset:'zero',min:undefined,max:undefined,preserve:false};Rickshaw.keys(this.defaults).forEach(function(k){this[k]=args[k]||this.defaults[k];},this);this.window={};this.updateCallbacks=[];var self=this;this.initialize=function(args){this.validateSeries(args.series);this.series.active=function(){return self.series.filter(function(s){return!s.disabled})};this.setSize({width:args.width,height:args.height});this.element.classList.add('rickshaw_graph');this.vis=d3.select(this.element).append("svg:svg").attr('width',this.width).attr('height',this.height);for(var name in Rickshaw.Graph.Renderer){if(!name||!Rickshaw.Graph.Renderer.hasOwnProperty(name))continue;var r=Rickshaw.Graph.Renderer[name];if(!r||!r.prototype||!r.prototype.render)continue;self.registerRenderer(new r({graph:self}));}
this.setRenderer(args.renderer||'stack',args);this.discoverRange();};this.validateSeries=function(series){if(!Array.isArray(series)&&!(series instanceof Rickshaw.Series)){var seriesSignature=Object.prototype.toString.apply(series);throw"series is not an array: "+seriesSignature;}
var pointsCount;series.forEach(function(s){if(!(s instanceof Object)){throw"series element is not an object: "+s;}
if(!(s.data)){throw"series has no data: "+JSON.stringify(s);}
if(!Array.isArray(s.data)){throw"series data is not an array: "+JSON.stringify(s.data);}
var x=s.data[0].x;var y=s.data[0].y;if(typeof x!='number'||(typeof y!='number'&&y!==null)){throw"x and y properties of points should be numbers instead of "+
(typeof x)+" and "+(typeof y);}
if(s.data.length>=3){if(s.data[2].x<s.data[1].x||s.data[1].x<s.data[0].x||s.data[s.data.length-1].x<s.data[0].x){throw"series data needs to be sorted on x values for series name: "+s.name;}}},this);};this.dataDomain=function(){var data=this.series.map(function(s){return s.data});var min=d3.min(data.map(function(d){return d[0].x}));var max=d3.max(data.map(function(d){return d[d.length-1].x}));return[min,max];};this.discoverRange=function(){var domain=this.renderer.domain();this.x=d3.scale.linear().domain(domain.x).range([0,this.width]);this.y=d3.scale.linear().domain(domain.y).range([this.height,0]);this.y.magnitude=d3.scale.linear().domain([domain.y[0]-domain.y[0],domain.y[1]-domain.y[0]]).range([0,this.height]);};this.render=function(){var stackedData=this.stackData();this.discoverRange();this.renderer.render();this.updateCallbacks.forEach(function(callback){callback();});};this.update=this.render;this.stackData=function(){var data=this.series.active().map(function(d){return d.data}).map(function(d){return d.filter(function(d){return this._slice(d)},this)},this);var preserve=this.preserve;if(!preserve){this.series.forEach(function(series){if(series.scale){preserve=true;}});}
data=preserve?Rickshaw.clone(data):data;this.series.active().forEach(function(series,index){if(series.scale){var seriesData=data[index];if(seriesData){seriesData.forEach(function(d){d.y=series.scale(d.y);});}}});this.stackData.hooks.data.forEach(function(entry){data=entry.f.apply(self,[data]);});var stackedData;if(!this.renderer.unstack){this._validateStackable();var layout=d3.layout.stack();layout.offset(self.offset);stackedData=layout(data);}
stackedData=stackedData||data;this.stackData.hooks.after.forEach(function(entry){stackedData=entry.f.apply(self,[data]);});var i=0;this.series.forEach(function(series){if(series.disabled)return;series.stack=stackedData[i++];});this.stackedData=stackedData;return stackedData;};this._validateStackable=function(){var series=this.series;var pointsCount;series.forEach(function(s){pointsCount=pointsCount||s.data.length;if(pointsCount&&s.data.length!=pointsCount){throw"stacked series cannot have differing numbers of points: "+
pointsCount+" vs "+s.data.length+"; see Rickshaw.Series.fill()";}},this);};this.stackData.hooks={data:[],after:[]};this._slice=function(d){if(this.window.xMin||this.window.xMax){var isInRange=true;if(this.window.xMin&&d.x<this.window.xMin)isInRange=false;if(this.window.xMax&&d.x>this.window.xMax)isInRange=false;return isInRange;}
return true;};this.onUpdate=function(callback){this.updateCallbacks.push(callback);};this.registerRenderer=function(renderer){this._renderers=this._renderers||{};this._renderers[renderer.name]=renderer;};this.configure=function(args){if(args.width||args.height){this.setSize(args);}
Rickshaw.keys(this.defaults).forEach(function(k){this[k]=k in args?args[k]:k in this?this[k]:this.defaults[k];},this);this.setRenderer(args.renderer||this.renderer.name,args);};this.setRenderer=function(r,args){if(typeof r=='function'){this.renderer=new r({graph:self});this.registerRenderer(this.renderer);}else{if(!this._renderers[r]){throw"couldn't find renderer "+r;}
this.renderer=this._renderers[r];}
if(typeof args=='object'){this.renderer.configure(args);}};this.setSize=function(args){args=args||{};if(typeof window!==undefined){var style=window.getComputedStyle(this.element,null);var elementWidth=parseInt(style.getPropertyValue('width'),10);var elementHeight=parseInt(style.getPropertyValue('height'),10);}
this.width=args.width||elementWidth||400;this.height=args.height||elementHeight||250;this.vis&&this.vis.attr('width',this.width).attr('height',this.height);};this.initialize(args);};Rickshaw.namespace('Rickshaw.Fixtures.Color');Rickshaw.Fixtures.Color=function(){this.schemes={};this.schemes.spectrum14=['#ecb796','#dc8f70','#b2a470','#92875a','#716c49','#d2ed82','#bbe468','#a1d05d','#e7cbe6','#d8aad6','#a888c2','#9dc2d3','#649eb9','#387aa3'].reverse();this.schemes.spectrum2000=['#57306f','#514c76','#646583','#738394','#6b9c7d','#84b665','#a7ca50','#bfe746','#e2f528','#fff726','#ecdd00','#d4b11d','#de8800','#de4800','#c91515','#9a0000','#7b0429','#580839','#31082b'];this.schemes.spectrum2001=['#2f243f','#3c2c55','#4a3768','#565270','#6b6b7c','#72957f','#86ad6e','#a1bc5e','#b8d954','#d3e04e','#ccad2a','#cc8412','#c1521d','#ad3821','#8a1010','#681717','#531e1e','#3d1818','#320a1b'];this.schemes.classic9=['#423d4f','#4a6860','#848f39','#a2b73c','#ddcb53','#c5a32f','#7d5836','#963b20','#7c2626','#491d37','#2f254a'].reverse();this.schemes.httpStatus={503:'#ea5029',502:'#d23f14',500:'#bf3613',410:'#efacea',409:'#e291dc',403:'#f457e8',408:'#e121d2',401:'#b92dae',405:'#f47ceb',404:'#a82a9f',400:'#b263c6',301:'#6fa024',302:'#87c32b',307:'#a0d84c',304:'#28b55c',200:'#1a4f74',206:'#27839f',201:'#52adc9',202:'#7c979f',203:'#a5b8bd',204:'#c1cdd1'};this.schemes.colorwheel=['#b5b6a9','#858772','#785f43','#96557e','#4682b4','#65b9ac','#73c03a','#cb513a'].reverse();this.schemes.cool=['#5e9d2f','#73c03a','#4682b4','#7bc3b8','#a9884e','#c1b266','#a47493','#c09fb5'];this.schemes.munin=['#00cc00','#0066b3','#ff8000','#ffcc00','#330099','#990099','#ccff00','#ff0000','#808080','#008f00','#00487d','#b35a00','#b38f00','#6b006b','#8fb300','#b30000','#bebebe','#80ff80','#80c9ff','#ffc080','#ffe680','#aa80ff','#ee00cc','#ff8080','#666600','#ffbfff','#00ffcc','#cc6699','#999900'];};Rickshaw.namespace('Rickshaw.Fixtures.RandomData');Rickshaw.Fixtures.RandomData=function(timeInterval){var addData;timeInterval=timeInterval||1;var lastRandomValue=200;var timeBase=Math.floor(new Date().getTime()/1000);this.addData=function(data){var randomValue=Math.random()*100+15+lastRandomValue;var index=data[0].length;var counter=1;data.forEach(function(series){var randomVariance=Math.random()*20;var v=randomValue/25+counter++ +
(Math.cos((index*counter*11)/960)+2)*15+
(Math.cos(index/7)+2)*7+
(Math.cos(index/17)+2)*1;series.push({x:(index*timeInterval)+timeBase,y:v+randomVariance});});lastRandomValue=randomValue*0.85;};this.removeData=function(data){data.forEach(function(series){series.shift();});timeBase+=timeInterval;};};Rickshaw.namespace('Rickshaw.Fixtures.Time');Rickshaw.Fixtures.Time=function(){var tzOffset=new Date().getTimezoneOffset()*60;var self=this;this.months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];this.units=[{name:'decade',seconds:86400*365.25*10,formatter:function(d){return(parseInt(d.getUTCFullYear()/10,10)*10)}},{name:'year',seconds:86400*365.25,formatter:function(d){return d.getUTCFullYear()}},{name:'month',seconds:86400*30.5,formatter:function(d){return self.months[d.getUTCMonth()]}},{name:'week',seconds:86400*7,formatter:function(d){return self.formatDate(d)}},{name:'day',seconds:86400,formatter:function(d){return d.getUTCDate()}},{name:'6 hour',seconds:3600*6,formatter:function(d){return self.formatTime(d)}},{name:'hour',seconds:3600,formatter:function(d){return self.formatTime(d)}},{name:'15 minute',seconds:60*15,formatter:function(d){return self.formatTime(d)}},{name:'minute',seconds:60,formatter:function(d){return d.getUTCMinutes()}},{name:'15 second',seconds:15,formatter:function(d){return d.getUTCSeconds()+'s'}},{name:'second',seconds:1,formatter:function(d){return d.getUTCSeconds()+'s'}}];this.unit=function(unitName){return this.units.filter(function(unit){return unitName==unit.name}).shift();};this.formatDate=function(d){return d3.time.format('%b %e')(d);};this.formatTime=function(d){return d.toUTCString().match(/(\d+:\d+):/)[1];};this.ceil=function(time,unit){var nearFuture;var rounded;if(unit.name=='month'){nearFuture=new Date((time+unit.seconds-1)*1000);rounded=new Date(0);rounded.setUTCFullYear(nearFuture.getUTCFullYear());rounded.setUTCMonth(nearFuture.getUTCMonth());rounded.setUTCDate(1);rounded.setUTCHours(0);rounded.setUTCMinutes(0);rounded.setUTCSeconds(0);rounded.setUTCMilliseconds(0);return rounded.getTime()/1000;}
if(unit.name=='year'){nearFuture=new Date((time+unit.seconds-1)*1000);rounded=new Date(0);rounded.setUTCFullYear(nearFuture.getUTCFullYear());rounded.setUTCMonth(0);rounded.setUTCDate(1);rounded.setUTCHours(0);rounded.setUTCMinutes(0);rounded.setUTCSeconds(0);rounded.setUTCMilliseconds(0);return rounded.getTime()/1000;}
return Math.ceil(time/unit.seconds)*unit.seconds;};};Rickshaw.namespace('Rickshaw.Fixtures.Time.Local');Rickshaw.Fixtures.Time.Local=function(){var tzOffset=new Date().getTimezoneOffset()*60;var self=this;this.months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];this.units=[{name:'decade',seconds:86400*365.25*10,formatter:function(d){return(parseInt(d.getFullYear()/10,10)*10)}},{name:'year',seconds:86400*365.25,formatter:function(d){return d.getFullYear()}},{name:'month',seconds:86400*30.5,formatter:function(d){return self.months[d.getMonth()]}},{name:'week',seconds:86400*7,formatter:function(d){return self.formatDate(d)}},{name:'day',seconds:86400,formatter:function(d){return d.getDate()}},{name:'6 hour',seconds:3600*6,formatter:function(d){return self.formatTime(d)}},{name:'hour',seconds:3600,formatter:function(d){return self.formatTime(d)}},{name:'15 minute',seconds:60*15,formatter:function(d){return self.formatTime(d)}},{name:'minute',seconds:60,formatter:function(d){return d.getMinutes()}},{name:'15 second',seconds:15,formatter:function(d){return d.getSeconds()+'s'}},{name:'second',seconds:1,formatter:function(d){return d.getSeconds()+'s'}}];this.unit=function(unitName){return this.units.filter(function(unit){return unitName==unit.name}).shift();};this.formatDate=function(d){return d3.time.format('%b %e')(d);};this.formatTime=function(d){return d.toString().match(/(\d+:\d+):/)[1];};this.ceil=function(time,unit){var nearFuture;var rounded;if(unit.name=='day'){nearFuture=new Date((time+unit.seconds-1)*1000);rounded=new Date(0);rounded.setMilliseconds(0);rounded.setSeconds(0);rounded.setMinutes(0);rounded.setHours(0);rounded.setDate(nearFuture.getDate());rounded.setMonth(nearFuture.getMonth());rounded.setFullYear(nearFuture.getFullYear());return rounded.getTime()/1000;}
if(unit.name=='month'){nearFuture=new Date((time+unit.seconds-1)*1000);rounded=new Date(0);rounded.setMilliseconds(0);rounded.setSeconds(0);rounded.setMinutes(0);rounded.setHours(0);rounded.setDate(1);rounded.setMonth(nearFuture.getMonth());rounded.setFullYear(nearFuture.getFullYear());return rounded.getTime()/1000;}
if(unit.name=='year'){nearFuture=new Date((time+unit.seconds-1)*1000);rounded=new Date(0);rounded.setFullYear(nearFuture.getFullYear());rounded.setMilliseconds(0);rounded.setSeconds(0);rounded.setMinutes(0);rounded.setHours(0);rounded.setDate(1);rounded.setMonth(0);return rounded.getTime()/1000;}
return Math.ceil(time/unit.seconds)*unit.seconds;};};Rickshaw.namespace('Rickshaw.Fixtures.Number');Rickshaw.Fixtures.Number.formatKMBT=function(y){var abs_y=Math.abs(y);if(abs_y>=1000000000000){return y/1000000000000+"T"}
else if(abs_y>=1000000000){return y/1000000000+"B"}
else if(abs_y>=1000000){return y/1000000+"M"}
else if(abs_y>=1000){return y/1000+"K"}
else if(abs_y<1&&y>0){return y.toFixed(2)}
else if(abs_y===0){return''}
else{return y}};Rickshaw.Fixtures.Number.formatBase1024KMGTP=function(y){var abs_y=Math.abs(y);if(abs_y>=1125899906842624){return y/1125899906842624+"P"}
else if(abs_y>=1099511627776){return y/1099511627776+"T"}
else if(abs_y>=1073741824){return y/1073741824+"G"}
else if(abs_y>=1048576){return y/1048576+"M"}
else if(abs_y>=1024){return y/1024+"K"}
else if(abs_y<1&&y>0){return y.toFixed(2)}
else if(abs_y===0){return''}
else{return y}};Rickshaw.namespace("Rickshaw.Color.Palette");Rickshaw.Color.Palette=function(args){var color=new Rickshaw.Fixtures.Color();args=args||{};this.schemes={};this.scheme=color.schemes[args.scheme]||args.scheme||color.schemes.colorwheel;this.runningIndex=0;this.generatorIndex=0;if(args.interpolatedStopCount){var schemeCount=this.scheme.length-1;var i,j,scheme=[];for(i=0;i<schemeCount;i++){scheme.push(this.scheme[i]);var generator=d3.interpolateHsl(this.scheme[i],this.scheme[i+1]);for(j=1;j<args.interpolatedStopCount;j++){scheme.push(generator((1/args.interpolatedStopCount)*j));}}
scheme.push(this.scheme[this.scheme.length-1]);this.scheme=scheme;}
this.rotateCount=this.scheme.length;this.color=function(key){return this.scheme[key]||this.scheme[this.runningIndex++]||this.interpolateColor()||'#808080';};this.interpolateColor=function(){if(!Array.isArray(this.scheme))return;var color;if(this.generatorIndex==this.rotateCount*2-1){color=d3.interpolateHsl(this.scheme[this.generatorIndex],this.scheme[0])(0.5);this.generatorIndex=0;this.rotateCount*=2;}else{color=d3.interpolateHsl(this.scheme[this.generatorIndex],this.scheme[this.generatorIndex+1])(0.5);this.generatorIndex++;}
this.scheme.push(color);return color;};};Rickshaw.namespace('Rickshaw.Graph.Ajax');Rickshaw.Graph.Ajax=Rickshaw.Class.create({initialize:function(args){this.dataURL=args.dataURL;this.onData=args.onData||function(d){return d};this.onComplete=args.onComplete||function(){};this.onError=args.onError||function(){};this.args=args;this.request();},request:function(){$.ajax({url:this.dataURL,dataType:'json',success:this.success.bind(this),error:this.error.bind(this)});},error:function(){console.log("error loading dataURL: "+this.dataURL);this.onError(this);},success:function(data,status){data=this.onData(data);this.args.series=this._splice({data:data,series:this.args.series});this.graph=this.graph||new Rickshaw.Graph(this.args);this.graph.render();this.onComplete(this);},_splice:function(args){var data=args.data;var series=args.series;if(!args.series)return data;series.forEach(function(s){var seriesKey=s.key||s.name;if(!seriesKey)throw"series needs a key or a name";data.forEach(function(d){var dataKey=d.key||d.name;if(!dataKey)throw"data needs a key or a name";if(seriesKey==dataKey){var properties=['color','name','data'];properties.forEach(function(p){if(d[p])s[p]=d[p];});}});});return series;}});Rickshaw.namespace('Rickshaw.Graph.Annotate');Rickshaw.Graph.Annotate=function(args){var graph=this.graph=args.graph;this.elements={timeline:args.element};var self=this;this.data={};this.elements.timeline.classList.add('rickshaw_annotation_timeline');this.add=function(time,content,end_time){self.data[time]=self.data[time]||{'boxes':[]};self.data[time].boxes.push({content:content,end:end_time});};this.update=function(){Rickshaw.keys(self.data).forEach(function(time){var annotation=self.data[time];var left=self.graph.x(time);if(left<0||left>self.graph.x.range()[1]){if(annotation.element){annotation.line.classList.add('offscreen');annotation.element.style.display='none';}
annotation.boxes.forEach(function(box){if(box.rangeElement)box.rangeElement.classList.add('offscreen');});return;}
if(!annotation.element){var element=annotation.element=document.createElement('div');element.classList.add('annotation');this.elements.timeline.appendChild(element);element.addEventListener('click',function(e){element.classList.toggle('active');annotation.line.classList.toggle('active');annotation.boxes.forEach(function(box){if(box.rangeElement)box.rangeElement.classList.toggle('active');});},false);}
annotation.element.style.left=left+'px';annotation.element.style.display='block';annotation.boxes.forEach(function(box){var element=box.element;if(!element){element=box.element=document.createElement('div');element.classList.add('content');element.innerHTML=box.content;annotation.element.appendChild(element);annotation.line=document.createElement('div');annotation.line.classList.add('annotation_line');self.graph.element.appendChild(annotation.line);if(box.end){box.rangeElement=document.createElement('div');box.rangeElement.classList.add('annotation_range');self.graph.element.appendChild(box.rangeElement);}}
if(box.end){var annotationRangeStart=left;var annotationRangeEnd=Math.min(self.graph.x(box.end),self.graph.x.range()[1]);if(annotationRangeStart>annotationRangeEnd){annotationRangeEnd=left;annotationRangeStart=Math.max(self.graph.x(box.end),self.graph.x.range()[0]);}
var annotationRangeWidth=annotationRangeEnd-annotationRangeStart;box.rangeElement.style.left=annotationRangeStart+'px';box.rangeElement.style.width=annotationRangeWidth+'px';box.rangeElement.classList.remove('offscreen');}
annotation.line.classList.remove('offscreen');annotation.line.style.left=left+'px';});},this);};this.graph.onUpdate(function(){self.update()});};Rickshaw.namespace('Rickshaw.Graph.Axis.Time');Rickshaw.Graph.Axis.Time=function(args){var self=this;this.graph=args.graph;this.elements=[];this.ticksTreatment=args.ticksTreatment||'plain';this.fixedTimeUnit=args.timeUnit;var time=args.timeFixture||new Rickshaw.Fixtures.Time();this.appropriateTimeUnit=function(){var unit;var units=time.units;var domain=this.graph.x.domain();var rangeSeconds=domain[1]-domain[0];units.forEach(function(u){if(Math.floor(rangeSeconds/u.seconds)>=2){unit=unit||u;}});return(unit||time.units[time.units.length-1]);};this.tickOffsets=function(){var domain=this.graph.x.domain();var unit=this.fixedTimeUnit||this.appropriateTimeUnit();var count=Math.ceil((domain[1]-domain[0])/unit.seconds);var runningTick=domain[0];var offsets=[];for(var i=0;i<count;i++){var tickValue=time.ceil(runningTick,unit);runningTick=tickValue+unit.seconds/2;offsets.push({value:tickValue,unit:unit});}
return offsets;};this.render=function(){this.elements.forEach(function(e){e.parentNode.removeChild(e);});this.elements=[];var offsets=this.tickOffsets();offsets.forEach(function(o){if(self.graph.x(o.value)>self.graph.x.range()[1])return;var element=document.createElement('div');element.style.left=self.graph.x(o.value)+'px';element.classList.add('x_tick');element.classList.add(self.ticksTreatment);var title=document.createElement('div');title.classList.add('title');title.innerHTML=o.unit.formatter(new Date(o.value*1000));element.appendChild(title);self.graph.element.appendChild(element);self.elements.push(element);});};this.graph.onUpdate(function(){self.render()});};Rickshaw.namespace('Rickshaw.Graph.Axis.X');Rickshaw.Graph.Axis.X=function(args){var self=this;var berthRate=0.10;this.initialize=function(args){this.graph=args.graph;this.orientation=args.orientation||'top';this.pixelsPerTick=args.pixelsPerTick||75;if(args.ticks)this.staticTicks=args.ticks;if(args.tickValues)this.tickValues=args.tickValues;this.tickSize=args.tickSize||4;this.ticksTreatment=args.ticksTreatment||'plain';if(args.element){this.element=args.element;this._discoverSize(args.element,args);this.vis=d3.select(args.element).append("svg:svg").attr('height',this.height).attr('width',this.width).attr('class','rickshaw_graph x_axis_d3');this.element=this.vis[0][0];this.element.style.position='relative';this.setSize({width:args.width,height:args.height});}else{this.vis=this.graph.vis;}
this.graph.onUpdate(function(){self.render()});};this.setSize=function(args){args=args||{};if(!this.element)return;this._discoverSize(this.element.parentNode,args);this.vis.attr('height',this.height).attr('width',this.width*(1+berthRate));var berth=Math.floor(this.width*berthRate/2);this.element.style.left=-1*berth+'px';};this.render=function(){if(this.graph.width!==this._renderWidth)this.setSize({auto:true});var axis=d3.svg.axis().scale(this.graph.x).orient(this.orientation);axis.tickFormat(args.tickFormat||function(x){return x});if(this.tickValues)axis.tickValues(this.tickValues);this.ticks=this.staticTicks||Math.floor(this.graph.width/this.pixelsPerTick);var berth=Math.floor(this.width*berthRate/2)||0;var transform;if(this.orientation=='top'){var yOffset=this.height||this.graph.height;transform='translate('+berth+','+yOffset+')';}else{transform='translate('+berth+', 0)';}
if(this.element){this.vis.selectAll('*').remove();}
this.vis.append("svg:g").attr("class",["x_ticks_d3",this.ticksTreatment].join(" ")).attr("transform",transform).call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize));var gridSize=(this.orientation=='bottom'?1:-1)*this.graph.height;this.graph.vis.append("svg:g").attr("class","x_grid_d3").call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize));this._renderHeight=this.graph.height;};this._discoverSize=function(element,args){if(typeof window!=='undefined'){var style=window.getComputedStyle(element,null);var elementHeight=parseInt(style.getPropertyValue('height'),10);if(!args.auto){var elementWidth=parseInt(style.getPropertyValue('width'),10);}}
this.width=(args.width||elementWidth||this.graph.width)*(1+berthRate);this.height=args.height||elementHeight||40;};this.initialize(args);};Rickshaw.namespace('Rickshaw.Graph.Axis.Y');Rickshaw.Graph.Axis.Y=Rickshaw.Class.create({initialize:function(args){this.graph=args.graph;this.orientation=args.orientation||'right';this.pixelsPerTick=args.pixelsPerTick||75;if(args.ticks)this.staticTicks=args.ticks;if(args.tickValues)this.tickValues=args.tickValues;this.tickSize=args.tickSize||4;this.ticksTreatment=args.ticksTreatment||'plain';this.tickFormat=args.tickFormat||function(y){return y};this.berthRate=0.10;if(args.element){this.element=args.element;this.vis=d3.select(args.element).append("svg:svg").attr('class','rickshaw_graph y_axis');this.element=this.vis[0][0];this.element.style.position='relative';this.setSize({width:args.width,height:args.height});}else{this.vis=this.graph.vis;}
var self=this;this.graph.onUpdate(function(){self.render()});},setSize:function(args){args=args||{};if(!this.element)return;if(typeof window!=='undefined'){var style=window.getComputedStyle(this.element.parentNode,null);var elementWidth=parseInt(style.getPropertyValue('width'),10);if(!args.auto){var elementHeight=parseInt(style.getPropertyValue('height'),10);}}
this.width=args.width||elementWidth||this.graph.width*this.berthRate;this.height=args.height||elementHeight||this.graph.height;this.vis.attr('width',this.width).attr('height',this.height*(1+this.berthRate));var berth=this.height*this.berthRate;if(this.orientation=='left'){this.element.style.top=-1*berth+'px';}},render:function(){if(this.graph.height!==this._renderHeight)this.setSize({auto:true});this.ticks=this.staticTicks||Math.floor(this.graph.height/this.pixelsPerTick);var axis=this._drawAxis(this.graph.y);this._drawGrid(axis);this._renderHeight=this.graph.height;},_drawAxis:function(scale){var axis=d3.svg.axis().scale(scale).orient(this.orientation);axis.tickFormat(this.tickFormat);if(this.tickValues)axis.tickValues(this.tickValues);if(this.orientation=='left'){var berth=this.height*this.berthRate;var transform='translate('+this.width+', '+berth+')';}
if(this.element){this.vis.selectAll('*').remove();}
this.vis.append("svg:g").attr("class",["y_ticks",this.ticksTreatment].join(" ")).attr("transform",transform).call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize));return axis;},_drawGrid:function(axis){var gridSize=(this.orientation=='right'?1:-1)*this.graph.width;this.graph.vis.append("svg:g").attr("class","y_grid").call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize));}});Rickshaw.namespace('Rickshaw.Graph.Axis.Y.Scaled');Rickshaw.Graph.Axis.Y.Scaled=Rickshaw.Class.create(Rickshaw.Graph.Axis.Y,{initialize:function($super,args){if(typeof(args.scale)==='undefined'){throw new Error('Scaled requires scale');}
this.scale=args.scale;if(typeof(args.grid)==='undefined'){this.grid=true;}else{this.grid=args.grid;}
$super(args);},_drawAxis:function($super,scale){var adjustedScale=this.scale.copy().range(scale.range());return $super(adjustedScale);},_drawGrid:function($super,axis){if(this.grid){$super(axis);}}});Rickshaw.namespace('Rickshaw.Graph.Behavior.Series.Highlight');Rickshaw.Graph.Behavior.Series.Highlight=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;var colorSafe={};var activeLine=null;var disabledColor=args.disabledColor||function(seriesColor){return d3.interpolateRgb(seriesColor,d3.rgb('#d8d8d8'))(0.8).toString();};this.addHighlightEvents=function(l){l.element.addEventListener('mouseover',function(e){if(activeLine)return;else activeLine=l;self.legend.lines.forEach(function(line,index){if(l===line){if(index>0&&self.graph.renderer.unstack&&(line.series.renderer?line.series.renderer.unstack:true)){var seriesIndex=self.graph.series.length-index-1;line.originalIndex=seriesIndex;var series=self.graph.series.splice(seriesIndex,1)[0];self.graph.series.push(series);}
return;}
colorSafe[line.series.name]=colorSafe[line.series.name]||line.series.color;line.series.color=disabledColor(line.series.color);});self.graph.update();},false);l.element.addEventListener('mouseout',function(e){if(!activeLine)return;else activeLine=null;self.legend.lines.forEach(function(line){if(l===line&&line.hasOwnProperty('originalIndex')){var series=self.graph.series.pop();self.graph.series.splice(line.originalIndex,0,series);delete line.originalIndex;}
if(colorSafe[line.series.name]){line.series.color=colorSafe[line.series.name];}});self.graph.update();},false);};if(this.legend){this.legend.lines.forEach(function(l){self.addHighlightEvents(l);});}};Rickshaw.namespace('Rickshaw.Graph.Behavior.Series.Order');Rickshaw.Graph.Behavior.Series.Order=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;if(typeof window.$=='undefined'){throw"couldn't find jQuery at window.$";}
if(typeof window.$.ui=='undefined'){throw"couldn't find jQuery UI at window.$.ui";}
$(function(){$(self.legend.list).sortable({containment:'parent',tolerance:'pointer',update:function(event,ui){var series=[];$(self.legend.list).find('li').each(function(index,item){if(!item.series)return;series.push(item.series);});for(var i=self.graph.series.length-1;i>=0;i--){self.graph.series[i]=series.shift();}
self.graph.update();}});$(self.legend.list).disableSelection();});this.graph.onUpdate(function(){var h=window.getComputedStyle(self.legend.element).height;self.legend.element.style.height=h;});};Rickshaw.namespace('Rickshaw.Graph.Behavior.Series.Toggle');Rickshaw.Graph.Behavior.Series.Toggle=function(args){this.graph=args.graph;this.legend=args.legend;var self=this;this.addAnchor=function(line){var anchor=document.createElement('a');anchor.innerHTML='&#10004;';anchor.classList.add('action');line.element.insertBefore(anchor,line.element.firstChild);anchor.onclick=function(e){if(line.series.disabled){line.series.enable();line.element.classList.remove('disabled');}else{if(this.graph.series.filter(function(s){return!s.disabled}).length<=1)return;line.series.disable();line.element.classList.add('disabled');}}.bind(this);var label=line.element.getElementsByTagName('span')[0];label.onclick=function(e){var disableAllOtherLines=line.series.disabled;if(!disableAllOtherLines){for(var i=0;i<self.legend.lines.length;i++){var l=self.legend.lines[i];if(line.series===l.series){}else if(l.series.disabled){}else{disableAllOtherLines=true;break;}}}
if(disableAllOtherLines){line.series.enable();line.element.classList.remove('disabled');self.legend.lines.forEach(function(l){if(line.series===l.series){}else{l.series.disable();l.element.classList.add('disabled');}});}else{self.legend.lines.forEach(function(l){l.series.enable();l.element.classList.remove('disabled');});}};};if(this.legend){if(typeof $!='undefined'&&$(this.legend.list).sortable){$(this.legend.list).sortable({start:function(event,ui){ui.item.bind('no.onclick',function(event){event.preventDefault();});},stop:function(event,ui){setTimeout(function(){ui.item.unbind('no.onclick');},250);}});}
this.legend.lines.forEach(function(l){self.addAnchor(l);});}
this._addBehavior=function(){this.graph.series.forEach(function(s){s.disable=function(){if(self.graph.series.length<=1){throw('only one series left');}
s.disabled=true;self.graph.update();};s.enable=function(){s.disabled=false;self.graph.update();};});};this._addBehavior();this.updateBehaviour=function(){this._addBehavior()};};Rickshaw.namespace('Rickshaw.Graph.HoverDetail');Rickshaw.Graph.HoverDetail=Rickshaw.Class.create({initialize:function(args){var graph=this.graph=args.graph;this.xFormatter=args.xFormatter||function(x){return new Date(x*1000).toUTCString();};this.yFormatter=args.yFormatter||function(y){return y===null?y:y.toFixed(2);};var element=this.element=document.createElement('div');element.className='detail';this.visible=true;graph.element.appendChild(element);this.lastEvent=null;this._addListeners();this.onShow=args.onShow;this.onHide=args.onHide;this.onRender=args.onRender;this.formatter=args.formatter||this.formatter;},formatter:function(series,x,y,formattedX,formattedY,d){return series.name+':&nbsp;'+formattedY;},update:function(e){e=e||this.lastEvent;if(!e)return;this.lastEvent=e;if(!e.target.nodeName.match(/^(path|svg|rect|circle)$/))return;var graph=this.graph;var eventX=e.offsetX||e.layerX;var eventY=e.offsetY||e.layerY;var j=0;var points=[];var nearestPoint;this.graph.series.active().forEach(function(series){var data=this.graph.stackedData[j++];if(!data.length)
return;var domainX=graph.x.invert(eventX);var domainIndexScale=d3.scale.linear().domain([data[0].x,data.slice(-1)[0].x]).range([0,data.length-1]);var approximateIndex=Math.round(domainIndexScale(domainX));if(approximateIndex==data.length-1)approximateIndex--;var dataIndex=Math.min(approximateIndex||0,data.length-1);for(var i=approximateIndex;i<data.length-1;){if(!data[i]||!data[i+1])break;if(data[i].x<=domainX&&data[i+1].x>domainX){dataIndex=Math.abs(domainX-data[i].x)<Math.abs(domainX-data[i+1].x)?i:i+1;break;}
if(data[i+1].x<=domainX){i++}else{i--}}
if(dataIndex<0)dataIndex=0;var value=data[dataIndex];var distance=Math.sqrt(Math.pow(Math.abs(graph.x(value.x)-eventX),2)+
Math.pow(Math.abs(graph.y(value.y+value.y0)-eventY),2));var xFormatter=series.xFormatter||this.xFormatter;var yFormatter=series.yFormatter||this.yFormatter;var point={formattedXValue:xFormatter(value.x),formattedYValue:yFormatter(series.scale?series.scale.invert(value.y):value.y),series:series,value:value,distance:distance,order:j,name:series.name};if(!nearestPoint||distance<nearestPoint.distance){nearestPoint=point;}
points.push(point);},this);if(!nearestPoint)
return;nearestPoint.active=true;var domainX=nearestPoint.value.x;var formattedXValue=nearestPoint.formattedXValue;this.element.innerHTML='';this.element.style.left=graph.x(domainX)+'px';this.visible&&this.render({points:points,detail:points,mouseX:eventX,mouseY:eventY,formattedXValue:formattedXValue,domainX:domainX});},hide:function(){this.visible=false;this.element.classList.add('inactive');if(typeof this.onHide=='function'){this.onHide();}},show:function(){this.visible=true;this.element.classList.remove('inactive');if(typeof this.onShow=='function'){this.onShow();}},render:function(args){var graph=this.graph;var points=args.points;var point=points.filter(function(p){return p.active}).shift();if(point.value.y===null)return;var formattedXValue=point.formattedXValue;var formattedYValue=point.formattedYValue;this.element.innerHTML='';this.element.style.left=graph.x(point.value.x)+'px';var xLabel=document.createElement('div');xLabel.className='x_label';xLabel.innerHTML=formattedXValue;this.element.appendChild(xLabel);var item=document.createElement('div');item.className='item';var series=point.series;var actualY=series.scale?series.scale.invert(point.value.y):point.value.y;item.innerHTML=this.formatter(series,point.value.x,actualY,formattedXValue,formattedYValue,point);item.style.top=this.graph.y(point.value.y0+point.value.y)+'px';this.element.appendChild(item);var dot=document.createElement('div');dot.className='dot';dot.style.top=item.style.top;dot.style.borderColor=series.color;this.element.appendChild(dot);if(point.active){item.className='item active';dot.className='dot active';}
this.show();if(typeof this.onRender=='function'){this.onRender(args);}},_addListeners:function(){this.graph.element.addEventListener('mousemove',function(e){this.visible=true;this.update(e);}.bind(this),false);this.graph.onUpdate(function(){this.update()}.bind(this));this.graph.element.addEventListener('mouseout',function(e){if(e.relatedTarget&&!(e.relatedTarget.compareDocumentPosition(this.graph.element)&Node.DOCUMENT_POSITION_CONTAINS)){this.hide();}}.bind(this),false);}});Rickshaw.namespace('Rickshaw.Graph.JSONP');Rickshaw.Graph.JSONP=Rickshaw.Class.create(Rickshaw.Graph.Ajax,{request:function(){$.ajax({url:this.dataURL,dataType:'jsonp',success:this.success.bind(this),error:this.error.bind(this)});}});Rickshaw.namespace('Rickshaw.Graph.Legend');Rickshaw.Graph.Legend=function(args){var element=this.element=args.element;var graph=this.graph=args.graph;var self=this;element.classList.add('rickshaw_legend');var list=this.list=document.createElement('ul');element.appendChild(list);var series=graph.series.map(function(s){return s});if(!args.naturalOrder){series=series.reverse();}
this.lines=[];this.addLine=function(series){var line=document.createElement('li');line.className='line';if(series.disabled){line.className+=' disabled';}
var swatch=document.createElement('div');swatch.className='swatch';swatch.style.backgroundColor=series.color;line.appendChild(swatch);var label=document.createElement('span');label.className='label';label.innerHTML=series.name;line.appendChild(label);list.appendChild(line);line.series=series;if(series.noLegend){line.style.display='none';}
var _line={element:line,series:series};if(self.shelving){self.shelving.addAnchor(_line);self.shelving.updateBehaviour();}
if(self.highlighter){self.highlighter.addHighlightEvents(_line);}
self.lines.push(_line);};series.forEach(function(s){self.addLine(s);});graph.onUpdate(function(){});};Rickshaw.namespace('Rickshaw.Graph.RangeSlider');Rickshaw.Graph.RangeSlider=Rickshaw.Class.create({initialize:function(args){var element=this.element=args.element;var graph=this.graph=args.graph;this.build();graph.onUpdate(function(){this.update()}.bind(this));},build:function(){var element=this.element;var graph=this.graph;var domain=graph.dataDomain();$(function(){$(element).slider({range:true,min:domain[0],max:domain[1],values:[domain[0],domain[1]],slide:function(event,ui){if(ui.values[1]<=ui.values[0])return;graph.window.xMin=ui.values[0];graph.window.xMax=ui.values[1];graph.update();var domain=graph.dataDomain();if(domain[0]==ui.values[0]){graph.window.xMin=undefined;}
if(domain[1]==ui.values[1]){graph.window.xMax=undefined;}}});});element[0].style.width=graph.width+'px';},update:function(){var element=this.element;var graph=this.graph;var values=$(element).slider('option','values');var domain=graph.dataDomain();$(element).slider('option','min',domain[0]);$(element).slider('option','max',domain[1]);if(graph.window.xMin==null){values[0]=domain[0];}
if(graph.window.xMax==null){values[1]=domain[1];}
$(element).slider('option','values',values);}});Rickshaw.namespace("Rickshaw.Graph.Renderer");Rickshaw.Graph.Renderer=Rickshaw.Class.create({initialize:function(args){this.graph=args.graph;this.tension=args.tension||this.tension;this.graph.unstacker=this.graph.unstacker||new Rickshaw.Graph.Unstacker({graph:this.graph});this.configure(args);},seriesPathFactory:function(){},seriesStrokeFactory:function(){},defaults:function(){return{tension:0.8,strokeWidth:2,unstack:true,padding:{top:0.01,right:0,bottom:0.01,left:0},stroke:false,fill:false};},domain:function(data){var stackedData=data||this.graph.stackedData||this.graph.stackData();var firstPoint=stackedData[0][0];if(firstPoint===undefined){return{x:[null,null],y:[null,null]};}
var xMin=firstPoint.x;var xMax=firstPoint.x;var yMin=firstPoint.y+firstPoint.y0;var yMax=firstPoint.y+firstPoint.y0;stackedData.forEach(function(series){series.forEach(function(d){if(d.y==null)return;var y=d.y+d.y0;if(y<yMin)yMin=y;if(y>yMax)yMax=y;});if(series[0].x<xMin)xMin=series[0].x;if(series[series.length-1].x>xMax)xMax=series[series.length-1].x;});xMin-=(xMax-xMin)*this.padding.left;xMax+=(xMax-xMin)*this.padding.right;yMin=this.graph.min==='auto'?yMin:this.graph.min||0;yMax=this.graph.max===undefined?yMax:this.graph.max;if(this.graph.min==='auto'||yMin<0){yMin-=(yMax-yMin)*this.padding.bottom;}
if(this.graph.max===undefined){yMax+=(yMax-yMin)*this.padding.top;}
return{x:[xMin,xMax],y:[yMin,yMax]};},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;vis.selectAll('*').remove();var data=series.filter(function(s){return!s.disabled}).map(function(s){return s.stack});var nodes=vis.selectAll("path").data(data).enter().append("svg:path").attr("d",this.seriesPathFactory());var i=0;series.forEach(function(series){if(series.disabled)return;series.path=nodes[0][i++];this._styleSeries(series);},this);},_styleSeries:function(series){var fill=this.fill?series.color:'none';var stroke=this.stroke?series.color:'none';series.path.setAttribute('fill',fill);series.path.setAttribute('stroke',stroke);series.path.setAttribute('stroke-width',this.strokeWidth);series.path.setAttribute('class',series.className);},configure:function(args){args=args||{};Rickshaw.keys(this.defaults()).forEach(function(key){if(!args.hasOwnProperty(key)){this[key]=this[key]||this.graph[key]||this.defaults()[key];return;}
if(typeof this.defaults()[key]=='object'){Rickshaw.keys(this.defaults()[key]).forEach(function(k){this[key][k]=args[key][k]!==undefined?args[key][k]:this[key][k]!==undefined?this[key][k]:this.defaults()[key][k];},this);}else{this[key]=args[key]!==undefined?args[key]:this[key]!==undefined?this[key]:this.graph[key]!==undefined?this.graph[key]:this.defaults()[key];}},this);},setStrokeWidth:function(strokeWidth){if(strokeWidth!==undefined){this.strokeWidth=strokeWidth;}},setTension:function(tension){if(tension!==undefined){this.tension=tension;}}});Rickshaw.namespace('Rickshaw.Graph.Renderer.Line');Rickshaw.Graph.Renderer.Line=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'line',defaults:function($super){return Rickshaw.extend($super(),{unstack:true,fill:false,stroke:true});},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.line().x(function(d){return graph.x(d.x)}).y(function(d){return graph.y(d.y)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory;}});Rickshaw.namespace('Rickshaw.Graph.Renderer.Stack');Rickshaw.Graph.Renderer.Stack=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'stack',defaults:function($super){return Rickshaw.extend($super(),{fill:true,stroke:false,unstack:false});},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.area().x(function(d){return graph.x(d.x)}).y0(function(d){return graph.y(d.y0)}).y1(function(d){return graph.y(d.y+d.y0)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory;}});Rickshaw.namespace('Rickshaw.Graph.Renderer.Bar');Rickshaw.Graph.Renderer.Bar=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'bar',defaults:function($super){var defaults=Rickshaw.extend($super(),{gapSize:0.05,unstack:false});delete defaults.tension;return defaults;},initialize:function($super,args){args=args||{};this.gapSize=args.gapSize||this.gapSize;$super(args);},domain:function($super){var domain=$super();var frequentInterval=this._frequentInterval(this.graph.stackedData.slice(-1).shift());domain.x[1]+=Number(frequentInterval.magnitude);return domain;},barWidth:function(series){var frequentInterval=this._frequentInterval(series.stack);var barWidth=this.graph.x(series.stack[0].x+frequentInterval.magnitude*(1-this.gapSize));return barWidth;},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;vis.selectAll('*').remove();var barWidth=this.barWidth(series.active()[0]);var barXOffset=0;var activeSeriesCount=series.filter(function(s){return!s.disabled;}).length;var seriesBarWidth=this.unstack?barWidth/activeSeriesCount:barWidth;var transform=function(d){var matrix=[1,0,0,(d.y<0?-1:1),0,(d.y<0?graph.y.magnitude(Math.abs(d.y))*2:0)];return"matrix("+matrix.join(',')+")";};series.forEach(function(series){if(series.disabled)return;var barWidth=this.barWidth(series);var nodes=vis.selectAll("path").data(series.stack.filter(function(d){return d.y!==null})).enter().append("svg:rect").attr("x",function(d){return graph.x(d.x)+barXOffset}).attr("y",function(d){return(graph.y(d.y0+Math.abs(d.y)))*(d.y<0?-1:1)}).attr("width",seriesBarWidth).attr("height",function(d){return graph.y.magnitude(Math.abs(d.y))}).attr("transform",transform);Array.prototype.forEach.call(nodes[0],function(n){n.setAttribute('fill',series.color);});if(this.unstack)barXOffset+=seriesBarWidth;},this);},_frequentInterval:function(data){var intervalCounts={};for(var i=0;i<data.length-1;i++){var interval=data[i+1].x-data[i].x;intervalCounts[interval]=intervalCounts[interval]||0;intervalCounts[interval]++;}
var frequentInterval={count:0,magnitude:1};Rickshaw.keys(intervalCounts).forEach(function(i){if(frequentInterval.count<intervalCounts[i]){frequentInterval={count:intervalCounts[i],magnitude:i};}});return frequentInterval;}});Rickshaw.namespace('Rickshaw.Graph.Renderer.Area');Rickshaw.Graph.Renderer.Area=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'area',defaults:function($super){return Rickshaw.extend($super(),{unstack:false,fill:false,stroke:false});},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.area().x(function(d){return graph.x(d.x)}).y0(function(d){return graph.y(d.y0)}).y1(function(d){return graph.y(d.y+d.y0)}).interpolate(graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory;},seriesStrokeFactory:function(){var graph=this.graph;var factory=d3.svg.line().x(function(d){return graph.x(d.x)}).y(function(d){return graph.y(d.y+d.y0)}).interpolate(graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory;},render:function(){var graph=this.graph;graph.vis.selectAll('*').remove();var method=this.unstack?'append':'insert';var nodes=graph.vis.selectAll("path").data(this.graph.stackedData).enter()[method]("svg:g",'g');nodes.append("svg:path").attr("d",this.seriesPathFactory()).attr("class",'area');if(this.stroke){nodes.append("svg:path").attr("d",this.seriesStrokeFactory()).attr("class",'line');}
var i=0;graph.series.forEach(function(series){if(series.disabled)return;series.path=nodes[0][i++];this._styleSeries(series);},this);},_styleSeries:function(series){if(!series.path)return;d3.select(series.path).select('.area').attr('fill',series.color);if(this.stroke){d3.select(series.path).select('.line').attr('fill','none').attr('stroke',series.stroke||d3.interpolateRgb(series.color,'black')(0.125)).attr('stroke-width',this.strokeWidth);}
if(series.className){series.path.setAttribute('class',series.className);}}});Rickshaw.namespace('Rickshaw.Graph.Renderer.ScatterPlot');Rickshaw.Graph.Renderer.ScatterPlot=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'scatterplot',defaults:function($super){return Rickshaw.extend($super(),{unstack:true,fill:true,stroke:false,padding:{top:0.01,right:0.01,bottom:0.01,left:0.01},dotSize:4});},initialize:function($super,args){$super(args);},render:function(args){args=args||{};var graph=this.graph;var series=args.series||graph.series;var vis=args.vis||graph.vis;var dotSize=this.dotSize;vis.selectAll('*').remove();series.forEach(function(series){if(series.disabled)return;var nodes=vis.selectAll("path").data(series.stack.filter(function(d){return d.y!==null})).enter().append("svg:circle").attr("cx",function(d){return graph.x(d.x)}).attr("cy",function(d){return graph.y(d.y)}).attr("r",function(d){return("r"in d)?d.r:dotSize});Array.prototype.forEach.call(nodes[0],function(n){n.setAttribute('fill',series.color);});},this);}});Rickshaw.namespace('Rickshaw.Graph.Renderer.Multi');Rickshaw.Graph.Renderer.Multi=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'multi',initialize:function($super,args){$super(args);},defaults:function($super){return Rickshaw.extend($super(),{unstack:true,fill:false,stroke:true});},domain:function($super){this.graph.stackData();var domains=[];var groups=this._groups();this._stack(groups);groups.forEach(function(group){var data=group.series.filter(function(s){return!s.disabled}).map(function(s){return s.stack});if(!data.length)return;var domain=$super(data);domains.push(domain);});var xMin=d3.min(domains.map(function(d){return d.x[0]}));var xMax=d3.max(domains.map(function(d){return d.x[1]}));var yMin=d3.min(domains.map(function(d){return d.y[0]}));var yMax=d3.max(domains.map(function(d){return d.y[1]}));return{x:[xMin,xMax],y:[yMin,yMax]};},_groups:function(){var graph=this.graph;var renderGroups={};graph.series.forEach(function(series){if(series.disabled)return;if(!renderGroups[series.renderer]){var ns="http://www.w3.org/2000/svg";var vis=document.createElementNS(ns,'g');graph.vis[0][0].appendChild(vis);var renderer=graph._renderers[series.renderer];renderGroups[series.renderer]={renderer:renderer,series:[],vis:d3.select(vis)};}
renderGroups[series.renderer].series.push(series);},this);var groups=[];Object.keys(renderGroups).forEach(function(key){var group=renderGroups[key];groups.push(group);});return groups;},_stack:function(groups){groups.forEach(function(group){var series=group.series.filter(function(series){return!series.disabled});var data=series.map(function(series){return series.stack});if(!group.renderer.unstack){var layout=d3.layout.stack();var stackedData=Rickshaw.clone(layout(data));series.forEach(function(series,index){series._stack=Rickshaw.clone(stackedData[index]);});}},this);return groups;},render:function(){this.graph.series.forEach(function(series){if(!series.renderer){throw new Error("Each series needs a renderer for graph 'multi' renderer");}});this.graph.vis.selectAll('*').remove();var groups=this._groups();groups=this._stack(groups);groups.forEach(function(group){var series=group.series.filter(function(series){return!series.disabled});group.renderer.render({series:series,vis:group.vis});series.forEach(function(s){s.stack=s._stack||s.stack||s.data;});});}});Rickshaw.namespace('Rickshaw.Graph.Renderer.LinePlot');Rickshaw.Graph.Renderer.LinePlot=Rickshaw.Class.create(Rickshaw.Graph.Renderer,{name:'lineplot',defaults:function($super){return Rickshaw.extend($super(),{unstack:true,fill:false,stroke:true,padding:{top:0.01,right:0.01,bottom:0.01,left:0.01},dotSize:3,strokeWidth:2});},initialize:function($super,args){$super(args);},seriesPathFactory:function(){var graph=this.graph;var factory=d3.svg.line().x(function(d){return graph.x(d.x)}).y(function(d){return graph.y(d.y)}).interpolate(this.graph.interpolation).tension(this.tension);factory.defined&&factory.defined(function(d){return d.y!==null});return factory;},_renderDots:function(){var graph=this.graph;graph.series.forEach(function(series){if(series.disabled)return;var nodes=graph.vis.selectAll("x").data(series.stack.filter(function(d){return d.y!==null})).enter().append("svg:circle").attr("cx",function(d){return graph.x(d.x)}).attr("cy",function(d){return graph.y(d.y)}).attr("r",function(d){return("r"in d)?d.r:graph.renderer.dotSize});Array.prototype.forEach.call(nodes[0],function(n){if(!n)return;n.setAttribute('data-color',series.color);n.setAttribute('fill','white');n.setAttribute('stroke',series.color);n.setAttribute('stroke-width',this.strokeWidth);}.bind(this));},this);},_renderLines:function(){var graph=this.graph;var nodes=graph.vis.selectAll("path").data(this.graph.stackedData).enter().append("svg:path").attr("d",this.seriesPathFactory());var i=0;graph.series.forEach(function(series){if(series.disabled)return;series.path=nodes[0][i++];this._styleSeries(series);},this);},render:function(){var graph=this.graph;graph.vis.selectAll('*').remove();this._renderLines();this._renderDots();}});Rickshaw.namespace('Rickshaw.Graph.Smoother');Rickshaw.Graph.Smoother=Rickshaw.Class.create({initialize:function(args){this.graph=args.graph;this.element=args.element;this.aggregationScale=1;this.build();this.graph.stackData.hooks.data.push({name:'smoother',orderPosition:50,f:this.transformer.bind(this)});},build:function(){var self=this;if(this.element){$(function(){$(self.element).slider({min:1,max:100,slide:function(event,ui){self.setScale(ui.value);self.graph.update();}});});}},setScale:function(scale){if(scale<1){throw"scale out of range: "+scale;}
this.aggregationScale=scale;this.graph.update();},transformer:function(data){if(this.aggregationScale==1)return data;var aggregatedData=[];data.forEach(function(seriesData){var aggregatedSeriesData=[];while(seriesData.length){var avgX=0,avgY=0;var slice=seriesData.splice(0,this.aggregationScale);slice.forEach(function(d){avgX+=d.x/slice.length;avgY+=d.y/slice.length;});aggregatedSeriesData.push({x:avgX,y:avgY});}
aggregatedData.push(aggregatedSeriesData);}.bind(this));return aggregatedData;}});Rickshaw.namespace('Rickshaw.Graph.Unstacker');Rickshaw.Graph.Unstacker=function(args){this.graph=args.graph;var self=this;this.graph.stackData.hooks.after.push({name:'unstacker',f:function(data){if(!self.graph.renderer.unstack)return data;data.forEach(function(seriesData){seriesData.forEach(function(d){d.y0=0;});});return data;}});};Rickshaw.namespace('Rickshaw.Series');Rickshaw.Series=Rickshaw.Class.create(Array,{initialize:function(data,palette,options){options=options||{};this.palette=new Rickshaw.Color.Palette(palette);this.timeBase=typeof(options.timeBase)==='undefined'?Math.floor(new Date().getTime()/1000):options.timeBase;var timeInterval=typeof(options.timeInterval)=='undefined'?1000:options.timeInterval;this.setTimeInterval(timeInterval);if(data&&(typeof(data)=="object")&&Array.isArray(data)){data.forEach(function(item){this.addItem(item)},this);}},addItem:function(item){if(typeof(item.name)==='undefined'){throw('addItem() needs a name');}
item.color=(item.color||this.palette.color(item.name));item.data=(item.data||[]);if((item.data.length===0)&&this.length&&(this.getIndex()>0)){this[0].data.forEach(function(plot){item.data.push({x:plot.x,y:0});});}else if(item.data.length===0){item.data.push({x:this.timeBase-(this.timeInterval||0),y:0});}
this.push(item);if(this.legend){this.legend.addLine(this.itemByName(item.name));}},addData:function(data,x){var index=this.getIndex();Rickshaw.keys(data).forEach(function(name){if(!this.itemByName(name)){this.addItem({name:name});}},this);this.forEach(function(item){item.data.push({x:x||(index*this.timeInterval||1)+this.timeBase,y:(data[item.name]||0)});},this);},getIndex:function(){return(this[0]&&this[0].data&&this[0].data.length)?this[0].data.length:0;},itemByName:function(name){for(var i=0;i<this.length;i++){if(this[i].name==name)
return this[i];}},setTimeInterval:function(iv){this.timeInterval=iv/1000;},setTimeBase:function(t){this.timeBase=t;},dump:function(){var data={timeBase:this.timeBase,timeInterval:this.timeInterval,items:[]};this.forEach(function(item){var newItem={color:item.color,name:item.name,data:[]};item.data.forEach(function(plot){newItem.data.push({x:plot.x,y:plot.y});});data.items.push(newItem);});return data;},load:function(data){if(data.timeInterval){this.timeInterval=data.timeInterval;}
if(data.timeBase){this.timeBase=data.timeBase;}
if(data.items){data.items.forEach(function(item){this.push(item);if(this.legend){this.legend.addLine(this.itemByName(item.name));}},this);}}});Rickshaw.Series.zeroFill=function(series){Rickshaw.Series.fill(series,0);};Rickshaw.Series.fill=function(series,fill){var x;var i=0;var data=series.map(function(s){return s.data});while(i<Math.max.apply(null,data.map(function(d){return d.length}))){x=Math.min.apply(null,data.filter(function(d){return d[i]}).map(function(d){return d[i].x}));data.forEach(function(d){if(!d[i]||d[i].x!=x){d.splice(i,0,{x:x,y:fill});}});i++;}};Rickshaw.namespace('Rickshaw.Series.FixedDuration');Rickshaw.Series.FixedDuration=Rickshaw.Class.create(Rickshaw.Series,{initialize:function(data,palette,options){options=options||{};if(typeof(options.timeInterval)==='undefined'){throw new Error('FixedDuration series requires timeInterval');}
if(typeof(options.maxDataPoints)==='undefined'){throw new Error('FixedDuration series requires maxDataPoints');}
this.palette=new Rickshaw.Color.Palette(palette);this.timeBase=typeof(options.timeBase)==='undefined'?Math.floor(new Date().getTime()/1000):options.timeBase;this.setTimeInterval(options.timeInterval);if(this[0]&&this[0].data&&this[0].data.length){this.currentSize=this[0].data.length;this.currentIndex=this[0].data.length;}else{this.currentSize=0;this.currentIndex=0;}
this.maxDataPoints=options.maxDataPoints;if(data&&(typeof(data)=="object")&&Array.isArray(data)){data.forEach(function(item){this.addItem(item)},this);this.currentSize+=1;this.currentIndex+=1;}
this.timeBase-=(this.maxDataPoints-this.currentSize)*this.timeInterval;if((typeof(this.maxDataPoints)!=='undefined')&&(this.currentSize<this.maxDataPoints)){for(var i=this.maxDataPoints-this.currentSize-1;i>1;i--){this.currentSize+=1;this.currentIndex+=1;this.forEach(function(item){item.data.unshift({x:((i-1)*this.timeInterval||1)+this.timeBase,y:0,i:i});},this);}}},addData:function($super,data,x){$super(data,x);this.currentSize+=1;this.currentIndex+=1;if(this.maxDataPoints!==undefined){while(this.currentSize>this.maxDataPoints){this.dropData();}}},dropData:function(){this.forEach(function(item){item.data.splice(0,1);});this.currentSize-=1;},getIndex:function(){return this.currentIndex;}});Rickshaw.namespace('Rickshaw.Graph.Renderer.StaticAxes');Rickshaw.Graph.Renderer.StaticAxes=Rickshaw.Class.create(Rickshaw.Graph.Renderer.Line,{name:'StaticAxes',defaults:function($super){return Rickshaw.extend($super(),{xMin:undefined,xMax:undefined,yMin:undefined,yMax:undefined,});},domain:function($super){var ret=$super();if(this.yMin!==undefined&&this.yMax!==undefined){ret.y=[this.yMin,this.yMax];}
return ret;},});horizon.d3_line_chart={LineChart:function(chart_module,html_element,settings){var self=this;var jquery_element=$(html_element);self.chart_module=chart_module;self.html_element=html_element;self.jquery_element=jquery_element;self.init=function(){var self=this;self.legend_element=$(jquery_element.data('legend-selector')).get(0);self.slider_element=$(jquery_element.data('slider-selector')).get(0);self.url=jquery_element.data('url');self.url_parameters=jquery_element.data('url_parameters');self.final_url=self.url;if(jquery_element.data('form-selector')){$(jquery_element.data('form-selector')).each(function(){if(self.final_url.indexOf('?')>-1){self.final_url+='&'+$(this).serialize();}else{self.final_url+='?'+$(this).serialize();}});}
self.data=[];self.color=d3.scale.category10();self.stats={};self.stats.average=0;self.stats.last_value=0;self.init_settings(settings);self.get_size();};self.init_settings=function(settings){var self=this;self.settings={};self.settings.renderer='line';self.settings.auto_size=true;self.settings.axes_x=true;self.settings.axes_y=true;self.settings.interpolation='linear';self.settings.yMin=undefined;self.settings.yMax=undefined;self.settings.higlight_last_point=false;self.settings.composed_chart_selector='.overview_chart';self.settings.bar_chart_selector='div[data-chart-type="overview_bar_chart"]';self.settings.bar_chart_settings=undefined;self.hover_formatter='verbose';if(settings){self.apply_settings(settings);}
if(self.jquery_element.data('settings')){var inline_settings=self.jquery_element.data('settings');self.apply_settings(inline_settings);}};self.apply_settings=function(settings){var self=this;var allowed_settings=['renderer','auto_size','axes_x','axes_y','interpolation','yMin','yMax','bar_chart_settings','bar_chart_selector','composed_chart_selector','higlight_last_point'];jQuery.each(allowed_settings,function(index,setting_name){if(settings[setting_name]!==undefined){self.settings[setting_name]=settings[setting_name];}});};self.get_size=function(){$(self.html_element).css('height','');$(self.html_element).css('width','');var svg=$(self.html_element).find('svg');svg.hide();self.width=jquery_element.width();self.height=jquery_element.height();if(self.settings.auto_size){var auto_height=$(window).height()-jquery_element.offset().top-30;if(auto_height>self.height){self.height=auto_height;}}
$(self.html_element).css('height',self.height);$(self.html_element).css('width',self.width);svg.show();svg.css('height',self.height);svg.css('width',self.width);};self.init();self.refresh=function(){var self=this;self.start_loading();horizon.ajax.queue({url:self.final_url,success:function(data,textStatus,jqXHR){$(self.html_element).html('');$(self.legend_element).html('');self.series=data.series;self.stats=data.stats;self.apply_settings(data.settings);if(self.series.length<=0){$(self.html_element).html(gettext('No data available.'));$(self.legend_element).html('');$(self.legend_element).css('height','');}else{self.render();}},error:function(jqXHR,textStatus,errorThrown){$(self.html_element).html(gettext('No data available.'));$(self.legend_element).html('');$(self.legend_element).css('height','');horizon.alert('error',gettext('An error occurred. Please try again later.'));},complete:function(jqXHR,textStatus){self.finish_loading();}});};self.render=function(){var self=this;var last_point=undefined,last_point_color=undefined;$.map(self.series,function(serie){serie.color=last_point_color=self.color(serie.name);$.map(serie.data,function(statistic){statistic.x=d3.time.format('%Y-%m-%dT%H:%M:%S').parse(statistic.x);statistic.x=statistic.x.getTime()/1000;last_point=statistic;last_point.color=serie.color;});});var renderer=self.settings.renderer;if(renderer==='StaticAxes'){renderer=Rickshaw.Graph.Renderer.StaticAxes;}
var graph=new Rickshaw.Graph({element:self.html_element,width:self.width,height:self.height,renderer:renderer,series:self.series,yMin:self.settings.yMin,yMax:self.settings.yMax,interpolation:self.settings.interpolation,});graph.render();if(self.hover_formatter==='verbose'){var hoverDetail=new Rickshaw.Graph.HoverDetail({graph:graph,formatter:function(series,x,y){var date='<span class="date">'+new Date(x*1000).toUTCString()+'</span>';var swatch='<span class="detail_swatch" style="background-color: '+series.color+'"></span>';var content=swatch+series.name+': '+parseFloat(y).toFixed(2)+' '+series.unit+'<br>'+date;return content;}});}
if(self.legend_element){var legend=new Rickshaw.Graph.Legend({graph:graph,element:self.legend_element});var shelving=new Rickshaw.Graph.Behavior.Series.Toggle({graph:graph,legend:legend});var order=new Rickshaw.Graph.Behavior.Series.Order({graph:graph,legend:legend});var highlighter=new Rickshaw.Graph.Behavior.Series.Highlight({graph:graph,legend:legend});}
if(self.settings.axes_x){var axes_x=new Rickshaw.Graph.Axis.Time({graph:graph});axes_x.render();}
if(self.settings.axes_y){var axes_y=new Rickshaw.Graph.Axis.Y({graph:graph});axes_y.render();}
$(self.legend_element).css('height','');if(self.stats!==undefined){var composed_chart=self.jquery_element.parents(self.settings.composed_chart_selector).first();var bar_chart_html=composed_chart.find(self.settings.bar_chart_selector).get(0);horizon.d3_bar_chart.refresh(bar_chart_html,self.settings.bar_chart_settings,self.stats);}
if(self.settings.higlight_last_point){if(last_point!==undefined&&last_point_color!==undefined){graph.vis.append('circle').attr('class','used_component').attr('cy',graph.y(last_point.y)).attr('cx',graph.x(last_point.x)).attr('r',2).style('fill',last_point_color).style('stroke',last_point_color).style('stroke-width',2);}}};self.start_loading=function(){var self=this;$(self.html_element).find('.modal-backdrop').remove();$(self.html_element).find('.spinner_wrapper').remove();self.backdrop=$('<div class="modal-backdrop"></div>');self.backdrop.css('width',self.width).css('height',self.height);$(self.html_element).append(self.backdrop);$(self.legend_element).html('').addClass('disabled');self.spinner=$('<div class="spinner_wrapper"></div>');$(self.html_element).append(self.spinner);self.spinner.spin(horizon.conf.spinner_options.line_chart);var radius=horizon.conf.spinner_options.line_chart.radius;var length=horizon.conf.spinner_options.line_chart.length;var spinner_size=radius+length;var top=(self.height/2)-spinner_size/2;var left=(self.width/2)-spinner_size/2;self.spinner.css('top',top).css('left',left);};self.finish_loading=function(){var self=this;$(self.legend_element).removeClass('disabled');};},init:function(selector,settings){var self=this;$(selector).each(function(){self.refresh(this,settings);});if(settings!==undefined&&settings.auto_resize){var rtime=new Date(1,1,2000,12,0,0);var timeout=false;var delta=400;$(window).resize(function(){rtime=new Date();if(timeout===false){timeout=true;setTimeout(resizeend,delta);}});var resizeend=function(){if(new Date()-rtime<delta){setTimeout(resizeend,delta);}else{timeout=false;$(selector).each(function(){self.refresh(this,settings);});}};}
self.bind_commands(selector,settings);},refresh:function(html_element,settings){var chart=new this.LineChart(this,html_element,settings);chart.refresh();},bind_commands:function(selector,settings){var select_box_selector='select[data-line-chart-command="select_box_change"]';var datepicker_selector='input[data-line-chart-command="date_picker_change"]';var self=this;connect_forms_to_charts=function(){$(selector).each(function(){var chart=$(this);$(chart.data('form-selector')).each(function(){var form=$(this);var chart_identifier='div[data-form-selector="'+chart.data('form-selector')+'"]';if(!form.data('charts_selector')){form.data('charts_selector',chart_identifier);}else{form.data('charts_selector',form.data('charts_selector')+', '+chart_identifier);}});});};delegate_event_and_refresh_charts=function(selector,event_name,settings){$('form').delegate(selector,event_name,function(){var invoker=$(this);var form=invoker.parents('form').first();$(form.data('charts_selector')).each(function(){self.refresh(this,settings);});});};bind_select_box_change=function(settings){delegate_event_and_refresh_charts(select_box_selector,'change',settings);};bind_datepicker_change=function(settings){var now=new Date();$(datepicker_selector).each(function(){var el=$(this);el.datepicker({format:'yyyy-mm-dd',setDate:new Date(),showButtonPanel:true});});delegate_event_and_refresh_charts(datepicker_selector,'changeDate',settings);};connect_forms_to_charts();bind_select_box_change(settings);bind_datepicker_change(settings);}};horizon.addInitFunction(function(){horizon.d3_line_chart.init('div[data-chart-type="line_chart"]',{'auto_resize':true});});horizon.d3_bar_chart={BarChart:function(chart_module,html_element,settings,data){var self=this;self.chart_module=chart_module;self.html_element=html_element;self.jquery_element=$(self.html_element);self.init=function(settings,data){var self=this;self.data={};self.data.max_value=self.jquery_element.data('max-value');if(!self.max_value){self.max_value=100;}
self.data.used=self.jquery_element.data('used');self.data.average=self.jquery_element.data('average');self.data.tooltip_average=self.jquery_element.data('tooltip-average');self.data.tooltip_free=self.jquery_element.data('tooltip-free');self.data.tooltip_used=self.jquery_element.data('tooltip-used');if(data!==undefined){if(data.used!==undefined){self.data.used=data.used;}
if(data.average!==undefined){self.data.average=data.average;}
if(data.tooltip_average!==undefined){self.data.tooltip_average=data.tooltip_average;}
if(data.tooltip_free!==undefined){self.data.tooltip_free=data.tooltip_free;}
if(data.tooltip_used!==undefined){self.data.tooltip_used=data.tooltip_used;}}
if($.isArray(self.data.used)){self.data.percentage_average=0;self.data.percentage_used=Array();self.data.tooltip_used_contents=Array();for(var i=0;i<self.data.used.length;++i){if(!isNaN(self.max_value)&&!isNaN(self.data.used[i].used_instances)){var used=Math.round((self.data.used[i].used_instances/self.max_value)*100);self.data.percentage_used.push(used);self.data.tooltip_used_contents.push(self.data.used[i].tooltip_used);}else{}}}
else{if(!isNaN(self.max_value)&&!isNaN(self.data.used)){self.data.percentage_used=Math.round((self.data.used/self.max_value)*100);}else{self.data.percentage_used=0;}
if(!isNaN(self.max_value)&&!isNaN(self.data.average)){self.data.percentage_average=((self.data.average/self.max_value)*100);}else{self.data.percentage_average=0;}}
self.init_settings(settings);};self.init_settings=function(settings){var self=this;self.data.settings={};self.data.settings.used_label_placement=undefined;self.data.settings.orientation='horizontal';self.data.settings.color_scale_domain=[0,100];self.data.settings.color_scale_range=['#000000','#0000FF'];self.data.settings.width=self.jquery_element.data('width');self.data.settings.height=self.jquery_element.data('height');if(settings){self.apply_settings(settings);}
if(self.jquery_element.data('settings')){var inline_settings=self.jquery_element.data('settings');self.apply_settings(inline_settings);}};self.apply_settings=function(settings){var self=this;var allowed_settings=['orientation','used_label_placement','color_scale_domain','color_scale_range','width','height'];$.each(allowed_settings,function(index,setting_name){if(settings[setting_name]!==undefined){self.data.settings[setting_name]=settings[setting_name];}});};self.init(settings,data);self.refresh=function(){var self=this;self.render();};self.render=function(){var self=this;var wrapper=new self.chart_module.Wrapper(self.chart_module,self.html_element,self.data);var tooltip_average=(new self.chart_module.TooltipComponent(wrapper)).render(self.data.tooltip_average);var tooltip_free=(new self.chart_module.TooltipComponent(wrapper)).render(self.data.tooltip_free);var tooltip_used=(new self.chart_module.TooltipComponent(wrapper)).render(self.data.tooltip_used);(new self.chart_module.UnusedComponent(wrapper)).render(tooltip_free);if(wrapper.used_multi()){for(var i=0;i<wrapper.percentage_used.length;++i){wrapper.used_multi_iterator=i;tooltip_used=(new self.chart_module.TooltipComponent(wrapper)).render('');(new self.chart_module.UsedComponent(wrapper)).render(tooltip_used);wrapper.total_used_perc+=wrapper.percentage_used_value();wrapper.total_used_value_in_pixels=(wrapper.w/100)*wrapper.total_used_perc;}}else{(new self.chart_module.UsedComponent(wrapper)).render(tooltip_used);(new self.chart_module.AverageComponent(wrapper)).render(tooltip_average);}};},Wrapper:function(chart_module,html_element,data){var self=this;self.html_element=html_element;self.jquery_element=$(html_element);self.bar_html=d3.select(html_element);self.bar=self.bar_html.append('svg:svg').attr('class','chart').style('background-color','white');chart_module.get_size(self.html_element);self.data=data;self.used_label_placement=data.settings.used_label_placement;if(data.settings.width!==undefined){self.w=parseFloat(data.settings.width);}else{self.w=parseFloat(self.jquery_element.width());}
if(data.settings.height!==undefined){self.h=parseFloat(data.settings.height);}else{self.h=parseFloat(self.jquery_element.height());}
self.chart_start_x=0;if(self.data.settings.orientation==='vertical'){if(self.used_label_placement==='left'){self.chart_start_x=44;}
self.chart_wrapper_w=self.w+self.chart_start_x;}else{self.chart_wrapper_w=self.w;}
self.chart_wrapper_h=self.h;self.lvl_curve=3;self.bkgrnd='#F2F2F2';self.frgrnd='grey';self.color_scale_max=25;self.percentage_used=data.percentage_used;self.total_used_perc=0;self.total_used_value_in_pixels=0;self.used_value_in_pixels=0;self.average_value_in_pixels=0;self.percentage_average=data.percentage_average;self.tooltip_used_contents=data.tooltip_used_contents;self.usage_color=d3.scale.linear().domain(data.settings.color_scale_domain).range(data.settings.color_scale_range);self.border_width=1;self.used_multi=function(){return($.isArray(self.percentage_used));};self.used_multi_iterator=0;self.percentage_used_value=function(){if(self.used_multi()){return self.percentage_used[self.used_multi_iterator];}else{return self.percentage_used;}};self.tooltip_used_value=function(){if(self.used_multi()){return self.tooltip_used_contents[self.used_multi_iterator];}else{return'';}};self.horizontal_orientation=function(){return(self.data.settings.orientation==='horizontal');};},UsedComponent:function(wrapper){var self=this;self.wrapper=wrapper;if(self.wrapper.horizontal_orientation()){self.wrapper.used_value_in_pixels=(self.wrapper.w/100)*self.wrapper.percentage_used_value();self.y=0;self.x=self.wrapper.total_used_value_in_pixels;self.width=0;self.height=self.wrapper.h;self.trasition_attr='width';self.trasition_value=self.wrapper.used_value_in_pixels;}else{self.wrapper.used_value_in_pixels=(self.wrapper.h/100)*self.wrapper.percentage_used_value();self.y=self.wrapper.h;self.x=self.wrapper.chart_start_x;self.width=self.wrapper.w-self.wrapper.border_width;self.height=self.wrapper.used_value_in_pixels;self.trasition_attr='y';self.trasition_value=self.wrapper.h-self.wrapper.used_value_in_pixels;}
self.render=function(tooltip){self.wrapper.bar.append('rect').attr('class','used_component').attr('y',self.y).attr('x',self.x).attr('width',self.width).attr('height',self.height).style('fill',self.wrapper.usage_color(self.wrapper.percentage_used_value())).style('stroke','#bebebe').style('stroke-width',0).attr('d',self.wrapper.percentage_used_value()).attr('tooltip-used',self.wrapper.tooltip_used_value()).on('mouseover',function(d){if($(this).attr('tooltip-used')){tooltip.html($(this).attr('tooltip-used'));}
tooltip.style('visibility','visible');}).on('mousemove',function(d){tooltip.style('top',(event.pageY-10)+'px').style('left',(event.pageX+10)+'px');}).on('mouseout',function(d){tooltip.style('visibility','hidden');}).transition().duration(500).attr(self.trasition_attr,self.trasition_value);if(self.wrapper.used_label_placement==='left'){var label_placement_y=self.wrapper.h-self.wrapper.used_value_in_pixels;if(label_placement_y<=6){label_placement_y=6;}else if(label_placement_y>=(self.wrapper.h-6)){label_placement_y=self.wrapper.h-6;}
self.wrapper.bar.append('text').attr('class','used_component_label').text(self.wrapper.percentage_used_value()+'%').attr('y',label_placement_y).attr('x',0).attr('dominant-baseline','middle').attr('font-size',12).transition().duration(500).attr('x',function(){if(self.wrapper.percentage_used_value()>99){return 0;}
else if(self.wrapper.percentage_used_value()>9){return 4;}
else{return 8;}});var poly=[{'x':self.wrapper.chart_start_x-8,'y':label_placement_y},{'x':self.wrapper.chart_start_x-3,'y':label_placement_y+2},{'x':self.wrapper.chart_start_x-3,'y':label_placement_y-2},];self.wrapper.bar.selectAll('polygon').data([poly]).enter().append('polygon').attr('points',function(d){return d.map(function(d){return[d.x,d.y].join(',');}).join(' ');}).attr('stroke','black').attr('stroke-width',2);}};},AverageComponent:function(wrapper){var self=this;self.wrapper=wrapper;if(wrapper.horizontal_orientation()){self.wrapper.average_value_in_pixels=(self.wrapper.w/100)*self.wrapper.percentage_average;self.y=1;self.x=self.wrapper.average_value_in_pixels;self.width=0;self.height=self.wrapper.h;}else{self.wrapper.average_value_in_pixels=(self.wrapper.h/100)*(100-self.wrapper.percentage_average);self.y=self.wrapper.average_value_in_pixels;self.x=self.wrapper.chart_start_x;self.width=self.wrapper.w-self.wrapper.border_width;self.height=0;}
self.render=function(tooltip){if(self.wrapper.percentage_average>0){self.wrapper.bar.append('line').attr('class','average_component').attr('y1',self.y).attr('x1',self.x).attr('class','average').attr('y2',self.y+self.height).attr('x2',self.x+self.width).style('stroke','black').style('stroke-width',3).style('stroke-dasharray',('6, 2')).on('mouseover',function(){tooltip.style('visibility','visible');}).on('mousemove',function(){tooltip.style('top',(event.pageY-10)+'px').style('left',(event.pageX+10)+'px');}).on('mouseout',function(){tooltip.style('visibility','hidden');});self.wrapper.bar.append('line').attr('class','average_component').attr('y1',self.y).attr('x1',self.x).attr('class','average').attr('y2',self.y+self.height).attr('x2',self.x+self.width).style('stroke','transparent').style('stroke-width',5).on('mouseover',function(){tooltip.style('visibility','visible');}).on('mousemove',function(){tooltip.style('top',(event.pageY-10)+'px').style('left',(event.pageX+10)+'px');}).on('mouseout',function(){tooltip.style('visibility','hidden');});}};},UnusedComponent:function(wrapper){var self=this;self.wrapper=wrapper;self.render=function(tooltip_free){self.wrapper.bar.append('rect').attr('class','unused_component').attr('y',0).attr('x',self.wrapper.chart_start_x).attr('width',self.wrapper.w).attr('height',self.wrapper.h).attr('rx',self.wrapper.lvl_curve).attr('ry',self.wrapper.lvl_curve).style('fill',self.wrapper.bkgrnd).on('mouseover',function(d){tooltip_free.style('visibility','visible');}).on('mousemove',function(d){tooltip_free.style('top',(event.pageY-10)+'px').style('left',(event.pageX+10)+'px');}).on('mouseout',function(d){tooltip_free.style('visibility','hidden');});self.wrapper.bar.append('rect').attr('class','unused_component_border').attr('x',self.wrapper.chart_start_x).attr('y',0).attr('height',self.wrapper.h).attr('width',self.wrapper.w-self.wrapper.border_width).style('stroke','#bebebe').style('fill','none').style('stroke-width',1);};},TooltipComponent:function(wrapper){var self=this;self.wrapper=wrapper;self.tooltip_html=self.wrapper.bar_html.append('div');self.render=function(html_content){var display='none';if(html_content){display='block';}
return self.tooltip_html.attr('class','tooltip_detail').style('position','absolute').style('z-index','10').style('visibility','hidden').style('display',display).html(html_content);};},init:function(selector,settings,data){var self=this;self.bars=$(selector);self.bars.each(function(){self.refresh(this,settings,data);});},refresh:function(html_element,settings,data){var chart=new this.BarChart(this,html_element,settings,data);chart.refresh();},get_size:function(html_element){var jquery_element=$(html_element);jquery_element.css('height','');jquery_element.css('width','');var svg=jquery_element.find('svg');svg.hide();var width=jquery_element.width();var height=jquery_element.height();jquery_element.css('height',height);jquery_element.css('width',width);svg.show();svg.css('height',height);svg.css('width',width);},};horizon.addInitFunction(function(){horizon.d3_bar_chart.init('div[data-chart-type="bar_chart"]',{},{});});horizon.firewalls={user_decided_length:false,rules_selected:[],rules_available:[],getConsoleLog:function(via_user_submit){var form_element=$("#tail_length"),data;if(!via_user_submit){via_user_submit=false;}
if(this.user_decided_length){data=$(form_element).serialize();}else{data="length=35";}
$.ajax({url:$(form_element).attr('action'),data:data,method:'get',success:function(response_body){$('pre.logs').text(response_body);},error:function(response){if(via_user_submit){horizon.clearErrorMessages();horizon.alert('error',gettext('There was a problem communicating with the server, please try again.'));}}});},get_rule_element:function(rule_id){return $('li > label[for^="id_rule_'+rule_id+'"]');},init_rule_list:function(){horizon.firewalls.rules_selected=[];horizon.firewalls.rules_available=[];$(this.get_rule_element("")).each(function(){var $this=$(this);var $input=$this.children("input");var rule_property={name:$this.text().replace(/^\s+/,""),id:$input.attr("id"),value:$input.attr("value")};if($input.is(':checked')){horizon.firewalls.rules_selected.push(rule_property);}else{horizon.firewalls.rules_available.push(rule_property);}});},generate_rule_element:function(name,id,value){var $li=$('<li>');$li.attr('name',value).html(name+'<em class="rule_id">('+value+')</em><a href="#" class="btn btn-primary"></a>');return $li;},generate_rulelist_html:function(){var self=this;var updateForm=function(){var lists=$("#ruleListId div.input li").attr('data-index',100);var active_rules=$("#selected_rule > li").map(function(){return $(this).attr("name");});$("#ruleListId div.input input:checkbox").removeAttr('checked');active_rules.each(function(index,value){$("#ruleListId div.input input:checkbox[value="+value+"]").attr('checked','checked').parents("li").attr('data-index',index);});$("#ruleListId div.input ul").html(lists.sort(function(a,b){if($(a).data("index")<$(b).data("index")){return-1;}
if($(a).data("index")>$(b).data("index")){return 1;}
return 0;}));};$("#ruleListSortContainer").show();$("#ruleListIdContainer").hide();self.init_rule_list();$("#available_rule").empty();$.each(self.rules_available,function(index,value){$("#available_rule").append(self.generate_rule_element(value.name,value.id,value.value));});$("#selected_rule").empty();$.each(self.rules_selected,function(index,value){$("#selected_rule").append(self.generate_rule_element(value.name,value.id,value.value));});$(".rulelist > li > a.btn").click(function(e){var $this=$(this);e.preventDefault();e.stopPropagation();if($this.parents("ul#available_rule").length>0){$this.parent().appendTo($("#selected_rule"));}else if($this.parents("ul#selected_rule").length>0){$this.parent().appendTo($("#available_rule"));}
updateForm();});if($("#ruleListId > div.control-group.error").length>0){var errortext=$("#ruleListId > div.control-group.error").find("span.help-inline").text();$("#selected_rule_h4").before($('<div class="dynamic-error">').html(errortext));}
$(".rulelist").sortable({connectWith:"ul.rulelist",placeholder:"ui-state-highlight",distance:5,start:function(e,info){$("#selected_rule").addClass("dragging");},stop:function(e,info){$("#selected_rule").removeClass("dragging");updateForm();}}).disableSelection();},workflow_init:function(modal){horizon.firewalls.generate_rulelist_html();}};horizon.addInitFunction(function(){$(document).on('submit','#tail_length',function(evt){horizon.firewalls.user_decided_length=true;horizon.firewalls.getConsoleLog(true);evt.preventDefault();});});var JSEncryptExports={};(function(exports){var dbits;var canary=0xdeadbeefcafe;var j_lm=((canary&0xffffff)==0xefcafe);function BigInteger(a,b,c){if(a!=null)if("number"==typeof a)this.fromNumber(a,b,c);else if(b==null&&"string"!=typeof a)this.fromString(a,256);else this.fromString(a,b);}
function nbi(){return new BigInteger(null);}
function am1(i,x,w,j,c,n){while(--n>=0){var v=x*this[i++]+w[j]+c;c=Math.floor(v/0x4000000);w[j++]=v&0x3ffffff;}
return c;}
function am2(i,x,w,j,c,n){var xl=x&0x7fff,xh=x>>15;while(--n>=0){var l=this[i]&0x7fff;var h=this[i++]>>15;var m=xh*l+h*xl;l=xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);c=(l>>>30)+(m>>>15)+xh*h+(c>>>30);w[j++]=l&0x3fffffff;}
return c;}
function am3(i,x,w,j,c,n){var xl=x&0x3fff,xh=x>>14;while(--n>=0){var l=this[i]&0x3fff;var h=this[i++]>>14;var m=xh*l+h*xl;l=xl*l+((m&0x3fff)<<14)+w[j]+c;c=(l>>28)+(m>>14)+xh*h;w[j++]=l&0xfffffff;}
return c;}
if(j_lm&&(navigator.appName=="Microsoft Internet Explorer")){BigInteger.prototype.am=am2;dbits=30;}else if(j_lm&&(navigator.appName!="Netscape")){BigInteger.prototype.am=am1;dbits=26;}else{BigInteger.prototype.am=am3;dbits=28;}
BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=((1<<dbits)-1);BigInteger.prototype.DV=(1<<dbits);var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";var BI_RC=new Array();var rr,vv;rr="0".charCodeAt(0);for(vv=0;vv<=9;++vv)BI_RC[rr++]=vv;rr="a".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;rr="A".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;function int2char(n){return BI_RM.charAt(n);}
function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return(c==null)?-1:c;}
function bnpCopyTo(r){for(var i=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t;r.s=this.s;}
function bnpFromInt(x){this.t=1;this.s=(x<0)?-1:0;if(x>0)this[0]=x;else if(x<-1)this[0]=x+DV;else this.t=0;}
function nbv(i){var r=nbi();r.fromInt(i);return r;}
function bnpFromString(s,b){var k;if(b==16)k=4;else if(b==8)k=3;else if(b==256)k=8;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2;else{this.fromRadix(s,b);return;}
this.t=0;this.s=0;var i=s.length,mi=false,sh=0;while(--i>=0){var x=(k==8)?s[i]&0xff:intAt(s,i);if(x<0){if(s.charAt(i)=="-")mi=true;continue;}
mi=false;if(sh==0)this[this.t++]=x;else if(sh+k>this.DB){this[this.t-1]|=(x&((1<<(this.DB-sh))-1))<<sh;this[this.t++]=(x>>(this.DB-sh));}else this[this.t-1]|=x<<sh;sh+=k;if(sh>=this.DB)sh-=this.DB;}
if(k==8&&(s[0]&0x80)!=0){this.s=-1;if(sh>0)this[this.t-1]|=((1<<(this.DB-sh))-1)<<sh;}
this.clamp();if(mi)BigInteger.ZERO.subTo(this,this);}
function bnpClamp(){var c=this.s&this.DM;while(this.t>0&&this[this.t-1]==c)--this.t;}
function bnToString(b){if(this.s<0)return"-"+this.negate().toString(b);var k;if(b==16)k=4;else if(b==8)k=3;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2;else return this.toRadix(b);var km=(1<<k)-1,d,m=false,r="",i=this.t;var p=this.DB-(i*this.DB)%k;if(i-->0){if(p<this.DB&&(d=this[i]>>p)>0){m=true;r=int2char(d);}
while(i>=0){if(p<k){d=(this[i]&((1<<p)-1))<<(k-p);d|=this[--i]>>(p+=this.DB-k);}else{d=(this[i]>>(p-=k))&km;if(p<=0){p+=this.DB;--i;}}
if(d>0)m=true;if(m)r+=int2char(d);}}
return m?r:"0";}
function bnNegate(){var r=nbi();BigInteger.ZERO.subTo(this,r);return r;}
function bnAbs(){return(this.s<0)?this.negate():this;}
function bnCompareTo(a){var r=this.s-a.s;if(r!=0)return r;var i=this.t;r=i-a.t;if(r!=0)return(this.s<0)?-r:r;while(--i>=0)if((r=this[i]-a[i])!=0)return r;return 0;}
function nbits(x){var r=1,t;if((t=x>>>16)!=0){x=t;r+=16;}
if((t=x>>8)!=0){x=t;r+=8;}
if((t=x>>4)!=0){x=t;r+=4;}
if((t=x>>2)!=0){x=t;r+=2;}
if((t=x>>1)!=0){x=t;r+=1;}
return r;}
function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));}
function bnpDLShiftTo(n,r){var i;for(i=this.t-1;i>=0;--i)r[i+n]=this[i];for(i=n-1;i>=0;--i)r[i]=0;r.t=this.t+n;r.s=this.s;}
function bnpDRShiftTo(n,r){for(var i=n;i<this.t;++i)r[i-n]=this[i];r.t=Math.max(this.t-n,0);r.s=this.s;}
function bnpLShiftTo(n,r){var bs=n%this.DB;var cbs=this.DB-bs;var bm=(1<<cbs)-1;var ds=Math.floor(n/this.DB),c=(this.s<<bs)&this.DM,i;for(i=this.t-1;i>=0;--i){r[i+ds+1]=(this[i]>>cbs)|c;c=(this[i]&bm)<<bs;}
for(i=ds-1;i>=0;--i)r[i]=0;r[ds]=c;r.t=this.t+ds+1;r.s=this.s;r.clamp();}
function bnpRShiftTo(n,r){r.s=this.s;var ds=Math.floor(n/this.DB);if(ds>=this.t){r.t=0;return;}
var bs=n%this.DB;var cbs=this.DB-bs;var bm=(1<<bs)-1;r[0]=this[ds]>>bs;for(var i=ds+1;i<this.t;++i){r[i-ds-1]|=(this[i]&bm)<<cbs;r[i-ds]=this[i]>>bs;}
if(bs>0)r[this.t-ds-1]|=(this.s&bm)<<cbs;r.t=this.t-ds;r.clamp();}
function bnpSubTo(a,r){var i=0,c=0,m=Math.min(a.t,this.t);while(i<m){c+=this[i]-a[i];r[i++]=c&this.DM;c>>=this.DB;}
if(a.t<this.t){c-=a.s;while(i<this.t){c+=this[i];r[i++]=c&this.DM;c>>=this.DB;}
c+=this.s;}else{c+=this.s;while(i<a.t){c-=a[i];r[i++]=c&this.DM;c>>=this.DB;}
c-=a.s;}
r.s=(c<0)?-1:0;if(c<-1)r[i++]=this.DV+c;else if(c>0)r[i++]=c;r.t=i;r.clamp();}
function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r[i]=0;for(i=0;i<y.t;++i)r[i+x.t]=x.am(0,y[i],r,i,0,x.t);r.s=0;r.clamp();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r);}
function bnpSquareTo(r){var x=this.abs();var i=r.t=2*x.t;while(--i>=0)r[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x[i],r,2*i,0,1);if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1))>=x.DV){r[i+x.t]-=x.DV;r[i+x.t+1]=1;}}
if(r.t>0)r[r.t-1]+=x.am(i,x[i],r,2*i,0,1);r.s=0;r.clamp();}
function bnpDivRemTo(m,q,r){var pm=m.abs();if(pm.t<=0)return;var pt=this.abs();if(pt.t<pm.t){if(q!=null)q.fromInt(0);if(r!=null)this.copyTo(r);return;}
if(r==null)r=nbi();var y=nbi(),ts=this.s,ms=m.s;var nsh=this.DB-nbits(pm[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r);}else{pm.copyTo(y);pt.copyTo(r);}
var ys=y.t;var y0=y[ys-1];if(y0==0)return;var yt=y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);var d1=this.FV/yt,d2=(1<<this.F1)/yt,e=1<<this.F2;var i=r.t,j=i-ys,t=(q==null)?nbi():q;y.dlShiftTo(j,t);if(r.compareTo(t)>=0){r[r.t++]=1;r.subTo(t,r);}
BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t<ys)y[y.t++]=0;while(--j>=0){var qd=(r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);if((r[i]+=y.am(0,qd,r,j,0,ys))<qd){y.dlShiftTo(j,t);r.subTo(t,r);while(r[i]<--qd)r.subTo(t,r);}}
if(q!=null){r.drShiftTo(ys,q);if(ts!=ms)BigInteger.ZERO.subTo(q,q);}
r.t=ys;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r);}
function bnMod(a){var r=nbi();this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);return r;}
function Classic(m){this.m=m;}
function cConvert(x){if(x.s<0||x.compareTo(this.m)>=0)return x.mod(this.m);else return x;}
function cRevert(x){return x;}
function cReduce(x){x.divRemTo(this.m,null,x);}
function cMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}
function cSqrTo(x,r){x.squareTo(r);this.reduce(r);}
Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var x=this[0];if((x&1)==0)return 0;var y=x&3;y=(y*(2-(x&0xf)*y))&0xf;y=(y*(2-(x&0xff)*y))&0xff;y=(y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;y=(y*(2-x*y%this.DV))%this.DV;return(y>0)?this.DV-y:-y;}
function Montgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&0x7fff;this.mph=this.mp>>15;this.um=(1<<(m.DB-15))-1;this.mt2=2*m.t;}
function montConvert(x){var r=nbi();x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);return r;}
function montRevert(x){var r=nbi();x.copyTo(r);this.reduce(r);return r;}
function montReduce(x){while(x.t<=this.mt2)
x[x.t++]=0;for(var i=0;i<this.m.t;++i){var j=x[i]&0x7fff;var u0=(j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;j=i+this.m.t;x[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x[j]>=x.DV){x[j]-=x.DV;x[++j]++;}}
x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x);}
function montSqrTo(x,r){x.squareTo(r);this.reduce(r);}
function montMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}
Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return((this.t>0)?(this[0]&1):this.s)==0;}
function bnpExp(e,z){if(e>0xffffffff||e<1)return BigInteger.ONE;var r=nbi(),r2=nbi(),g=z.convert(this),i=nbits(e)-1;g.copyTo(r);while(--i>=0){z.sqrTo(r,r2);if((e&(1<<i))>0)z.mulTo(r2,g,r);else{var t=r;r=r2;r2=t;}}
return z.revert(r);}
function bnModPowInt(e,m){var z;if(e<256||m.isEven())z=new Classic(m);else z=new Montgomery(m);return this.exp(e,z);}
BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var r=nbi();this.copyTo(r);return r;}
function bnIntValue(){if(this.s<0){if(this.t==1)return this[0]-this.DV;else if(this.t==0)return-1;}else if(this.t==1)return this[0];else if(this.t==0)return 0;return((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];}
function bnByteValue(){return(this.t==0)?this.s:(this[0]<<24)>>24;}
function bnShortValue(){return(this.t==0)?this.s:(this[0]<<16)>>16;}
function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r));}
function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||(this.t==1&&this[0]<=0))return 0;else return 1;}
function bnpToRadix(b){if(b==null)b=10;if(this.signum()==0||b<2||b>36)return"0";var cs=this.chunkSize(b);var a=Math.pow(b,cs);var d=nbv(a),y=nbi(),z=nbi(),r="";this.divRemTo(d,y,z);while(y.signum()>0){r=(a+z.intValue()).toString(b).substr(1)+r;y.divRemTo(d,y,z);}
return z.intValue().toString(b)+r;}
function bnpFromRadix(s,b){this.fromInt(0);if(b==null)b=10;var cs=this.chunkSize(b);var d=Math.pow(b,cs),mi=false,j=0,w=0;for(var i=0;i<s.length;++i){var x=intAt(s,i);if(x<0){if(s.charAt(i)=="-"&&this.signum()==0)mi=true;continue;}
w=b*w+x;if(++j>=cs){this.dMultiply(d);this.dAddOffset(w,0);j=0;w=0;}}
if(j>0){this.dMultiply(Math.pow(b,j));this.dAddOffset(w,0);}
if(mi)BigInteger.ZERO.subTo(this,this);}
function bnpFromNumber(a,b,c){if("number"==typeof b){if(a<2)this.fromInt(1);else{this.fromNumber(a,c);if(!this.testBit(a-1))
this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(b)){this.dAddOffset(2,0);if(this.bitLength()>a)this.subTo(BigInteger.ONE.shiftLeft(a-1),this);}}}else{var x=new Array(),t=a&7;x.length=(a>>3)+1;b.nextBytes(x);if(t>0)x[0]&=((1<<t)-1);else x[0]=0;this.fromString(x,256);}}
function bnToByteArray(){var i=this.t,r=new Array();r[0]=this.s;var p=this.DB-(i*this.DB)%8,d,k=0;if(i-->0){if(p<this.DB&&(d=this[i]>>p)!=(this.s&this.DM)>>p)r[k++]=d|(this.s<<(this.DB-p));while(i>=0){if(p<8){d=(this[i]&((1<<p)-1))<<(8-p);d|=this[--i]>>(p+=this.DB-8);}else{d=(this[i]>>(p-=8))&0xff;if(p<=0){p+=this.DB;--i;}}
if((d&0x80)!=0)d|=-256;if(k==0&&(this.s&0x80)!=(d&0x80))++k;if(k>0||d!=this.s)r[k++]=d;}}
return r;}
function bnEquals(a){return(this.compareTo(a)==0);}
function bnMin(a){return(this.compareTo(a)<0)?this:a;}
function bnMax(a){return(this.compareTo(a)>0)?this:a;}
function bnpBitwiseTo(a,op,r){var i,f,m=Math.min(a.t,this.t);for(i=0;i<m;++i)r[i]=op(this[i],a[i]);if(a.t<this.t){f=a.s&this.DM;for(i=m;i<this.t;++i)r[i]=op(this[i],f);r.t=this.t;}else{f=this.s&this.DM;for(i=m;i<a.t;++i)r[i]=op(f,a[i]);r.t=a.t;}
r.s=op(this.s,a.s);r.clamp();}
function op_and(x,y){return x&y;}
function bnAnd(a){var r=nbi();this.bitwiseTo(a,op_and,r);return r;}
function op_or(x,y){return x|y;}
function bnOr(a){var r=nbi();this.bitwiseTo(a,op_or,r);return r;}
function op_xor(x,y){return x^y;}
function bnXor(a){var r=nbi();this.bitwiseTo(a,op_xor,r);return r;}
function op_andnot(x,y){return x&~y;}
function bnAndNot(a){var r=nbi();this.bitwiseTo(a,op_andnot,r);return r;}
function bnNot(){var r=nbi();for(var i=0;i<this.t;++i)r[i]=this.DM&~this[i];r.t=this.t;r.s=~this.s;return r;}
function bnShiftLeft(n){var r=nbi();if(n<0)this.rShiftTo(-n,r);else this.lShiftTo(n,r);return r;}
function bnShiftRight(n){var r=nbi();if(n<0)this.lShiftTo(-n,r);else this.rShiftTo(n,r);return r;}
function lbit(x){if(x==0)return-1;var r=0;if((x&0xffff)==0){x>>=16;r+=16;}
if((x&0xff)==0){x>>=8;r+=8;}
if((x&0xf)==0){x>>=4;r+=4;}
if((x&3)==0){x>>=2;r+=2;}
if((x&1)==0)++r;return r;}
function bnGetLowestSetBit(){for(var i=0;i<this.t;++i)
if(this[i]!=0)return i*this.DB+lbit(this[i]);if(this.s<0)return this.t*this.DB;return-1;}
function cbit(x){var r=0;while(x!=0){x&=x-1;++r;}
return r;}
function bnBitCount(){var r=0,x=this.s&this.DM;for(var i=0;i<this.t;++i)r+=cbit(this[i]^x);return r;}
function bnTestBit(n){var j=Math.floor(n/this.DB);if(j>=this.t)return(this.s!=0);return((this[j]&(1<<(n%this.DB)))!=0);}
function bnpChangeBit(n,op){var r=BigInteger.ONE.shiftLeft(n);this.bitwiseTo(r,op,r);return r;}
function bnSetBit(n){return this.changeBit(n,op_or);}
function bnClearBit(n){return this.changeBit(n,op_andnot);}
function bnFlipBit(n){return this.changeBit(n,op_xor);}
function bnpAddTo(a,r){var i=0,c=0,m=Math.min(a.t,this.t);while(i<m){c+=this[i]+a[i];r[i++]=c&this.DM;c>>=this.DB;}
if(a.t<this.t){c+=a.s;while(i<this.t){c+=this[i];r[i++]=c&this.DM;c>>=this.DB;}
c+=this.s;}else{c+=this.s;while(i<a.t){c+=a[i];r[i++]=c&this.DM;c>>=this.DB;}
c+=a.s;}
r.s=(c<0)?-1:0;if(c>0)r[i++]=c;else if(c<-1)r[i++]=this.DV+c;r.t=i;r.clamp();}
function bnAdd(a){var r=nbi();this.addTo(a,r);return r;}
function bnSubtract(a){var r=nbi();this.subTo(a,r);return r;}
function bnMultiply(a){var r=nbi();this.multiplyTo(a,r);return r;}
function bnSquare(){var r=nbi();this.squareTo(r);return r;}
function bnDivide(a){var r=nbi();this.divRemTo(a,r,null);return r;}
function bnRemainder(a){var r=nbi();this.divRemTo(a,null,r);return r;}
function bnDivideAndRemainder(a){var q=nbi(),r=nbi();this.divRemTo(a,q,r);return new Array(q,r);}
function bnpDMultiply(n){this[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp();}
function bnpDAddOffset(n,w){if(n==0)return;while(this.t<=w)this[this.t++]=0;this[w]+=n;while(this[w]>=this.DV){this[w]-=this.DV;if(++w>=this.t)this[this.t++]=0;++this[w];}}
function NullExp(){}
function nNop(x){return x;}
function nMulTo(x,y,r){x.multiplyTo(y,r);}
function nSqrTo(x,r){x.squareTo(r);}
NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp());}
function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r[--i]=0;var j;for(j=r.t-this.t;i<j;++i)r[i+this.t]=this.am(0,a[i],r,i,0,this.t);for(j=Math.min(a.t,n);i<j;++i)this.am(0,a[i],r,i,0,n-i);r.clamp();}
function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;r.s=0;while(--i>=0)r[i]=0;for(i=Math.max(n-this.t,0);i<a.t;++i)
r[this.t+i-n]=this.am(n-i,a[i],r,0,0,this.t+i-n);r.clamp();r.drShiftTo(1,r);}
function Barrett(m){this.r2=nbi();this.q3=nbi();BigInteger.ONE.dlShiftTo(2*m.t,this.r2);this.mu=this.r2.divide(m);this.m=m;}
function barrettConvert(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);else if(x.compareTo(this.m)<0)return x;else{var r=nbi();x.copyTo(r);this.reduce(r);return r;}}
function barrettRevert(x){return x;}
function barrettReduce(x){x.drShiftTo(this.m.t-1,this.r2);if(x.t>this.m.t+1){x.t=this.m.t+1;x.clamp();}
this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(x.compareTo(this.r2)<0)x.dAddOffset(1,this.m.t+1);x.subTo(this.r2,x);while(x.compareTo(this.m)>=0)x.subTo(this.m,x);}
function barrettSqrTo(x,r){x.squareTo(r);this.reduce(r);}
function barrettMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}
Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,m){var i=e.bitLength(),k,r=nbv(1),z;if(i<=0)return r;else if(i<18)k=1;else if(i<48)k=3;else if(i<144)k=4;else if(i<768)k=5;else k=6;if(i<8)z=new Classic(m);else if(m.isEven())z=new Barrett(m);else z=new Montgomery(m);var g=new Array(),n=3,k1=k-1,km=(1<<k)-1;g[1]=z.convert(this);if(k>1){var g2=nbi();z.sqrTo(g[1],g2);while(n<=km){g[n]=nbi();z.mulTo(g2,g[n-2],g[n]);n+=2;}}
var j=e.t-1,w,is1=true,r2=nbi(),t;i=nbits(e[j])-1;while(j>=0){if(i>=k1)w=(e[j]>>(i-k1))&km;else{w=(e[j]&((1<<(i+1))-1))<<(k1-i);if(j>0)w|=e[j-1]>>(this.DB+i-k1);}
n=k;while((w&1)==0){w>>=1;--n;}
if((i-=n)<0){i+=this.DB;--j;}
if(is1){g[w].copyTo(r);is1=false;}else{while(n>1){z.sqrTo(r,r2);z.sqrTo(r2,r);n-=2;}
if(n>0)z.sqrTo(r,r2);else{t=r;r=r2;r2=t;}
z.mulTo(r2,g[w],r);}
while(j>=0&&(e[j]&(1<<i))==0){z.sqrTo(r,r2);t=r;r=r2;r2=t;if(--i<0){i=this.DB-1;--j;}}}
return z.revert(r);}
function bnGCD(a){var x=(this.s<0)?this.negate():this.clone();var y=(a.s<0)?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y;y=t;}
var i=x.getLowestSetBit(),g=y.getLowestSetBit();if(g<0)return x;if(i<g)g=i;if(g>0){x.rShiftTo(g,x);y.rShiftTo(g,y);}
while(x.signum()>0){if((i=x.getLowestSetBit())>0)x.rShiftTo(i,x);if((i=y.getLowestSetBit())>0)y.rShiftTo(i,y);if(x.compareTo(y)>=0){x.subTo(y,x);x.rShiftTo(1,x);}else{y.subTo(x,y);y.rShiftTo(1,y);}}
if(g>0)y.lShiftTo(g,y);return y;}
function bnpModInt(n){if(n<=0)return 0;var d=this.DV%n,r=(this.s<0)?n-1:0;if(this.t>0)if(d==0)r=this[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this[i])%n;return r;}
function bnModInverse(m){var ac=m.isEven();if((this.isEven()&&ac)||m.signum()==0)return BigInteger.ZERO;var u=m.clone(),v=this.clone();var a=nbv(1),b=nbv(0),c=nbv(0),d=nbv(1);while(u.signum()!=0){while(u.isEven()){u.rShiftTo(1,u);if(ac){if(!a.isEven()||!b.isEven()){a.addTo(this,a);b.subTo(m,b);}
a.rShiftTo(1,a);}else if(!b.isEven())b.subTo(m,b);b.rShiftTo(1,b);}
while(v.isEven()){v.rShiftTo(1,v);if(ac){if(!c.isEven()||!d.isEven()){c.addTo(this,c);d.subTo(m,d);}
c.rShiftTo(1,c);}else if(!d.isEven())d.subTo(m,d);d.rShiftTo(1,d);}
if(u.compareTo(v)>=0){u.subTo(v,u);if(ac)a.subTo(c,a);b.subTo(d,b);}else{v.subTo(u,v);if(ac)c.subTo(a,c);d.subTo(b,d);}}
if(v.compareTo(BigInteger.ONE)!=0)return BigInteger.ZERO;if(d.compareTo(m)>=0)return d.subtract(m);if(d.signum()<0)d.addTo(m,d);else return d;if(d.signum()<0)return d.add(m);else return d;}
var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(t){var i,x=this.abs();if(x.t==1&&x[0]<=lowprimes[lowprimes.length-1]){for(i=0;i<lowprimes.length;++i)
if(x[0]==lowprimes[i])return true;return false;}
if(x.isEven())return false;i=1;while(i<lowprimes.length){var m=lowprimes[i],j=i+1;while(j<lowprimes.length&&m<lplim)m*=lowprimes[j++];m=x.modInt(m);while(i<j)if(m%lowprimes[i++]==0)return false;}
return x.millerRabin(t);}
function bnpMillerRabin(t){var n1=this.subtract(BigInteger.ONE);var k=n1.getLowestSetBit();if(k<=0)return false;var r=n1.shiftRight(k);t=(t+1)>>1;if(t>lowprimes.length)t=lowprimes.length;var a=nbi();for(var i=0;i<t;++i){a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var y=a.modPow(r,this);if(y.compareTo(BigInteger.ONE)!=0&&y.compareTo(n1)!=0){var j=1;while(j++<k&&y.compareTo(n1)!=0){y=y.modPowInt(2,this);if(y.compareTo(BigInteger.ONE)==0)return false;}
if(y.compareTo(n1)!=0)return false;}}
return true;}
BigInteger.prototype.chunkSize=bnpChunkSize;BigInteger.prototype.toRadix=bnpToRadix;BigInteger.prototype.fromRadix=bnpFromRadix;BigInteger.prototype.fromNumber=bnpFromNumber;BigInteger.prototype.bitwiseTo=bnpBitwiseTo;BigInteger.prototype.changeBit=bnpChangeBit;BigInteger.prototype.addTo=bnpAddTo;BigInteger.prototype.dMultiply=bnpDMultiply;BigInteger.prototype.dAddOffset=bnpDAddOffset;BigInteger.prototype.multiplyLowerTo=bnpMultiplyLowerTo;BigInteger.prototype.multiplyUpperTo=bnpMultiplyUpperTo;BigInteger.prototype.modInt=bnpModInt;BigInteger.prototype.millerRabin=bnpMillerRabin;BigInteger.prototype.clone=bnClone;BigInteger.prototype.intValue=bnIntValue;BigInteger.prototype.byteValue=bnByteValue;BigInteger.prototype.shortValue=bnShortValue;BigInteger.prototype.signum=bnSigNum;BigInteger.prototype.toByteArray=bnToByteArray;BigInteger.prototype.equals=bnEquals;BigInteger.prototype.min=bnMin;BigInteger.prototype.max=bnMax;BigInteger.prototype.and=bnAnd;BigInteger.prototype.or=bnOr;BigInteger.prototype.xor=bnXor;BigInteger.prototype.andNot=bnAndNot;BigInteger.prototype.not=bnNot;BigInteger.prototype.shiftLeft=bnShiftLeft;BigInteger.prototype.shiftRight=bnShiftRight;BigInteger.prototype.getLowestSetBit=bnGetLowestSetBit;BigInteger.prototype.bitCount=bnBitCount;BigInteger.prototype.testBit=bnTestBit;BigInteger.prototype.setBit=bnSetBit;BigInteger.prototype.clearBit=bnClearBit;BigInteger.prototype.flipBit=bnFlipBit;BigInteger.prototype.add=bnAdd;BigInteger.prototype.subtract=bnSubtract;BigInteger.prototype.multiply=bnMultiply;BigInteger.prototype.divide=bnDivide;BigInteger.prototype.remainder=bnRemainder;BigInteger.prototype.divideAndRemainder=bnDivideAndRemainder;BigInteger.prototype.modPow=bnModPow;BigInteger.prototype.modInverse=bnModInverse;BigInteger.prototype.pow=bnPow;BigInteger.prototype.gcd=bnGCD;BigInteger.prototype.isProbablePrime=bnIsProbablePrime;BigInteger.prototype.square=bnSquare;function Arcfour(){this.i=0;this.j=0;this.S=new Array();}
function ARC4init(key){var i,j,t;for(i=0;i<256;++i)
this.S[i]=i;j=0;for(i=0;i<256;++i){j=(j+this.S[i]+key[i%key.length])&255;t=this.S[i];this.S[i]=this.S[j];this.S[j]=t;}
this.i=0;this.j=0;}
function ARC4next(){var t;this.i=(this.i+1)&255;this.j=(this.j+this.S[this.i])&255;t=this.S[this.i];this.S[this.i]=this.S[this.j];this.S[this.j]=t;return this.S[(t+this.S[this.i])&255];}
Arcfour.prototype.init=ARC4init;Arcfour.prototype.next=ARC4next;function prng_newstate(){return new Arcfour();}
var rng_psize=256;var rng_state;var rng_pool;var rng_pptr;if(rng_pool==null){rng_pool=new Array();rng_pptr=0;var t;if(window.crypto&&window.crypto.getRandomValues){var z=new Uint32Array(256);window.crypto.getRandomValues(z);for(t=0;t<z.length;++t)
rng_pool[rng_pptr++]=z[t]&255;}
var onMouseMoveListener=function(ev){this.count=this.count||0;if(this.count>=256||rng_pptr>=rng_psize){if(window.removeEventListener)window.removeEventListener("mousemove",onMouseMoveListener);else if(window.detachEvent)window.detachEvent("onmousemove",onMouseMoveListener);return;}
this.count+=1;var mouseCoordinates=ev.x+ev.y;rng_pool[rng_pptr++]=mouseCoordinates&255;};if(window.addEventListener)window.addEventListener("mousemove",onMouseMoveListener);else if(window.attachEvent)window.attachEvent("onmousemove",onMouseMoveListener);}
function rng_get_byte(){if(rng_state==null){rng_state=prng_newstate();while(rng_pptr<rng_psize){var random=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=random&255;}
rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)
rng_pool[rng_pptr]=0;rng_pptr=0;}
return rng_state.next();}
function rng_get_bytes(ba){var i;for(i=0;i<ba.length;++i)ba[i]=rng_get_byte();}
function SecureRandom(){}
SecureRandom.prototype.nextBytes=rng_get_bytes;function parseBigInt(str,r){return new BigInteger(str,r);}
function linebrk(s,n){var ret="";var i=0;while(i+n<s.length){ret+=s.substring(i,i+n)+"\n";i+=n;}
return ret+s.substring(i,s.length);}
function byte2Hex(b){if(b<0x10)return"0"+b.toString(16);else return b.toString(16);}
function pkcs1pad2(s,n){if(n<s.length+11){console.error("Message too long for RSA");return null;}
var ba=new Array();var i=s.length-1;while(i>=0&&n>0){var c=s.charCodeAt(i--);if(c<128){ba[--n]=c;}else if((c>127)&&(c<2048)){ba[--n]=(c&63)|128;ba[--n]=(c>>6)|192;}else{ba[--n]=(c&63)|128;ba[--n]=((c>>6)&63)|128;ba[--n]=(c>>12)|224;}}
ba[--n]=0;var rng=new SecureRandom();var x=new Array();while(n>2){x[0]=0;while(x[0]==0)rng.nextBytes(x);ba[--n]=x[0];}
ba[--n]=2;ba[--n]=0;return new BigInteger(ba);}
function RSAKey(){this.n=null;this.e=0;this.d=null;this.p=null;this.q=null;this.dmp1=null;this.dmq1=null;this.coeff=null;}
function RSASetPublic(N,E){if(N!=null&&E!=null&&N.length>0&&E.length>0){this.n=parseBigInt(N,16);this.e=parseInt(E,16);}else console.error("Invalid RSA public key");}
function RSADoPublic(x){return x.modPowInt(this.e,this.n);}
function RSAEncrypt(text){var m=pkcs1pad2(text,(this.n.bitLength()+7)>>3);if(m==null)return null;var c=this.doPublic(m);if(c==null)return null;var h=c.toString(16);if((h.length&1)==0)return h;else return"0"+h;}
RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;function pkcs1unpad2(d,n){var b=d.toByteArray();var i=0;while(i<b.length&&b[i]==0)++i;if(b.length-i!=n-1||b[i]!=2)return null;++i;while(b[i]!=0)
if(++i>=b.length)return null;var ret="";while(++i<b.length){var c=b[i]&255;if(c<128){ret+=String.fromCharCode(c);}else if((c>191)&&(c<224)){ret+=String.fromCharCode(((c&31)<<6)|(b[i+1]&63));++i;}else{ret+=String.fromCharCode(((c&15)<<12)|((b[i+1]&63)<<6)|(b[i+2]&63));i+=2;}}
return ret;}
function RSASetPrivate(N,E,D){if(N!=null&&E!=null&&N.length>0&&E.length>0){this.n=parseBigInt(N,16);this.e=parseInt(E,16);this.d=parseBigInt(D,16);}else console.error("Invalid RSA private key");}
function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C){if(N!=null&&E!=null&&N.length>0&&E.length>0){this.n=parseBigInt(N,16);this.e=parseInt(E,16);this.d=parseBigInt(D,16);this.p=parseBigInt(P,16);this.q=parseBigInt(Q,16);this.dmp1=parseBigInt(DP,16);this.dmq1=parseBigInt(DQ,16);this.coeff=parseBigInt(C,16);}else console.error("Invalid RSA private key");}
function RSAGenerate(B,E){var rng=new SecureRandom();var qs=B>>1;this.e=parseInt(E,16);var ee=new BigInteger(E,16);for(;;){for(;;){this.p=new BigInteger(B-qs,1,rng);if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE)==0&&this.p.isProbablePrime(10))break;}
for(;;){this.q=new BigInteger(qs,1,rng);if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE)==0&&this.q.isProbablePrime(10))break;}
if(this.p.compareTo(this.q)<=0){var t=this.p;this.p=this.q;this.q=t;}
var p1=this.p.subtract(BigInteger.ONE);var q1=this.q.subtract(BigInteger.ONE);var phi=p1.multiply(q1);if(phi.gcd(ee).compareTo(BigInteger.ONE)==0){this.n=this.p.multiply(this.q);this.d=ee.modInverse(phi);this.dmp1=this.d.mod(p1);this.dmq1=this.d.mod(q1);this.coeff=this.q.modInverse(this.p);break;}}}
function RSADoPrivate(x){if(this.p==null||this.q==null)return x.modPow(this.d,this.n);var xp=x.mod(this.p).modPow(this.dmp1,this.p);var xq=x.mod(this.q).modPow(this.dmq1,this.q);while(xp.compareTo(xq)<0)
xp=xp.add(this.p);return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);}
function RSADecrypt(ctext){var c=parseBigInt(ctext,16);var m=this.doPrivate(c);if(m==null)return null;return pkcs1unpad2(m,(this.n.bitLength()+7)>>3);}
RSAKey.prototype.doPrivate=RSADoPrivate;RSAKey.prototype.setPrivate=RSASetPrivate;RSAKey.prototype.setPrivateEx=RSASetPrivateEx;RSAKey.prototype.generate=RSAGenerate;RSAKey.prototype.decrypt=RSADecrypt;(function(){var RSAGenerateAsync=function(B,E,callback){var rng=new SecureRandom();var qs=B>>1;this.e=parseInt(E,16);var ee=new BigInteger(E,16);var rsa=this;var loop1=function(){var loop4=function(){if(rsa.p.compareTo(rsa.q)<=0){var t=rsa.p;rsa.p=rsa.q;rsa.q=t;}
var p1=rsa.p.subtract(BigInteger.ONE);var q1=rsa.q.subtract(BigInteger.ONE);var phi=p1.multiply(q1);if(phi.gcd(ee).compareTo(BigInteger.ONE)==0){rsa.n=rsa.p.multiply(rsa.q);rsa.d=ee.modInverse(phi);rsa.dmp1=rsa.d.mod(p1);rsa.dmq1=rsa.d.mod(q1);rsa.coeff=rsa.q.modInverse(rsa.p);setTimeout(function(){callback()},0);}else{setTimeout(loop1,0);}};var loop3=function(){rsa.q=nbi();rsa.q.fromNumberAsync(qs,1,rng,function(){rsa.q.subtract(BigInteger.ONE).gcda(ee,function(r){if(r.compareTo(BigInteger.ONE)==0&&rsa.q.isProbablePrime(10)){setTimeout(loop4,0);}else{setTimeout(loop3,0);}});});};var loop2=function(){rsa.p=nbi();rsa.p.fromNumberAsync(B-qs,1,rng,function(){rsa.p.subtract(BigInteger.ONE).gcda(ee,function(r){if(r.compareTo(BigInteger.ONE)==0&&rsa.p.isProbablePrime(10)){setTimeout(loop3,0);}else{setTimeout(loop2,0);}});});};setTimeout(loop2,0);};setTimeout(loop1,0);};RSAKey.prototype.generateAsync=RSAGenerateAsync;var bnGCDAsync=function(a,callback){var x=(this.s<0)?this.negate():this.clone();var y=(a.s<0)?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y;y=t;}
var i=x.getLowestSetBit(),g=y.getLowestSetBit();if(g<0){callback(x);return;}
if(i<g)g=i;if(g>0){x.rShiftTo(g,x);y.rShiftTo(g,y);}
var gcda1=function(){if((i=x.getLowestSetBit())>0){x.rShiftTo(i,x);}
if((i=y.getLowestSetBit())>0){y.rShiftTo(i,y);}
if(x.compareTo(y)>=0){x.subTo(y,x);x.rShiftTo(1,x);}else{y.subTo(x,y);y.rShiftTo(1,y);}
if(!(x.signum()>0)){if(g>0)y.lShiftTo(g,y);setTimeout(function(){callback(y)},0);}else{setTimeout(gcda1,0);}};setTimeout(gcda1,10);};BigInteger.prototype.gcda=bnGCDAsync;var bnpFromNumberAsync=function(a,b,c,callback){if("number"==typeof b){if(a<2){this.fromInt(1);}else{this.fromNumber(a,c);if(!this.testBit(a-1)){this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);}
if(this.isEven()){this.dAddOffset(1,0);}
var bnp=this;var bnpfn1=function(){bnp.dAddOffset(2,0);if(bnp.bitLength()>a)bnp.subTo(BigInteger.ONE.shiftLeft(a-1),bnp);if(bnp.isProbablePrime(b)){setTimeout(function(){callback()},0);}else{setTimeout(bnpfn1,0);}};setTimeout(bnpfn1,0);}}else{var x=new Array(),t=a&7;x.length=(a>>3)+1;b.nextBytes(x);if(t>0)x[0]&=((1<<t)-1);else x[0]=0;this.fromString(x,256);}};BigInteger.prototype.fromNumberAsync=bnpFromNumberAsync;})();var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64pad="=";function hex2b64(h){var i;var c;var ret="";for(i=0;i+3<=h.length;i+=3){c=parseInt(h.substring(i,i+3),16);ret+=b64map.charAt(c>>6)+b64map.charAt(c&63);}
if(i+1==h.length){c=parseInt(h.substring(i,i+1),16);ret+=b64map.charAt(c<<2);}else if(i+2==h.length){c=parseInt(h.substring(i,i+2),16);ret+=b64map.charAt(c>>2)+b64map.charAt((c&3)<<4);}
while((ret.length&3)>0)ret+=b64pad;return ret;}
function b64tohex(s){var ret=""
var i;var k=0;var slop;for(i=0;i<s.length;++i){if(s.charAt(i)==b64pad)break;v=b64map.indexOf(s.charAt(i));if(v<0)continue;if(k==0){ret+=int2char(v>>2);slop=v&3;k=1;}else if(k==1){ret+=int2char((slop<<2)|(v>>4));slop=v&0xf;k=2;}else if(k==2){ret+=int2char(slop);ret+=int2char(v>>2);slop=v&3;k=3;}else{ret+=int2char((slop<<2)|(v>>4));ret+=int2char(v&0xf);k=0;}}
if(k==1)ret+=int2char(slop<<2);return ret;}
function b64toBA(s){var h=b64tohex(s);var i;var a=new Array();for(i=0;2*i<h.length;++i){a[i]=parseInt(h.substring(2*i,2*i+2),16);}
return a;}
var JSX=JSX||{};JSX.env=JSX.env||{};var L=JSX,OP=Object.prototype,FUNCTION_TOSTRING='[object Function]',ADD=["toString","valueOf"];JSX.env.parseUA=function(agent){var numberify=function(s){var c=0;return parseFloat(s.replace(/\./g,function(){return(c++==1)?'':'.';}));},nav=navigator,o={ie:0,opera:0,gecko:0,webkit:0,chrome:0,mobile:null,air:0,ipad:0,iphone:0,ipod:0,ios:null,android:0,webos:0,caja:nav&&nav.cajaVersion,secure:false,os:null},ua=agent||(navigator&&navigator.userAgent),loc=window&&window.location,href=loc&&loc.href,m;o.secure=href&&(href.toLowerCase().indexOf("https")===0);if(ua){if((/windows|win32/i).test(ua)){o.os='windows';}else if((/macintosh/i).test(ua)){o.os='macintosh';}else if((/rhino/i).test(ua)){o.os='rhino';}
if((/KHTML/).test(ua)){o.webkit=1;}
m=ua.match(/AppleWebKit\/([^\s]*)/);if(m&&m[1]){o.webkit=numberify(m[1]);if(/ Mobile\//.test(ua)){o.mobile='Apple';m=ua.match(/OS ([^\s]*)/);if(m&&m[1]){m=numberify(m[1].replace('_','.'));}
o.ios=m;o.ipad=o.ipod=o.iphone=0;m=ua.match(/iPad|iPod|iPhone/);if(m&&m[0]){o[m[0].toLowerCase()]=o.ios;}}else{m=ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);if(m){o.mobile=m[0];}
if(/webOS/.test(ua)){o.mobile='WebOS';m=ua.match(/webOS\/([^\s]*);/);if(m&&m[1]){o.webos=numberify(m[1]);}}
if(/ Android/.test(ua)){o.mobile='Android';m=ua.match(/Android ([^\s]*);/);if(m&&m[1]){o.android=numberify(m[1]);}}}
m=ua.match(/Chrome\/([^\s]*)/);if(m&&m[1]){o.chrome=numberify(m[1]);}else{m=ua.match(/AdobeAIR\/([^\s]*)/);if(m){o.air=m[0];}}}
if(!o.webkit){m=ua.match(/Opera[\s\/]([^\s]*)/);if(m&&m[1]){o.opera=numberify(m[1]);m=ua.match(/Version\/([^\s]*)/);if(m&&m[1]){o.opera=numberify(m[1]);}
m=ua.match(/Opera Mini[^;]*/);if(m){o.mobile=m[0];}}else{m=ua.match(/MSIE\s([^;]*)/);if(m&&m[1]){o.ie=numberify(m[1]);}else{m=ua.match(/Gecko\/([^\s]*)/);if(m){o.gecko=1;m=ua.match(/rv:([^\s\)]*)/);if(m&&m[1]){o.gecko=numberify(m[1]);}}}}}}
return o;};JSX.env.ua=JSX.env.parseUA();JSX.isFunction=function(o){return(typeof o==='function')||OP.toString.apply(o)===FUNCTION_TOSTRING;};JSX._IEEnumFix=(JSX.env.ua.ie)?function(r,s){var i,fname,f;for(i=0;i<ADD.length;i=i+1){fname=ADD[i];f=s[fname];if(L.isFunction(f)&&f!=OP[fname]){r[fname]=f;}}}:function(){};JSX.extend=function(subc,superc,overrides){if(!superc||!subc){throw new Error("extend failed, please check that "+"all dependencies are included.");}
var F=function(){},i;F.prototype=superc.prototype;subc.prototype=new F();subc.prototype.constructor=subc;subc.superclass=superc.prototype;if(superc.prototype.constructor==OP.constructor){superc.prototype.constructor=superc;}
if(overrides){for(i in overrides){if(L.hasOwnProperty(overrides,i)){subc.prototype[i]=overrides[i];}}
L._IEEnumFix(subc.prototype,overrides);}};if(typeof KJUR=="undefined"||!KJUR)KJUR={};if(typeof KJUR.asn1=="undefined"||!KJUR.asn1)KJUR.asn1={};KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(i){var h=i.toString(16);if((h.length%2)==1)h='0'+h;return h;};this.bigIntToMinTwosComplementsHex=function(bigIntegerValue){var h=bigIntegerValue.toString(16);if(h.substr(0,1)!='-'){if(h.length%2==1){h='0'+h;}else{if(!h.match(/^[0-7]/)){h='00'+h;}}}else{var hPos=h.substr(1);var xorLen=hPos.length;if(xorLen%2==1){xorLen+=1;}else{if(!h.match(/^[0-7]/)){xorLen+=2;}}
var hMask='';for(var i=0;i<xorLen;i++){hMask+='f';}
var biMask=new BigInteger(hMask,16);var biNeg=biMask.xor(bigIntegerValue).add(BigInteger.ONE);h=biNeg.toString(16).replace(/^-/,'');}
return h;};this.getPEMStringFromHex=function(dataHex,pemHeader){var dataWA=CryptoJS.enc.Hex.parse(dataHex);var dataB64=CryptoJS.enc.Base64.stringify(dataWA);var pemBody=dataB64.replace(/(.{64})/g,"$1\r\n");pemBody=pemBody.replace(/\r\n$/,'');return"-----BEGIN "+pemHeader+"-----\r\n"+pemBody+"\r\n-----END "+pemHeader+"-----\r\n";};};KJUR.asn1.ASN1Object=function(){var isModified=true;var hTLV=null;var hT='00'
var hL='00';var hV='';this.getLengthHexFromValue=function(){if(typeof this.hV=="undefined"||this.hV==null){throw"this.hV is null or undefined.";}
if(this.hV.length%2==1){throw"value hex must be even length: n="+hV.length+",v="+this.hV;}
var n=this.hV.length/2;var hN=n.toString(16);if(hN.length%2==1){hN="0"+hN;}
if(n<128){return hN;}else{var hNlen=hN.length/2;if(hNlen>15){throw"ASN.1 length too long to represent by 8x: n = "+n.toString(16);}
var head=128+hNlen;return head.toString(16)+hN;}};this.getEncodedHex=function(){if(this.hTLV==null||this.isModified){this.hV=this.getFreshValueHex();this.hL=this.getLengthHexFromValue();this.hTLV=this.hT+this.hL+this.hV;this.isModified=false;}
return this.hTLV;};this.getValueHex=function(){this.getEncodedHex();return this.hV;}
this.getFreshValueHex=function(){return'';};};KJUR.asn1.DERAbstractString=function(params){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var s=null;var hV=null;this.getString=function(){return this.s;};this.setString=function(newS){this.hTLV=null;this.isModified=true;this.s=newS;this.hV=stohex(this.s);};this.setStringHex=function(newHexString){this.hTLV=null;this.isModified=true;this.s=null;this.hV=newHexString;};this.getFreshValueHex=function(){return this.hV;};if(typeof params!="undefined"){if(typeof params['str']!="undefined"){this.setString(params['str']);}else if(typeof params['hex']!="undefined"){this.setStringHex(params['hex']);}}};JSX.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractTime=function(params){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);var s=null;var date=null;this.localDateToUTC=function(d){utc=d.getTime()+(d.getTimezoneOffset()*60000);var utcDate=new Date(utc);return utcDate;};this.formatDate=function(dateObject,type){var pad=this.zeroPadding;var d=this.localDateToUTC(dateObject);var year=String(d.getFullYear());if(type=='utc')year=year.substr(2,2);var month=pad(String(d.getMonth()+1),2);var day=pad(String(d.getDate()),2);var hour=pad(String(d.getHours()),2);var min=pad(String(d.getMinutes()),2);var sec=pad(String(d.getSeconds()),2);return year+month+day+hour+min+sec+'Z';};this.zeroPadding=function(s,len){if(s.length>=len)return s;return new Array(len-s.length+1).join('0')+s;};this.getString=function(){return this.s;};this.setString=function(newS){this.hTLV=null;this.isModified=true;this.s=newS;this.hV=stohex(this.s);};this.setByDateValue=function(year,month,day,hour,min,sec){var dateObject=new Date(Date.UTC(year,month-1,day,hour,min,sec,0));this.setByDate(dateObject);};this.getFreshValueHex=function(){return this.hV;};};JSX.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractStructured=function(params){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var asn1Array=null;this.setByASN1ObjectArray=function(asn1ObjectArray){this.hTLV=null;this.isModified=true;this.asn1Array=asn1ObjectArray;};this.appendASN1Object=function(asn1Object){this.hTLV=null;this.isModified=true;this.asn1Array.push(asn1Object);};this.asn1Array=new Array();if(typeof params!="undefined"){if(typeof params['array']!="undefined"){this.asn1Array=params['array'];}}};JSX.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object);KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this);this.hT="01";this.hTLV="0101ff";};JSX.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object);KJUR.asn1.DERInteger=function(params){KJUR.asn1.DERInteger.superclass.constructor.call(this);this.hT="02";this.setByBigInteger=function(bigIntegerValue){this.hTLV=null;this.isModified=true;this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);};this.setByInteger=function(intValue){var bi=new BigInteger(String(intValue),10);this.setByBigInteger(bi);};this.setValueHex=function(newHexString){this.hV=newHexString;};this.getFreshValueHex=function(){return this.hV;};if(typeof params!="undefined"){if(typeof params['bigint']!="undefined"){this.setByBigInteger(params['bigint']);}else if(typeof params['int']!="undefined"){this.setByInteger(params['int']);}else if(typeof params['hex']!="undefined"){this.setValueHex(params['hex']);}}};JSX.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object);KJUR.asn1.DERBitString=function(params){KJUR.asn1.DERBitString.superclass.constructor.call(this);this.hT="03";this.setHexValueIncludingUnusedBits=function(newHexStringIncludingUnusedBits){this.hTLV=null;this.isModified=true;this.hV=newHexStringIncludingUnusedBits;};this.setUnusedBitsAndHexValue=function(unusedBits,hValue){if(unusedBits<0||7<unusedBits){throw"unused bits shall be from 0 to 7: u = "+unusedBits;}
var hUnusedBits="0"+unusedBits;this.hTLV=null;this.isModified=true;this.hV=hUnusedBits+hValue;};this.setByBinaryString=function(binaryString){binaryString=binaryString.replace(/0+$/,'');var unusedBits=8-binaryString.length%8;if(unusedBits==8)unusedBits=0;for(var i=0;i<=unusedBits;i++){binaryString+='0';}
var h='';for(var i=0;i<binaryString.length-1;i+=8){var b=binaryString.substr(i,8);var x=parseInt(b,2).toString(16);if(x.length==1)x='0'+x;h+=x;}
this.hTLV=null;this.isModified=true;this.hV='0'+unusedBits+h;};this.setByBooleanArray=function(booleanArray){var s='';for(var i=0;i<booleanArray.length;i++){if(booleanArray[i]==true){s+='1';}else{s+='0';}}
this.setByBinaryString(s);};this.newFalseArray=function(nLength){var a=new Array(nLength);for(var i=0;i<nLength;i++){a[i]=false;}
return a;};this.getFreshValueHex=function(){return this.hV;};if(typeof params!="undefined"){if(typeof params['hex']!="undefined"){this.setHexValueIncludingUnusedBits(params['hex']);}else if(typeof params['bin']!="undefined"){this.setByBinaryString(params['bin']);}else if(typeof params['array']!="undefined"){this.setByBooleanArray(params['array']);}}};JSX.extend(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object);KJUR.asn1.DEROctetString=function(params){KJUR.asn1.DEROctetString.superclass.constructor.call(this,params);this.hT="04";};JSX.extend(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this);this.hT="05";this.hTLV="0500";};JSX.extend(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object);KJUR.asn1.DERObjectIdentifier=function(params){var itox=function(i){var h=i.toString(16);if(h.length==1)h='0'+h;return h;};var roidtox=function(roid){var h='';var bi=new BigInteger(roid,10);var b=bi.toString(2);var padLen=7-b.length%7;if(padLen==7)padLen=0;var bPad='';for(var i=0;i<padLen;i++)bPad+='0';b=bPad+b;for(var i=0;i<b.length-1;i+=7){var b8=b.substr(i,7);if(i!=b.length-7)b8='1'+b8;h+=itox(parseInt(b8,2));}
return h;}
KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);this.hT="06";this.setValueHex=function(newHexString){this.hTLV=null;this.isModified=true;this.s=null;this.hV=newHexString;};this.setValueOidString=function(oidString){if(!oidString.match(/^[0-9.]+$/)){throw"malformed oid string: "+oidString;}
var h='';var a=oidString.split('.');var i0=parseInt(a[0])*40+parseInt(a[1]);h+=itox(i0);a.splice(0,2);for(var i=0;i<a.length;i++){h+=roidtox(a[i]);}
this.hTLV=null;this.isModified=true;this.s=null;this.hV=h;};this.setValueName=function(oidName){if(typeof KJUR.asn1.x509.OID.name2oidList[oidName]!="undefined"){var oid=KJUR.asn1.x509.OID.name2oidList[oidName];this.setValueOidString(oid);}else{throw"DERObjectIdentifier oidName undefined: "+oidName;}};this.getFreshValueHex=function(){return this.hV;};if(typeof params!="undefined"){if(typeof params['oid']!="undefined"){this.setValueOidString(params['oid']);}else if(typeof params['hex']!="undefined"){this.setValueHex(params['hex']);}else if(typeof params['name']!="undefined"){this.setValueName(params['name']);}}};JSX.extend(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object);KJUR.asn1.DERUTF8String=function(params){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,params);this.hT="0c";};JSX.extend(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString);KJUR.asn1.DERNumericString=function(params){KJUR.asn1.DERNumericString.superclass.constructor.call(this,params);this.hT="12";};JSX.extend(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERPrintableString=function(params){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,params);this.hT="13";};JSX.extend(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERTeletexString=function(params){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,params);this.hT="14";};JSX.extend(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERIA5String=function(params){KJUR.asn1.DERIA5String.superclass.constructor.call(this,params);this.hT="16";};JSX.extend(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString);KJUR.asn1.DERUTCTime=function(params){KJUR.asn1.DERUTCTime.superclass.constructor.call(this,params);this.hT="17";this.setByDate=function(dateObject){this.hTLV=null;this.isModified=true;this.date=dateObject;this.s=this.formatDate(this.date,'utc');this.hV=stohex(this.s);};if(typeof params!="undefined"){if(typeof params['str']!="undefined"){this.setString(params['str']);}else if(typeof params['hex']!="undefined"){this.setStringHex(params['hex']);}else if(typeof params['date']!="undefined"){this.setByDate(params['date']);}}};JSX.extend(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime);KJUR.asn1.DERGeneralizedTime=function(params){KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this,params);this.hT="18";this.setByDate=function(dateObject){this.hTLV=null;this.isModified=true;this.date=dateObject;this.s=this.formatDate(this.date,'gen');this.hV=stohex(this.s);};if(typeof params!="undefined"){if(typeof params['str']!="undefined"){this.setString(params['str']);}else if(typeof params['hex']!="undefined"){this.setStringHex(params['hex']);}else if(typeof params['date']!="undefined"){this.setByDate(params['date']);}}};JSX.extend(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime);KJUR.asn1.DERSequence=function(params){KJUR.asn1.DERSequence.superclass.constructor.call(this,params);this.hT="30";this.getFreshValueHex=function(){var h='';for(var i=0;i<this.asn1Array.length;i++){var asn1Obj=this.asn1Array[i];h+=asn1Obj.getEncodedHex();}
this.hV=h;return this.hV;};};JSX.extend(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured);KJUR.asn1.DERSet=function(params){KJUR.asn1.DERSet.superclass.constructor.call(this,params);this.hT="31";this.getFreshValueHex=function(){var a=new Array();for(var i=0;i<this.asn1Array.length;i++){var asn1Obj=this.asn1Array[i];a.push(asn1Obj.getEncodedHex());}
a.sort();this.hV=a.join('');return this.hV;};};JSX.extend(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured);KJUR.asn1.DERTaggedObject=function(params){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);this.hT="a0";this.hV='';this.isExplicit=true;this.asn1Object=null;this.setASN1Object=function(isExplicitFlag,tagNoHex,asn1Object){this.hT=tagNoHex;this.isExplicit=isExplicitFlag;this.asn1Object=asn1Object;if(this.isExplicit){this.hV=this.asn1Object.getEncodedHex();this.hTLV=null;this.isModified=true;}else{this.hV=null;this.hTLV=asn1Object.getEncodedHex();this.hTLV=this.hTLV.replace(/^../,tagNoHex);this.isModified=false;}};this.getFreshValueHex=function(){return this.hV;};if(typeof params!="undefined"){if(typeof params['tag']!="undefined"){this.hT=params['tag'];}
if(typeof params['explicit']!="undefined"){this.isExplicit=params['explicit'];}
if(typeof params['obj']!="undefined"){this.asn1Object=params['obj'];this.setASN1Object(this.isExplicit,this.hT,this.asn1Object);}}};JSX.extend(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object);(function(undefined){"use strict";var Hex={},decoder;Hex.decode=function(a){var i;if(decoder===undefined){var hex="0123456789ABCDEF",ignore=" \f\n\r\t\u00A0\u2028\u2029";decoder=[];for(i=0;i<16;++i)
decoder[hex.charAt(i)]=i;hex=hex.toLowerCase();for(i=10;i<16;++i)
decoder[hex.charAt(i)]=i;for(i=0;i<ignore.length;++i)
decoder[ignore.charAt(i)]=-1;}
var out=[],bits=0,char_count=0;for(i=0;i<a.length;++i){var c=a.charAt(i);if(c=='=')break;c=decoder[c];if(c==-1)continue;if(c===undefined)throw'Illegal character at offset '+i;bits|=c;if(++char_count>=2){out[out.length]=bits;bits=0;char_count=0;}else{bits<<=4;}}
if(char_count)throw"Hex encoding incomplete: 4 bits missing";return out;};window.Hex=Hex;})();(function(undefined){"use strict";var Base64={},decoder;Base64.decode=function(a){var i;if(decoder===undefined){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ignore="= \f\n\r\t\u00A0\u2028\u2029";decoder=[];for(i=0;i<64;++i)
decoder[b64.charAt(i)]=i;for(i=0;i<ignore.length;++i)
decoder[ignore.charAt(i)]=-1;}
var out=[];var bits=0,char_count=0;for(i=0;i<a.length;++i){var c=a.charAt(i);if(c=='=')break;c=decoder[c];if(c==-1)continue;if(c===undefined)throw'Illegal character at offset '+i;bits|=c;if(++char_count>=4){out[out.length]=(bits>>16);out[out.length]=(bits>>8)&0xFF;out[out.length]=bits&0xFF;bits=0;char_count=0;}else{bits<<=6;}}
switch(char_count){case 1:throw"Base64 encoding incomplete: at least 2 bits missing";case 2:out[out.length]=(bits>>10);break;case 3:out[out.length]=(bits>>16);out[out.length]=(bits>>8)&0xFF;break;}
return out;};Base64.re=/-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;Base64.unarmor=function(a){var m=Base64.re.exec(a);if(m){if(m[1])a=m[1];else if(m[2])a=m[2];else throw"RegExp out of sync";}
return Base64.decode(a);};window.Base64=Base64;})();(function(undefined){"use strict";var hardLimit=100,ellipsis="\u2026",DOM={tag:function(tagName,className){var t=document.createElement(tagName);t.className=className;return t;},text:function(str){return document.createTextNode(str);}};function Stream(enc,pos){if(enc instanceof Stream){this.enc=enc.enc;this.pos=enc.pos;}else{this.enc=enc;this.pos=pos;}}
Stream.prototype.get=function(pos){if(pos===undefined)pos=this.pos++;if(pos>=this.enc.length)throw'Requesting byte offset '+pos+' on a stream of length '+this.enc.length;return this.enc[pos];};Stream.prototype.hexDigits="0123456789ABCDEF";Stream.prototype.hexByte=function(b){return this.hexDigits.charAt((b>>4)&0xF)+this.hexDigits.charAt(b&0xF);};Stream.prototype.hexDump=function(start,end,raw){var s="";for(var i=start;i<end;++i){s+=this.hexByte(this.get(i));if(raw!==true)switch(i&0xF){case 0x7:s+="  ";break;case 0xF:s+="\n";break;default:s+=" ";}}
return s;};Stream.prototype.parseStringISO=function(start,end){var s="";for(var i=start;i<end;++i)
s+=String.fromCharCode(this.get(i));return s;};Stream.prototype.parseStringUTF=function(start,end){var s="";for(var i=start;i<end;){var c=this.get(i++);if(c<128)s+=String.fromCharCode(c);else if((c>191)&&(c<224))s+=String.fromCharCode(((c&0x1F)<<6)|(this.get(i++)&0x3F));else s+=String.fromCharCode(((c&0x0F)<<12)|((this.get(i++)&0x3F)<<6)|(this.get(i++)&0x3F));}
return s;};Stream.prototype.parseStringBMP=function(start,end){var str=""
for(var i=start;i<end;i+=2){var high_byte=this.get(i);var low_byte=this.get(i+1);str+=String.fromCharCode((high_byte<<8)+low_byte);}
return str;};Stream.prototype.reTime=/^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;Stream.prototype.parseTime=function(start,end){var s=this.parseStringISO(start,end),m=this.reTime.exec(s);if(!m)return"Unrecognized time: "+s;s=m[1]+"-"+m[2]+"-"+m[3]+" "+m[4];if(m[5]){s+=":"+m[5];if(m[6]){s+=":"+m[6];if(m[7])s+="."+m[7];}}
if(m[8]){s+=" UTC";if(m[8]!='Z'){s+=m[8];if(m[9])s+=":"+m[9];}}
return s;};Stream.prototype.parseInteger=function(start,end){var len=end-start;if(len>4){len<<=3;var s=this.get(start);if(s===0)len-=8;else while(s<128){s<<=1;--len;}
return"("+len+" bit)";}
var n=0;for(var i=start;i<end;++i)
n=(n<<8)|this.get(i);return n;};Stream.prototype.parseBitString=function(start,end){var unusedBit=this.get(start),lenBit=((end-start-1)<<3)-unusedBit,s="("+lenBit+" bit)";if(lenBit<=20){var skip=unusedBit;s+=" ";for(var i=end-1;i>start;--i){var b=this.get(i);for(var j=skip;j<8;++j)
s+=(b>>j)&1?"1":"0";skip=0;}}
return s;};Stream.prototype.parseOctetString=function(start,end){var len=end-start,s="("+len+" byte) ";if(len>hardLimit)end=start+hardLimit;for(var i=start;i<end;++i)
s+=this.hexByte(this.get(i));if(len>hardLimit)s+=ellipsis;return s;};Stream.prototype.parseOID=function(start,end){var s='',n=0,bits=0;for(var i=start;i<end;++i){var v=this.get(i);n=(n<<7)|(v&0x7F);bits+=7;if(!(v&0x80)){if(s===''){var m=n<80?n<40?0:1:2;s=m+"."+(n-m*40);}else s+="."+((bits>=31)?"bigint":n);n=bits=0;}}
return s;};function ASN1(stream,header,length,tag,sub){this.stream=stream;this.header=header;this.length=length;this.tag=tag;this.sub=sub;}
ASN1.prototype.typeName=function(){if(this.tag===undefined)return"unknown";var tagClass=this.tag>>6,tagConstructed=(this.tag>>5)&1,tagNumber=this.tag&0x1F;switch(tagClass){case 0:switch(tagNumber){case 0x00:return"EOC";case 0x01:return"BOOLEAN";case 0x02:return"INTEGER";case 0x03:return"BIT_STRING";case 0x04:return"OCTET_STRING";case 0x05:return"NULL";case 0x06:return"OBJECT_IDENTIFIER";case 0x07:return"ObjectDescriptor";case 0x08:return"EXTERNAL";case 0x09:return"REAL";case 0x0A:return"ENUMERATED";case 0x0B:return"EMBEDDED_PDV";case 0x0C:return"UTF8String";case 0x10:return"SEQUENCE";case 0x11:return"SET";case 0x12:return"NumericString";case 0x13:return"PrintableString";case 0x14:return"TeletexString";case 0x15:return"VideotexString";case 0x16:return"IA5String";case 0x17:return"UTCTime";case 0x18:return"GeneralizedTime";case 0x19:return"GraphicString";case 0x1A:return"VisibleString";case 0x1B:return"GeneralString";case 0x1C:return"UniversalString";case 0x1E:return"BMPString";default:return"Universal_"+tagNumber.toString(16);}
case 1:return"Application_"+tagNumber.toString(16);case 2:return"["+tagNumber+"]";case 3:return"Private_"+tagNumber.toString(16);}};ASN1.prototype.reSeemsASCII=/^[ -~]+$/;ASN1.prototype.content=function(){if(this.tag===undefined)return null;var tagClass=this.tag>>6,tagNumber=this.tag&0x1F,content=this.posContent(),len=Math.abs(this.length);if(tagClass!==0){if(this.sub!==null)return"("+this.sub.length+" elem)";var s=this.stream.parseStringISO(content,content+Math.min(len,hardLimit));if(this.reSeemsASCII.test(s))return s.substring(0,2*hardLimit)+((s.length>2*hardLimit)?ellipsis:"");else return this.stream.parseOctetString(content,content+len);}
switch(tagNumber){case 0x01:return(this.stream.get(content)===0)?"false":"true";case 0x02:return this.stream.parseInteger(content,content+len);case 0x03:return this.sub?"("+this.sub.length+" elem)":this.stream.parseBitString(content,content+len);case 0x04:return this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(content,content+len);case 0x06:return this.stream.parseOID(content,content+len);case 0x10:case 0x11:return"("+this.sub.length+" elem)";case 0x0C:return this.stream.parseStringUTF(content,content+len);case 0x12:case 0x13:case 0x14:case 0x15:case 0x16:case 0x1A:return this.stream.parseStringISO(content,content+len);case 0x1E:return this.stream.parseStringBMP(content,content+len);case 0x17:case 0x18:return this.stream.parseTime(content,content+len);}
return null;};ASN1.prototype.toString=function(){return this.typeName()+"@"+this.stream.pos+"[header:"+this.header+",length:"+this.length+",sub:"+((this.sub===null)?'null':this.sub.length)+"]";};ASN1.prototype.print=function(indent){if(indent===undefined)indent='';document.writeln(indent+this);if(this.sub!==null){indent+='  ';for(var i=0,max=this.sub.length;i<max;++i)
this.sub[i].print(indent);}};ASN1.prototype.toPrettyString=function(indent){if(indent===undefined)indent='';var s=indent+this.typeName()+" @"+this.stream.pos;if(this.length>=0)s+="+";s+=this.length;if(this.tag&0x20)s+=" (constructed)";else if(((this.tag==0x03)||(this.tag==0x04))&&(this.sub!==null))s+=" (encapsulates)";s+="\n";if(this.sub!==null){indent+='  ';for(var i=0,max=this.sub.length;i<max;++i)
s+=this.sub[i].toPrettyString(indent);}
return s;};ASN1.prototype.toDOM=function(){var node=DOM.tag("div","node");node.asn1=this;var head=DOM.tag("div","head");var s=this.typeName().replace(/_/g," ");head.innerHTML=s;var content=this.content();if(content!==null){content=String(content).replace(/</g,"&lt;");var preview=DOM.tag("span","preview");preview.appendChild(DOM.text(content));head.appendChild(preview);}
node.appendChild(head);this.node=node;this.head=head;var value=DOM.tag("div","value");s="Offset: "+this.stream.pos+"<br/>";s+="Length: "+this.header+"+";if(this.length>=0)s+=this.length;else s+=(-this.length)+" (undefined)";if(this.tag&0x20)s+="<br/>(constructed)";else if(((this.tag==0x03)||(this.tag==0x04))&&(this.sub!==null))s+="<br/>(encapsulates)";if(content!==null){s+="<br/>Value:<br/><b>"+content+"</b>";if((typeof oids==='object')&&(this.tag==0x06)){var oid=oids[content];if(oid){if(oid.d)s+="<br/>"+oid.d;if(oid.c)s+="<br/>"+oid.c;if(oid.w)s+="<br/>(warning!)";}}}
value.innerHTML=s;node.appendChild(value);var sub=DOM.tag("div","sub");if(this.sub!==null){for(var i=0,max=this.sub.length;i<max;++i)
sub.appendChild(this.sub[i].toDOM());}
node.appendChild(sub);head.onclick=function(){node.className=(node.className=="node collapsed")?"node":"node collapsed";};return node;};ASN1.prototype.posStart=function(){return this.stream.pos;};ASN1.prototype.posContent=function(){return this.stream.pos+this.header;};ASN1.prototype.posEnd=function(){return this.stream.pos+this.header+Math.abs(this.length);};ASN1.prototype.fakeHover=function(current){this.node.className+=" hover";if(current)this.head.className+=" hover";};ASN1.prototype.fakeOut=function(current){var re=/ ?hover/;this.node.className=this.node.className.replace(re,"");if(current)this.head.className=this.head.className.replace(re,"");};ASN1.prototype.toHexDOM_sub=function(node,className,stream,start,end){if(start>=end)return;var sub=DOM.tag("span",className);sub.appendChild(DOM.text(stream.hexDump(start,end)));node.appendChild(sub);};ASN1.prototype.toHexDOM=function(root){var node=DOM.tag("span","hex");if(root===undefined)root=node;this.head.hexNode=node;this.head.onmouseover=function(){this.hexNode.className="hexCurrent";};this.head.onmouseout=function(){this.hexNode.className="hex";};node.asn1=this;node.onmouseover=function(){var current=!root.selected;if(current){root.selected=this.asn1;this.className="hexCurrent";}
this.asn1.fakeHover(current);};node.onmouseout=function(){var current=(root.selected==this.asn1);this.asn1.fakeOut(current);if(current){root.selected=null;this.className="hex";}};this.toHexDOM_sub(node,"tag",this.stream,this.posStart(),this.posStart()+1);this.toHexDOM_sub(node,(this.length>=0)?"dlen":"ulen",this.stream,this.posStart()+1,this.posContent());if(this.sub===null)node.appendChild(DOM.text(this.stream.hexDump(this.posContent(),this.posEnd())));else if(this.sub.length>0){var first=this.sub[0];var last=this.sub[this.sub.length-1];this.toHexDOM_sub(node,"intro",this.stream,this.posContent(),first.posStart());for(var i=0,max=this.sub.length;i<max;++i)
node.appendChild(this.sub[i].toHexDOM(root));this.toHexDOM_sub(node,"outro",this.stream,last.posEnd(),this.posEnd());}
return node;};ASN1.prototype.toHexString=function(root){return this.stream.hexDump(this.posStart(),this.posEnd(),true);};ASN1.decodeLength=function(stream){var buf=stream.get(),len=buf&0x7F;if(len==buf)return len;if(len>3)throw"Length over 24 bits not supported at position "+(stream.pos-1);if(len===0)return-1;buf=0;for(var i=0;i<len;++i)
buf=(buf<<8)|stream.get();return buf;};ASN1.hasContent=function(tag,len,stream){if(tag&0x20)
return true;if((tag<0x03)||(tag>0x04))return false;var p=new Stream(stream);if(tag==0x03)p.get();var subTag=p.get();if((subTag>>6)&0x01)
return false;try{var subLength=ASN1.decodeLength(p);return((p.pos-stream.pos)+subLength==len);}catch(exception){return false;}};ASN1.decode=function(stream){if(!(stream instanceof Stream))stream=new Stream(stream,0);var streamStart=new Stream(stream),tag=stream.get(),len=ASN1.decodeLength(stream),header=stream.pos-streamStart.pos,sub=null;if(ASN1.hasContent(tag,len,stream)){var start=stream.pos;if(tag==0x03)stream.get();sub=[];if(len>=0){var end=start+len;while(stream.pos<end)
sub[sub.length]=ASN1.decode(stream);if(stream.pos!=end)throw"Content size is not correct for container starting at offset "+start;}else{try{for(;;){var s=ASN1.decode(stream);if(s.tag===0)break;sub[sub.length]=s;}
len=start-stream.pos;}catch(e){throw"Exception while decoding undefined length content: "+e;}}}else stream.pos+=len;return new ASN1(streamStart,header,len,tag,sub);};ASN1.test=function(){var test=[{value:[0x27],expected:0x27},{value:[0x81,0xC9],expected:0xC9},{value:[0x83,0xFE,0xDC,0xBA],expected:0xFEDCBA}];for(var i=0,max=test.length;i<max;++i){var pos=0,stream=new Stream(test[i].value,0),res=ASN1.decodeLength(stream);if(res!=test[i].expected)document.write("In test["+i+"] expected "+test[i].expected+" got "+res+"\n");}};window.ASN1=ASN1;})();ASN1.prototype.getHexStringValue=function(){var hexString=this.toHexString();var offset=this.header*2;var length=this.length*2;return hexString.substr(offset,length);};RSAKey.prototype.parseKey=function(pem){try{var reHex=/^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;var der=reHex.test(pem)?Hex.decode(pem):Base64.unarmor(pem);var asn1=ASN1.decode(der);if(asn1.sub.length===9){var modulus=asn1.sub[1].getHexStringValue();this.n=parseBigInt(modulus,16);var public_exponent=asn1.sub[2].getHexStringValue();this.e=parseInt(public_exponent,16);var private_exponent=asn1.sub[3].getHexStringValue();this.d=parseBigInt(private_exponent,16);var prime1=asn1.sub[4].getHexStringValue();this.p=parseBigInt(prime1,16);var prime2=asn1.sub[5].getHexStringValue();this.q=parseBigInt(prime2,16);var exponent1=asn1.sub[6].getHexStringValue();this.dmp1=parseBigInt(exponent1,16);var exponent2=asn1.sub[7].getHexStringValue();this.dmq1=parseBigInt(exponent2,16);var coefficient=asn1.sub[8].getHexStringValue();this.coeff=parseBigInt(coefficient,16);}else if(asn1.sub.length===2){var bit_string=asn1.sub[1];var sequence=bit_string.sub[0];var modulus=sequence.sub[0].getHexStringValue();this.n=parseBigInt(modulus,16);var public_exponent=sequence.sub[1].getHexStringValue();this.e=parseInt(public_exponent,16);}else{return false;}
return true;}catch(ex){return false;}};RSAKey.prototype.getPrivateBaseKey=function(){var options={'array':[new KJUR.asn1.DERInteger({'int':0}),new KJUR.asn1.DERInteger({'bigint':this.n}),new KJUR.asn1.DERInteger({'int':this.e}),new KJUR.asn1.DERInteger({'bigint':this.d}),new KJUR.asn1.DERInteger({'bigint':this.p}),new KJUR.asn1.DERInteger({'bigint':this.q}),new KJUR.asn1.DERInteger({'bigint':this.dmp1}),new KJUR.asn1.DERInteger({'bigint':this.dmq1}),new KJUR.asn1.DERInteger({'bigint':this.coeff})]};var seq=new KJUR.asn1.DERSequence(options);return seq.getEncodedHex();};RSAKey.prototype.getPrivateBaseKeyB64=function(){return hex2b64(this.getPrivateBaseKey());};RSAKey.prototype.getPublicBaseKey=function(){var options={'array':[new KJUR.asn1.DERObjectIdentifier({'oid':'1.2.840.113549.1.1.1'}),new KJUR.asn1.DERNull()]};var first_sequence=new KJUR.asn1.DERSequence(options);options={'array':[new KJUR.asn1.DERInteger({'bigint':this.n}),new KJUR.asn1.DERInteger({'int':this.e})]};var second_sequence=new KJUR.asn1.DERSequence(options);options={'hex':'00'+second_sequence.getEncodedHex()};var bit_string=new KJUR.asn1.DERBitString(options);options={'array':[first_sequence,bit_string]};var seq=new KJUR.asn1.DERSequence(options);return seq.getEncodedHex();};RSAKey.prototype.getPublicBaseKeyB64=function(){return hex2b64(this.getPublicBaseKey());};RSAKey.prototype.wordwrap=function(str,width){width=width||64;if(!str)return str;var regex='(.{1,'+width+'})( +|$\n?)|(.{1,'+width+'})';return str.match(RegExp(regex,'g')).join('\n');};RSAKey.prototype.getPrivateKey=function(){var key="-----BEGIN RSA PRIVATE KEY-----\n";key+=this.wordwrap(this.getPrivateBaseKeyB64())+"\n";key+="-----END RSA PRIVATE KEY-----";return key;};RSAKey.prototype.getPublicKey=function(){var key="-----BEGIN PUBLIC KEY-----\n";key+=this.wordwrap(this.getPublicBaseKeyB64())+"\n";key+="-----END PUBLIC KEY-----";return key;};RSAKey.prototype.hasPublicKeyProperty=function(obj){obj=obj||{};return obj.hasOwnProperty('n')&&obj.hasOwnProperty('e');};RSAKey.prototype.hasPrivateKeyProperty=function(obj){obj=obj||{};return obj.hasOwnProperty('n')&&obj.hasOwnProperty('e')&&obj.hasOwnProperty('d')&&obj.hasOwnProperty('p')&&obj.hasOwnProperty('q')&&obj.hasOwnProperty('dmp1')&&obj.hasOwnProperty('dmq1')&&obj.hasOwnProperty('coeff');};RSAKey.prototype.parsePropertiesFrom=function(obj){this.n=obj.n;this.e=obj.e;if(obj.hasOwnProperty('d')){this.d=obj.d;this.p=obj.p;this.q=obj.q;this.dmp1=obj.dmp1;this.dmq1=obj.dmq1;this.coeff=obj.coeff;}};var JSEncryptRSAKey=function(key){RSAKey.call(this);if(key){if(typeof key==='string'){this.parseKey(key);}else if(this.hasPrivateKeyProperty(key)||this.hasPublicKeyProperty(key)){this.parsePropertiesFrom(key);}}};JSEncryptRSAKey.prototype=new RSAKey();JSEncryptRSAKey.prototype.constructor=JSEncryptRSAKey;var JSEncrypt=function(options){options=options||{};this.default_key_size=parseInt(options.default_key_size)||1024;this.default_public_exponent=options.default_public_exponent||'010001';this.log=options.log||false;this.key=null;};JSEncrypt.prototype.setKey=function(key){if(this.log&&this.key)console.warn('A key was already set, overriding existing.');this.key=new JSEncryptRSAKey(key);};JSEncrypt.prototype.setPrivateKey=function(privkey){this.setKey(privkey);};JSEncrypt.prototype.setPublicKey=function(pubkey){this.setKey(pubkey);};JSEncrypt.prototype.decrypt=function(string){try{return this.getKey().decrypt(b64tohex(string));}catch(ex){return false;}};JSEncrypt.prototype.encrypt=function(string){try{return hex2b64(this.getKey().encrypt(string));}catch(ex){return false;}};JSEncrypt.prototype.getKey=function(cb){if(!this.key){this.key=new JSEncryptRSAKey();if(cb&&{}.toString.call(cb)==='[object Function]'){this.key.generateAsync(this.default_key_size,this.default_public_exponent,cb);return;}
this.key.generate(this.default_key_size,this.default_public_exponent);}
return this.key;};JSEncrypt.prototype.getPrivateKey=function(){return this.getKey().getPrivateKey();};JSEncrypt.prototype.getPrivateKeyB64=function(){return this.getKey().getPrivateBaseKeyB64();};JSEncrypt.prototype.getPublicKey=function(){return this.getKey().getPublicKey();};JSEncrypt.prototype.getPublicKeyB64=function(){return this.getKey().getPublicBaseKeyB64();};exports.JSEncrypt=JSEncrypt;})(JSEncryptExports);var JSEncrypt=JSEncryptExports.JSEncrypt;