// ==UserScript==
// @name           fb phonebook
// @namespace      setfivefb
// @description    Extract name/phonenumber from fb phonebook. Navigate to http://m.facebook.com/friends.php? and switch the tab to "Phonebook". The script will extract your friends' name/phone and present a CSV at the end.
// @include        http://m.facebook.com/friends.php?
// ==/UserScript==


// lets make sure we are actually looking at a phonebook page
var nodesSnapshot = document.evaluate('//div[@class="nopad"]/div[@class="lnav header"]/small', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
var desc = nodesSnapshot.snapshotItem(0).childNodes;

for(var i=0; i < desc.length; i++){
  // figure out what page we are on
  if(desc[i].nodeName == "B" && desc[i].firstChild.textContent != "Phonebook"){
    return;
  }
}

// get the pagination link
var allLinks = document.getElementsByTagName("a");
var nextLink = "";

nodesSnapshot = document.evaluate('//div[@class="pager"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
var pagerLinks = nodesSnapshot.snapshotItem(0).childNodes;

// get the stuff back from the cache
var arr = GM_getValue("setfivefb");
if(arr == null){
  arr = new Array();
}else{
  arr = new String(arr).split("^");
}

// we are on the first page so reset our name/phone cache
// and present a conformation dialog
if( new String(pagerLinks[0].nodeName) == "#text" ){
  arr = new Array();
  var res = confirm("Do you want to extract your phonebook?");
  if(!res)
    return;
}

for(var i=0; i < pagerLinks.length; i++){
  
  if(pagerLinks[i].innerHTML == "Next"){
    nextLink = "http://m.facebook.com" + new String(pagerLinks[i].getAttribute("href"));
    break;
  }
}

// grab all the names+phones off the page
nodesSnapshot = document.evaluate('//table[@class="results"]//tr', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
var obj;
var ns;
var t;
var hasMatch = false;

for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
{
  ns = nodesSnapshot.snapshotItem(i).childNodes[1].childNodes;
  obj = new String();
  hasMatch = false;
  
  for(var j=0; j < ns.length; j++){
    
    t = new String(ns[j].textContent);
    if(t.length > 0){
      
      if(t.indexOf(":") != -1 && ns[j].childNodes[1] && !hasMatch){
        obj += "," + ns[j].childNodes[1].textContent;
        hasMatch = true;
      }else{
        obj = t;  
      }
      
    }
  }
  
  if(obj.indexOf(",") == -1)
    obj += ",NaN";
  
  arr.push(obj);
}

// throw the array into our temporary storage spot and push the page forward
GM_setValue("setfivefb", arr.join("^"));

if(nextLink != "")
  window.location = nextLink;
else{
  // display the results of this mess somewhere
  var str = new Array();
  var tmp;
  
  for(var i=0; i < arr.length; i++){
    str.push(arr[i]);
  }
  
  document.body.innerHTML = str.join("<br/>");
}
