var height = 500;
var width = 900;

var data = [];
var grid_spacing = 100;
var h = 75; //Cut off distance is the bandwidth for this type of kernel

for(var i = 0; i < 50; i++){
  data.push([Math.random()*width, Math.random()*height]);
}

var svg = d3.select("#chartArea") //Uniform Kernel
  .append("svg")
  .attr("width", width)
  .attr("height", height);

svg.selectAll('circle')
	.data(data).enter()
	.append('circle')
	.attr('cx', function(d) { return d[0]; })
	.attr('cy', function(d) { return d[1]; })
	.attr('r', 5)

for(var wi = 0; wi <= width; wi+=grid_spacing){
  svg.append('line')
    .style('stroke', 'black')
    .attr('x1', wi)
    .attr('x2', wi)
    .attr('y1', 0)
    .attr('y2', height)
}
for(var hi = 0; hi <= height; hi+=grid_spacing){
  svg.append('line')
    .style('stroke', 'black')
    .attr('x1', 0)
    .attr('x2', width)
    .attr('y1', hi)
    .attr('y2', hi)
}

for(var x_i = 0; x_i <= width; x_i += grid_spacing){
  for(var y_i = 0; y_i <= height; y_i += grid_spacing){
    var summation = 0;
    for(var i = 0; i < data.length; i++){
      //Calculate Eulicidean distance
      distance = Math.sqrt(Math.pow((x_i - data[i][0]),2) + Math.pow((y_i - data[i][1]),2))
      if(distance < h)
        summation++
    }
    //Shows the extent of the h
    svg.append('circle')
      .classed('h', true)
      .style('fill', 'none')
      .style('stroke', 'none')
      .attr('cx', x_i)
      .attr('cy', y_i)
      .attr('r', h)

    var lambda = 1/(Math.PI*h^2) * summation;
    if(lambda > 0){
      svg.append('circle')
        .style('fill', 'none')
        .style('stroke', 'maroon')
        .attr('cx', x_i)
        .attr('cy', y_i)
        .attr('r', lambda*1000)
    }
  }
}

d3.select("#show-h")
  .property("disabled", false)
  .on("change", function() { 
    var currentColour = d3.selectAll('.h').style('stroke');
    var nextColour = currentColour === 'rgb(28, 255, 152)' ? 'none' : 'rgb(28, 255, 152)';
    d3.selectAll('.h').style('stroke', nextColour);
  });