// ? Niko-Niko Stars, released under the GPL
// http://www.gnu.org/copyleft/gpl.html
//
// ==UserScript==
// @name           Hatena Niko-Niko Stars
// @description    Display starred comments in a niko-niko style.
// @include        http://b.hatena.ne.jp/entry/*://*
// ==/UserScript==
//
// 2008-11-25 (v0.2) Added modifications to support the new site design (http://hatena.g.hatena.ne.jp/hatenabookmark/20081125/1227602284).
// 2008-03-01 (v0.1) Initial Version.

(function(){
  const comments = document.evaluate('/descendant::SPAN[@class="comment"]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  const contents = document.createExpression('text()', null);
  const outerNum = document.createExpression('count(../SPAN[@class="hatena-star-star-container"]/A[IMG[@class="hatena-star-star"]])', null);
  const innerNum = document.createExpression('number(../SPAN[@class="hatena-star-star-container"]/SPAN[@class="hatena-star-inner-count"]/text())', null);
  
  var layer = document.body.appendChild(document.createElement('DIV'));
  var stars = [];

  layer.style.position = 'fixed';
  layer.style.width = layer.style.height = '100%';
  layer.style.left = layer.style.top = '0';
  layer.style.fontSize = '5em';
  layer.style.whiteSpace = 'nowrap';
  layer.style.overflow = 'hidden';
  layer.style.opacity = '0.5';

  document.addEventListener('dblclick', function () {
    layer.style.display = layer.style.display != 'none' ? 'none' : 'block';
  }, false);
  
  setTimeout(function () {
    var v = [];
    for (var i = 0; i < comments.snapshotLength; ++i) {
      var e = comments.snapshotItem(i);
      var s = contents.evaluate(e, XPathResult.STRING_TYPE, null).stringValue;
      var n = parseInt(Math.sqrt((outerNum.evaluate(e, XPathResult.NUMBER_TYPE, null).numberValue || 0) + (innerNum.evaluate(e, XPathResult.NUMBER_TYPE, null).numberValue || 0)));
      while (--n >= 0) {
        v.push(s);
      }
    }
    stars = v;
    setTimeout(arguments.callee, Math.random() * 5000 + 2500);
  }, 5000);

  setTimeout(function () {
    if (stars.length > 0 && layer.childNodes.length < 4) {
      var e = stars[parseInt(Math.random() * stars.length)];
      var n = document.createElement('DIV');
      var s = n.style;
      n.appendChild(document.createTextNode(e));
      s.position = 'absolute';
      s.visibility = 'hidden';
      layer.appendChild(n);
      s.color = '#' + 'c00c0cc0'.substr(parseInt(Math.random() * 6), 3);
      s.left = layer.clientWidth + 'px';
      s.top = parseInt(Math.random() * (layer.clientHeight - n.offsetHeight)) + 'px';
      s.visibility = 'visible';
      setTimeout(function () {
        var x = parseInt(s.left) - 25;
        if (x + n.offsetWidth > 0) {
          setTimeout(arguments.callee, 50);
          s.left = x + 'px';
        }
        else {
          layer.removeChild(n);
        }
      }, 50);
    }
    setTimeout(arguments.callee, Math.random() * 5000 + 2500);
  }, 5000);
})()

