// ==UserScript==
// @name					deviantEXPERIENCE:RainDrop
// @namespace				http://dancewiththesky.deviantart.com
// @description				Enhances the statistics section on deviantART by adding weighted lists
// @include					http://*.deviantart.com/stats/gallery/*
// @x-pkg-guid				{b7400dc5-2077-4d79-a9ea-5f24f6a06259}
// @x-pkg-version			0.2.0.3
// ==/UserScript==

/* ==UpdateInfo==

	0.2.0.3: New update URL.
	0.2.0.2: Fixed bugs. Migrated to ChickenFillet and became compatible with Firefox 3.
	0.2: Added two cloud types reflecting the "impact" of the deviation (suggested by ~beyond-frames).


   ==/UpdateInfo== */

(function(){

  const confMinFontSize = GM_getOrSet('minFontSize', 8);
  const confMaxFontSize = GM_getOrSet('maxFontSize', 40);

  //// LIBRARY FUNCTIONS ///////////////////////////////////////////////////

  // A prototype-style getElementById
  function $(id){
    return document.getElementById(id);
  }

  // Exectues an XPath query and returns the _first_ item
  function $xp(path){
    var result = document.evaluate(path, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    return result? result.snapshotItem(0) : null;
  }

  // Gets a configurable variable 
  // If it doesn't exist, it will set a specified default value 
  function GM_getOrSet(key, def){
    if (GM_getValue(key) == undefined){
        GM_setValue(key, def);
        return def;
    } else {
        return GM_getValue(key);
    }
  }

  /////////////////////////////////////////////////////////////////////////// 

  function setup(){
    var style = document.createElement('style');
    style.innerHTML = "#gallerystats-clouds{  display: none } #gallerystats-clouds.active { display: block } #__raindrop-cloud a:hover {text-decoration: none; background-color: #2C3635; color: #BBC2BB}";
	document.body.appendChild(style);

	$('gallerystats-tabs').innerHTML += "<a onclick=\"Tree2.giveClass(Tree.get('#gallerystats-tabs'), this, 'active'); Tree2.giveClass(Tree.get('#gallery-stats'), Tree.get('#gallerystats-clouds'), 'active'); cancelEvent(); return false;\" href=\"#gallerystats-clouds\">Clouds</a>"

    var cloudsDiv = document.createElement('div');
    cloudsDiv.id = 'gallerystats-clouds';
    cloudsDiv.innerHTML = "<h3>Clouds</h3><div><div style='float: right'>Cloud of <select id='__raindrop-select'>\
        <option value='views' selected>Views</option>\
        <option value='favourites'>Favourites</option>\
        <option value='fullviews'>Downloads (Full Views?)</option>\
        <option value='comments'>Comments</option>\
        <option value='impact-favourites'>Impact: Favourites % Views</option>\
        <option value='impact-comments'>Impact: Comments % Views</option>\
    </select><br /></div><div id='__raindrop-cloud' style='padding: 40px'></div></div>";
	
	var slidesDiv = $('gallery-stats');
    var lastDiv   = $xp('//div[@id="gallery-stats"]/div[@style="clear: both;"]');
    slidesDiv.insertBefore(cloudsDiv, lastDiv);

    $('__raindrop-select').addEventListener('change', function(e){
        renderDeviationCloud(e.target.value);
    }, false);

    renderDeviationCloud($('__raindrop-select').value);
  }


  function renderDeviationCloud(property){
    var devs = unsafeWindow.GalleryFeed.deviations
    var min, max, fix = null;
    var code = '';
    var impactElements;
    
    if (property.indexOf("impact") != -1){
        impactElements = property.split('-');
    }
    
    for(var i = 0; i < devs.length; i++){
      if (devs[i]["category"] != "Scraps"){
        var value = impactElements? getImpact(i, impactElements[1]) : devs[i][property]; 
        max = (value > max || max == null)? value : max;
        min = (value < min || min == null)? value : min;
      }
    } 

    var fix = max - min == 0? 1 : max - min;

    for(var i = 0; i < devs.length; i++){
      if (devs[i]["category"] != "Scraps"){
        var value = impactElements? getImpact(i, impactElements[1]) : devs[i][property];
        var ratio = (1 - (max - value) / fix);
        var fontSize = confMinFontSize + (ratio * (confMaxFontSize - confMinFontSize)) ;
        
        if (impactElements){
            value = "~ " + (value * 100).toFixed() + "%";
        }

        code += "<a href='http://www.deviantart.com/deviation/" + 
              + devs[i]["id"] + "/' class='cloud' style='padding: 0 4px; font-size: " + fontSize 
              + "px' onmouseover=\"fn_Hover_setup(this, " +  devs[i]["id"]  + ")\">" 
              + devs[i]["title"] + "</a> ";
      } 
    } 

    $('__raindrop-cloud').innerHTML = code;
  }

  function getImpact(i, forProperty){
        var devs = unsafeWindow.GalleryFeed.deviations;

        if (devs[i]['views'] == 0){
            return 0;
        }

        var impact = devs[i][forProperty] / devs[i]['views'];
        return impact;
  }


  unsafeWindow.addEventListener('load', setup, false);
})();