// ==UserScript==

// @name            DeviantArt Emoticons
// @author          Bruno Torres <http://www.brunotorres.net/>
// @namespace       http://www.brunotorres.net/greasemonkey/
// @description     Shows emoticons legend on a div inside the page instead of a pop up
// @include         http://*.deviantart.com/*

// ==/UserScript==

(function() {
  var dl = document.getElementsByTagName('dl');
  var body = document.getElementById('body');
  var style = document.getElementsByTagName('style')[0];
  var divs = document.getElementsByTagName('div');
  for (i=0; i<divs.length; i++)
  {
    if (divs[i].className == 'column2')
    {
      var col2 = divs[i];
    }
  }
  for (i=0; i<dl.length; i++)
  {
    if (dl[i].className == 'simple')
    {
      var iconsLink = dl[i].childNodes[dl[i].childNodes.length-2].childNodes[0];
      if (iconsLink.href.match("emoticons"))
      {
        iconsLink.onclick = function(){
          var reply = document.getElementById('reply');
          var load = document.createElement('div');
          load.id = 'loading';
          load.innerHTML = 'Loading...';
          load.style.background = 'red';
          load.style.padding = '10px';
          load.style.border = '1px solid #000';
          load.style.zIndex = '1000';
          load.style.color = '#fff';
          load.style.position = 'absolute';
          load.style.marginTop = (reply.clientHeight / 2) + 'px';
          load.style.marginLeft = '-25px';
          col2.insertBefore(load, reply);
          GM_xmlhttpRequest({
            method: 'GET',
            url: 'http://comments.deviantart.com/emoticons',
            headers: {
              'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey'
            },
            onload: function(responseDetails) {
              if (responseDetails.readyState == 4)
              {
                var icons = responseDetails.responseText;
                ul = icons.match(/<ul class="beacon emoticons">((?:.|[\r\n])*?)<\/ul>/)[1];
                div = document.createElement('div');
                div.id = 'emoticons';
                div.innerHTML += '<ul class="beacon emoticons">'+ul+'</ul>';
                var head = document.getElementById('head');
                col2.insertBefore(div, reply);
                load.style.display = 'none';
                var emoticons = document.getElementById('emoticons');
                emoticons.style.height = (reply.clientHeight - 3) + 'px';
                emoticons.style.position = 'absolute';
                emoticons.style.right = (reply.clientWidth + 20) + 'px';
                emoticons.style.marginTop = '18px';
                emoticons.style.overflow = 'auto';
                emoticons.style.border = '1px solid #000';
                style.innerHTML += '.ext: float:right;';
              }
            }
          });
          return false;
        }
      }
    }
  }
})();
