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

init();

top.onhashchange = init;

function init() {
  owner = (top.location.hash || '#').slice(1) ||
          top.document.querySelector('a.owner').textContent;
  var hash = '#'+ owner;
  if ((document.body.className = owner ? '' : 'help')) {
    d3.selectAll('.what li a')
      .attr('href', function() {
        return top.location.href.replace(/(#.*)?$/, this.hash);
      });
    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 not(fn) { return function() { return !fn.apply(this, arguments) }; }

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

function show(json) {
  gists = json.gists;

  draw('ul#list', blocks = gists.filter(is_block), 'http://bl.ocks.org/');
  draw('ul#gist', others = gists.filter(not(is_block)), 'https://gist.github.com/');

  var non = d3.selectAll('.nonblocks').style('display', 'none');
  if (!blocks.length) document.body.className = 'help';
  else if (others.length) non.style('display', 'inherit');

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

function draw(root, data, base_url) {
  var vis = d3.select(root).selectAll('li')
      .data(data)
    , 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 base_url + 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 || JSON.stringify(d.files); });
}