       renderLegend(scope, valFn)
 
 
+
+  #    #############################################
+  #      Legend Rendering
+  #    #############################################
+
   renderLegend = (scope, valFn) ->
     # reset current legend
     scope.legend.selectAll('li.key')

    isCategorical = mapInstance.getValueType() == 'categorical'

    if isCategorical
      renderCategoricalLegend(scope, valFn, mapInstance)
    else
      renderNumericalLegend(scope, valFn, mapInstance)


  renderNumericalLegend = (scope, valFn, mapInstance) ->
    data = valFn.range()

    scope.legend.selectAll('li.key')
        .data(data)
      .enter().append('li')
        .attr('class', 'key')
        .text( (d, index) ->
          extent = valFn.invertExtent(d)
          "#{Math.round(10*extent[0])/10} – #{Math.round(10*extent[1])/10}"
        )
      .append('svg')
        .attr('height', 30)
      .append('rect')

        .attr('height', 10)
        .attr('y', 10)
        .attr('x', (d, index) -> $(this).outerWidth() * index)
        .attr('class', (d) -> classFn(d) )


  filterDataForCategoricalLegend = (mapInstance, valFn) ->
    data = []
    dataUsed = mapInstance.usedDataValues
    for entry, index in valFn.range()
      category = valFn.domain()[index]
      if dataUsed.indexOf(category) != -1
        data.push
          key: entry
          value: category
    data


  # Stop progress bar with a timeout to prevent running conditions
