// ==UserScript==
// @name           finetoothcog graph
// @namespace      http://overheard.org
// @description    pull the event data & show a graph
// @include        http://finetoothcog.com
// ==/UserScript==

// This greasemonkey script pulls information from the stolen bike listing 
// at finetoothcog.com and displays a small frequency distribution by date. 
// Data is extracted using the event microformat on those pages.

// Try it here:
// http://www.finetoothcog.com/site/stolen_bikes_top_100
// http://www.finetoothcog.com/site/stolen_bikes

var bodyTag;  
var dateTags = [];
var dateList = [];
var dateCount = new Object;

// output stores the HTML for our graph
var output='<span style="font-size: 10px">FREQUENCY:</span>';

// The date tags in the document have a class of "dtstart" (part of the event microformat)
dateTags = document.evaluate(
    "//*[contains(@class, 'dtstart')]",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

// Create an array of dates & frequencies, along with a list of dates that are present
for (var i = 0; i < dateTags.snapshotLength; i++) {
  var thisDate = dateTags.snapshotItem(i).title;
  if (dateCount[thisDate]) {
    dateCount[thisDate]++;
  } else {
    dateCount[thisDate]=1; 
    dateList.push(thisDate);
  }
}

// Build the output
for (var i = 0; i < dateList.length; i++){
  output += convertCountToBar(dateList[i], dateCount[dateList[i]]);
}

// Insert our HTML into a new DIV on the page
if (bodyTag = document.getElementById('type-a')) {
  var graphDiv = document.createElement('div');
  graphDiv.setAttribute("id", "graphDiv");
  graphDiv.setAttribute("style", "position: absolute; top: 14em; right:1em; text-align: right; font-size: 7px;");  
  graphDiv.innerHTML = output;
  bodyTag.insertBefore(graphDiv, bodyTag.nextSibling);
}

function convertCountToBar(date, int) {
  var scale = 30;
  var baseOpacity = .3;
  date = date.substr(5); // Don't show the year
  
  return '<span style="float: right; clear:both;width: '+(int*scale)+'px; height: 10px; background-color: #c00; display:block; margin:1px 0; color: white; -moz-opacity: '+(baseOpacity+int/10)+';" title="'+date+': '+int+' report(s)">'+date+'</span>';
}


