var width = 960,
    height = 500,
    radius = Math.min(width, height) / 2;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 1.9 + ") scale(1.1)");

var partition = d3.layout.partition()
    .size([2 * Math.PI, radius * radius])
    .value(function(d) { return d.size; });

var arc = d3.svg.arc()
    .startAngle(function(d) { return d.x; })
    .endAngle(function(d) { return d.x + d.dx; })
    .innerRadius(function(d) { return Math.sqrt(d.y); })
    .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

var text = svg.append("text")
            .attr("x", 0)
            .attr("y", 0)
            .attr("dy", "0.35em");

getColor = function(d) {
    var flag;
    if (d.name === "owl:Thing") {
      return '#7E7F7E';
    } else if (d.name in colors) {
      return colors[d.name];
    } else {
      flag = '#7E7F7E';
      while (d.parent.name !== "owl:Thing") {
        if (d.parent.name in colors) {
          flag = colors[d.parent.name];
          break;
        } else {
          d = d.parent;
        }
      }
      return flag;
    }
  };

visitTree = function(node) {
  total_size = 0;
  
  if (node.children) {
 
    node.children.forEach(function(child) {
      total_size += visitTree(child);
    }); 
  } else {
    return node.size;
  }
  
  return total_size;
};

d3.json("http://wafi.iit.cnr.it/webvis/tmp/clavius/ontologyTree2.json", function(error, root) {
  
  root.size = visitTree(root);
  root = {"name": root.name, "size": root.size, "children": [root]};
  
  function mouseover(d) {
    var percentage = (100 * visitTree(d) / root.size).toPrecision(3);
    text.html("<tspan style='font-size: 30px' x=0 dy='-20'>" + visitTree(d) + "</tspan><tspan style='font-size: 15px' x=0 dy='25'>" + d.name + "</tspan><tspan style='font-size: 30px' x=0 dy='35'>" + percentage + "%</tspan>");
    
    d3.selectAll("path")
      .filter(function(d1) {
                return d === d1;
              })
      .style("opacity", 0.75);
  }
  
  function mouseout(d) {
    text.html("");
    
    d3.selectAll("path")
      .filter(function(d1) {
                return d === d1;
              })
      .style("opacity", function(d) { return d.children ? 0.5 : 1; });
  }
  
  var path = svg.datum(root).selectAll("path")
      .data(partition.nodes)
    .enter().append("path")
      .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
      .attr("d", arc)
      .style("stroke", "#fff")
      .style("fill", function(d) { return "steelblue"; })
      .style("opacity", function(d) { return d.children ? 0.5 : 1; })
      .on("mouseover", mouseover)
      .on("mouseout", mouseout);
});