// ==UserScript==
// @name          SocialMonkey
// @namespace     http://www.mapelli.info/
// @description   display number of diggs, del.icio.us bookmarks and technorati links for each reddit story
// @include http://*.reddit.com/*
// @include http://reddit.com/*
// ==/UserScript==

//socialmonkey 1.0
//guid: {3294d9f7-0f92-4637-a9a0-5d74d7a0cd4a}

/**
 * hello! this code is horrible, but it's my first javascript product... if you
 * find something orrible, ar you wanna help with the code, or you want to give 
 * feedbaks or request features etc, please write at francesco@mapelli.info or
 * leave a comment at www.mapelli.info/socialmonkey
 * 
 * thanks!
 *      
 **/ 
var allA;
var i;
var id;
var theDiv=new Array();
var theLink=new Array();

/* getting all the titles */
allA = document.evaluate(
    "//a[(@class='title' or @class='title loggedin' or @class='title loggedin click')]",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

/* cycle the titles */
for (i = 0; i < allA.snapshotLength; i++) {
    thisA = allA.snapshotItem(i);
    theDiv[i]=document.createElement("div");
    theDiv[i].setAttribute("class", "little");
    theLink[i]=document.createElement("a");
    theLink[i].setAttribute("href",'javascript:{}');
    theLink[i].setAttribute("id","SocialMonkey-"+i);
    theLink[i].addEventListener('click',releaseMonkeys , true);
    theLink[i].textContent="[Release the Monkeys]";
    theDiv[i].appendChild(theLink[i]);
// search for the no-points stories    
    if (thisA.rel=="nofollow")
      theDiv[i].appendChild(document.createTextNode(' | no points '));
    else
      theDiv[i].appendChild(document.createTextNode(' '));
      
	  thisA.parentNode.insertBefore(theDiv[i], thisA);
  

}

//called on click events
function releaseMonkeys(e) {
  
  //ids will help us finding the correct div to modify
  pieces = this.id.split("-");
  i=pieces[1];
  
  theLink[i].textContent="Monkeys are out!";
  theLink[i].removeEventListener('click', releaseMonkeys, true);
  a= allA.snapshotItem(i);
  //release the monkeys!
  httpGetDelicious(a, theDiv[i]) ;
  httpGetDigg(a, theDiv[i]) ;
  httpGetTechnorati(a,theDiv[i]);  
}

//this fetch technnorati
function httpGetTechnorati(a, item) {
  GM_xmlhttpRequest({
      method: 'GET',
      url: getTechnoratiAddress(a),
      headers: {
          'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
         'Accept': 'application/atom+xml,application/xml,text/xml',
      },
      //when the page as been loaded we want to get the numbers and add the span
      //to the right item
      onload: function(responseDetails) {
       del= createTechnoratiSpan(getTechnoratiAddress(a),parseTechnoratiRequest(responseDetails.responseText) );
       item.appendChild(del); 
        }
  });
}

//parse request
function parseTechnoratiRequest(text) {
  if ( 
  (text.indexOf('There are no posts that contain that text.') != -1)
  || text.indexOf('No posts link to that')!=-1)
  return "0";

  var pos = text.indexOf('links to this URL');
  if (pos>0) {
    text=text.substr(0,pos);
    text=text.substr(text.lastIndexOf("<h2>"),pos);
    pieces=text.split("<h2>");
    
    return pieces[1];
  }
  else {
    pos = text.indexOf('link to this URL');
    if (pos>0)
      return '1';
    else 
      return '0';
  }
}

// returns the technorati address
function getTechnoratiAddress(a) {
  return "http://technorati.com/search/" +escape(a.href) ;
}

//create a span element with given informations
function createTechnoratiSpan(theAddress, num) {
  span=document.createElement("span");
  span.setAttribute("class", "little");
  a=document.createElement("a");
  a.setAttribute("href", theAddress);
  a.textContent="Technorati";
  span.appendChild(document.createTextNode(" | "));
  span.appendChild(a);
  span.appendChild(document.createTextNode(":"+num+" "));
  return span;
}

//get the delicious page
function httpGetDelicious(a, item) {
  GM_xmlhttpRequest({
      method: 'GET',
      url: getDeliciousAddress(a),
      headers: {
          'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
         'Accept': 'application/atom+xml,application/xml,text/xml',
      },
      onload: function(responseDetails) {
       del= createDeliciousSpan(getDeliciousAddress(a),parseDeliciousRequest(responseDetails.responseText) );
       item.appendChild(del); 
        }
});
}

//get the digg page
function httpGetDigg(a, item) {

  GM_xmlhttpRequest({
      method: 'GET',
      url: getDiggAddress(a),
      headers: {
          'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
         'Accept': 'application/atom+xml,application/xml,text/xml',
      },
      onload: function(responseDetails) {
       del= createDiggSpan(getDiggAddress(a),parseDiggRequest(responseDetails.responseText) );
       item.appendChild(del);
        
        }
  });
}
 
//get the digg address 
function getDiggAddress(a) {
  return  "http://digg.com/search?s="+escape(a.href)+"&submit=Search&section=news&type=url&area=all&age=all&sort=new"
}
 //create the dig span 
 //(not "spam", the diggers are good at creating spam, they do not need my help)
function createDiggSpan(theAddress, num) {
  span=document.createElement("span");
  span.setAttribute("class", "little");
  a=document.createElement("a");
  a.setAttribute("href", theAddress);
  a.textContent="Digg";
  span.appendChild(document.createTextNode(" | "));
  span.appendChild(a);
  span.appendChild(document.createTextNode(":"+num+" "));
  return span;
}
 
 //create delicious span
function createDeliciousSpan(theAddress, num) {
  span=document.createElement("span");
  span.setAttribute("class", "little");
  a=document.createElement("a");
  a.setAttribute("href", theAddress);
  a.textContent="Del"
  span.appendChild(document.createTextNode(" | "));
  span.appendChild(a);
  span.appendChild(document.createTextNode(":"+num+" "));
  return span;
}

//parse the digg request
function parseDiggRequest (text)  {
  if (text.indexOf('No results Found') == -1) {
    var pieces = text.split('<strong id="diggs-strong-0">');
    if (pieces.length > 1) {
      pieces = pieces[1].split('<');
      return pieces[0];
    }
  } else {
    return '0';
  }
  return '-';
}


//parse the delicious request
function parseDeliciousRequest (text)  {
  if (text.indexOf('There is no del.icio.us history for this url') != -1)
    return "0";
  var pieces = text.split('this url has been saved by ');
  if (pieces.length > 1) {
    pieces = pieces[1].split(' ');
    return pieces[0];
  }
  else {
    return '-';
  }
}
//get the delicious address
function getDeliciousAddress (a) {
  return "http://del.icio.us/url/check?url=" + escape(a.href) + "&submit=check%20url";
} 
