/* 
 * Copyright 2009 Jeffrey Palm.
 */

function note(s) {
  $('_debug').innerHTML = s;
}

function $n(tag,onto) {
  var node = document.createElement(tag);
  if (onto) onto.appendChild(node);
  return node;
}

function $t(text,onto) {
  var node = document.createTextNode(text);
  if (onto) onto.appendChild(node);
  return node;
}

function url(page) {
  //return '/~jeff/twitterfriends/' + page;
  return '/twitterfriends/' + page;
}

function showResults() {
  var id1 = $('id1').value;
  var id2 = $('id2').value;
  if (id1 && id2) {
    compareIds(id1,id2);
  } else if (id1) {
    showId(id1);
  } else {
    showId(id2);
  }
}

/** 
 * Shows friends in common between the two ids. 
 */
function compareIds(id1,id2) {
  clearResults();
  //
  // First find your friends
  //
  new Ajax.Request(url('friends.php'),{
    method:'get',
        onSuccess: function(transport){
        var doc = transport.responseXML.documentElement;
        var ids = doc.getElementsByTagName('id');
        var userIds = [];
        for (var i=0; i<ids.length; i++) {
          userIds.push(parseInt(ids[i].firstChild.nodeValue));
        }
        //
        // Now find the second set of friends
        //
        new Ajax.Request(url('friends.php'),{
          method:'get',
              onSuccess: function(transport){
              var doc = transport.responseXML.documentElement;
              var ids = doc.getElementsByTagName('id');
              var user2Ids = [];
              for (var i=0; i<ids.length; i++) {
                user2Ids.push(parseInt(ids[i].firstChild.nodeValue));
              }
              showIntersection(userIds,user2Ids);
            },
              parameters: {user:id2}
          });  
      },
        parameters: {user:id1}
  });  
}

function showIntersection(userIds,user2Ids) {
  var target = $('resultsWrapper');
  var intersection = findIntersection(userIds,user2Ids);
  for (var i=0; i<intersection.length; i++) {
    new Ajax.Request(url('users_show.php'),{
      method:'get',
          onSuccess: function(transport){
          var doc = transport.responseXML.documentElement;
          var name = nodeValue(doc,'name');
          var screenName = nodeValue(doc,'screen_name');
          var imageURL = nodeValue(doc,'profile_image_url');
          var a = $n('a',target);
          a.style.border = '0px';
          var url = 'http://www.twitter.com/' + screenName;
          a.href = url;
          var img = $n('img',a);
          img.src = imageURL;
        },
        parameters: {id:intersection[i]}
      });    
  }
}

function clearResults() {
  currentNum = 0;
  names2counts = new Array();
  $('resultsWrapper').innerHTML = '';
}

function nodeValue(doc,nodeName) {
  return doc.getElementsByTagName(nodeName)[0].firstChild.nodeValue;
}

/**
 * @param user user in question
 * @param userIds user's friend ids
 * @param id2 other user
 * @param tab table in which to add results
 */
function addRow(user,userIds,id2,tab) {
  new Ajax.Request(url('users_show.php'),{
    method:'get',
        onSuccess: function(transport){
        var doc = transport.responseXML.documentElement;
        var name = nodeValue(doc,'name');
        var screenName = nodeValue(doc,'screen_name');
        var imageURL = nodeValue(doc,'profile_image_url');
        addRowRest(user,userIds,id2,tab,name,screenName,imageURL);
      },
        parameters: {id:id2}
    });
}

function findIntersection(userIds,user2Ids) {
  var ids2true = new Hash();
  for (var i=0; i<userIds.length; i++) {
    var userId = userIds[i];
    for (var j=0; j<user2Ids.length; j++) {
      if (userId == user2Ids[j]) {
        ids2true.set(userId,true);
        break;
      }
    }
  }
  for (var i=0; i<user2Ids.length; i++) {
    var userId = user2Ids[i];
    for (var j=0; j<userIds.length; j++) {
      if (userId == userIds[j]) {
        ids2true.set(userId,true);
        break;
      }
    }
  }
  return ids2true.keys();
}

function addRowRest(user,userIds,id2,tab,name,screenName,imageURL) {
  new Ajax.Request(url('friends.php'),{
    method:'get',
        onSuccess: function(transport){
        var doc = transport.responseXML.documentElement;
        var ids = doc.getElementsByTagName('id');
        var user2Ids = [];
        for (var i=0; i<ids.length; i++) {
          user2Ids.push(ids[i].firstChild.nodeValue);
        }
        //
        // Find the intersection of userIds and user2Ids
        //
        var intersection = findIntersection(userIds,user2Ids);
        var total = user2Ids.length;
        var count = intersection.length;
        var totalNumFriends = userIds.length;
       
        var tr = $n('tr',tab);
        var td;
        
        td = $n('td',tr);
        var url = 'http://www.twitter.com/' + screenName;
        td.innerHTML = '<a target="_" href="' + url + '">' + name + '</a>';
        
        td = $n('td',tr);
        td.innerHTML = total;
        
        td = $n('td',tr);
        td.innerHTML = count;
        
        td = $n('td',tr);
        td.innerHTML = Math.floor(100.0 * count / total) + '%';
        
        td = $n('td',tr);
        td.innerHTML = Math.floor(100.0 * count / totalNumFriends) + '%';
      },
        parameters: {id:id2}
  });
}
/** 
 * Makes a chart showing the similarities between the user with 'id'
 * and the rest of this person's friends. 
 */
function showId(id) {
  clearResults();
  var tab = $n('table',$('resultsWrapper'));
  var tr = $n('tr',tab);
  function addTH(width,text) {
    var th = $n('th',tr);
    th.width = width + 'px';
    th.innerHTML = text;
  }
  addTH(120,'Friend');
  addTH(80,'Total');
  addTH(80,'Common<br/>Friends');
  addTH(80,'% Their\'s<br/>in Common');
  addTH(80,'% Yours<br/>in Common');
  new Ajax.Request(url('friends.php'),{
    method:'get',
        onSuccess: function(transport){
        var doc = transport.responseXML.documentElement;
        var ids = doc.getElementsByTagName('id');
        var userIds = [];
        for (var i=0; i<ids.length; i++) {
          userIds.push(parseInt(ids[i].firstChild.nodeValue));
        }
        for (var i=0; i<userIds.length; i++) {
          addRow(id,userIds,userIds[i],tab);
        }
      },
        parameters: {user:id}
  });

}

