var api_key = '6ae48b05eba4d41a4fad61eb9f8fe8d3';
var channel_path = 'channel';
var fields2titles = [];
var fields = ['profile_url'];

function debug(s) {
  document.getElementById('_debug').innerHTML = s;
}

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

function showHistogram(title,key,infos,f) {
  //
  // Show the link and heading
  //
  var div   = document.getElementById('results');
  var links = document.getElementById('links');
  var a = $n('a',div);
  a.name = key;
  var link = $n('a',links);
  link.href = '#' + key;
  link.innerHTML = title;
  $n('br',links);

  var head = $n('h3',div);
  head.innerHTML = title + ' [<a href="#top">top</a>]';
  //
  // Create the histogram
  //
  var values2counts = [];
  var cnt = 0;
  for (var i=0; i<infos.length; i++) {
    var info  = infos[i];
    var value = info[key];
    if (f) value = f(value); 
    if (value) {
      var count = values2counts[value];
      if (!count) count = 0;
      count += 1;
      values2counts[value] = count;
    }
  }
  //
  // Show the histogram
  //
  var tab = $n('table',$n('blockquote',div));
  tab.style.border = '0';
  for (var value in values2counts) {
    var tr = $n('tr',tab);
    var td;
   
    td = $n('td',tr);
    td.align = 'right';
    td.innerHTML = value;

    var count = values2counts[value];

    td = $n('td',tr);
    td.align = 'right';
    td.innerHTML = '(' + count + ')';
    
    td = $n('td',tr);
    td.align = 'left';
    for (var i=0; i<count; i++) td.innerHTML += '|';
  }
  
}

function seeking(value) {
  return value ? value['seeking'] : null;
}

function displayResults(infos) {
  var url = 'http://jeffpalm.com/facebookfriends/results.php#';
  for (var i=0; i<infos.length; i++) {
    var uid = infos[i]['uid'];
    if (i>0) url += ',';
    url += uid;
  }
  document.location = url;
}

function showStats() {

  if (document.getElementById('links')) {
		document.getElementById('links').innerHTML = '';
	}
  if (document.getElementById('resultsWrapper')) {
		document.getElementById('resultsWrapper').innerHTML = '';
	}
    
  FB_RequireFeatures(["Api"], function(){
      FB.Facebook.init(api_key, channel_path);
      var api = FB.Facebook.apiClient;
      api.requireLogin(function(exception){
          debug("Current user id is " + api.get_session().uid);
          api.friends_get(null, function(uids){  
              api.users_getInfo(uids,fields,function(infos) {
                  displayResults(infos);
                });
            });
        });
    });

}

