var owner  = '' // fetched from url hash
  , gists  = [] // all gists
  , blocks = [] // gists with an index.html file
  ;

top.onhashchange = init;

init();

function init() {
  owner = (top.location.hash || '#').slice(1) ||
          top.document.querySelector('a.owner').textContent;
  var hash = '#'+ owner;
  if ((document.body.className = owner ? '' : 'help'))
    return;
  if (top.location.hash != hash)
    top.location.hash = hash;

  d3.select('#user')
    .attr('href', 'https://gist.github.com/'+ owner)
    .text(owner);

  JSONP('http://gist.github.com/api/v1/json/gists/'+ owner, show);
}

function is_block(gist) {
  return -1 !== gist.files.indexOf('index.html');
}

function show(json) {
  gists = json.gists;
  var vis = d3.select('ul#list').selectAll('li')
      .data(blocks = gists.filter(is_block))
    , lis = vis.enter().append('li')
    , out = vis.exit().remove();

  lis.append('span')
    .attr('class', 'created_at')
    .text(function(d) { return d.created_at; });

  lis.append('a')
    .attr('target', function(d) { return 'bl_ock_'+ d.repo; })
    .attr('href', function(d) { return 'http://bl.ocks.org/'+ d.repo; })
    .attr('class', 'block')
    .classed('private', function(d) { return !d.public; })
    .text(function(d) { return d.repo; });

  lis.append('span')
    .classed('info', function(d) { return !!d.description; })
    .text(function(d) { return d.description || ''; });

  if (!blocks.length) document.body.className = 'help';

  d3.select(self.frameElement).style('height', document.body.offsetHeight +'px');
}