//<![CDATA[ 
var name; //global array mapping uids to real names
function chron(a,b){  //comparison function that allows content to be sorted
  return b.time-a.time;
}

//This really should be done via hashtable not array traversal but if you're reading it hasn't (yet?)
function getName(uid){
  var i=0;
  for(;name[i].uid!=uid;i++);
  return name[i].name;
}

//Hypothtically would replace statuses with text of url to actual link
function repURL(stat){ // this should work (tested on a regex test site) yet breaks the widget...
  //return stat.replace(/(^.*)(http://\S*)(.*$)/g,'$1<a href="$2" target="_blank">$2</a>$3');
  return stat;
}

//converts time (seconds) since content item occured to human readable amount of time
function timeToText(time){
  var days=Math.floor(time/86400);
  var hours=Math.floor(time/3600)%24;
  var min=Math.floor(time/60)%60;
  var sec=Math.floor(time)%60;
  var count=0;  //so max of 2 units print eg 3 days 7 hours, not 3 days 7 hours 12 minutes 4 seconds
  var out='';
  if(days==1){  //special case for not plural
    out+='1 day, ';
    count++;
  }
  else if(days){
    out+=days+' days, ';
    count++;
  }
  if(hours==1){
    out+='1 hour, '
    count++;
  }
  else if(hours){
    out+=hours+' hours, ';
    count++;
  }
  if(count<2&&min==1){
    out+='1 minute, ';
    count++;
  }
  else if(count<2&&min){
    out+=min+' minutes, ';
    count++;
  }
  if(count<2&&sec==1){
    out+='1 second, ';
    count++;
  }
  else if(count<2&&sec){
    if(count)
      out+=', ';
    out+=sec+' seconds, ';
    count++;
  }
  out=out.substring(0,out.length-2);  // remove last comma
  out+=" ago.";
  return out;
}

var api_key = '99aae797f819a87c34d4497a02811e5c'; 
var channel_path = 'xd_receiver.htm'; 
FB_RequireFeatures(["Api"], function(){ 
  FB.Facebook.init(api_key, channel_path); 
  var api = FB.Facebook.apiClient; 
  api.requireLogin(function(exception){ //login, code from facebook
    var rand={'random':1};
    api.friends_get(null, function(result,rand){ //get uids of all friends (not batch, needed for future calls)
      const NOTE=1;
      const STATUS=2;
      const LINK=4;
      var seq=new FB.BatchSequencer(); 
      var uids='';
      result[result.length]=api.get_session().uid; //append logined in user to list to retrive/display content for
      for(var i in result)
        uids+='uid='+result[i]+' OR ';  //generate string in form 'uid=xxxx OR uid=yyy OR...' for FQL calls
      uids=uids.substring(0,uids.length-4);
      var owners=uids.replace(/uid/g,'owner'); //FQL varibale names not consistant so change uid to owner/subject
      var subjects=uids.replace(/uid/g,'subject');
      var d=new Date();
      var curTime=Math.floor(d.getTime()/1000); //Facebook uses seconds since epoch not miliseconds......
      var day=86400;  //60*60*24
      //FQL calls slowness in loading is here, or technically from when they get executed by the sequencer
      name=api.fql_query('SELECT uid, name FROM user WHERE '+uids,seq);                                  //final empty string needed WHY!?!?!?
      var note=api.fql_query('SELECT uid, title, created_time, note_id FROM note WHERE ('+uids+') AND created_time>'+(curTime-day*21)+'',seq);
      var status=api.fql_query('SELECT uid, time, message FROM status WHERE ('+uids+') AND time>'+(curTime-day)+'',seq);
      var links=api.fql_query('SELECT owner, created_time, title, url FROM link WHERE ('+owners+') AND created_time>'+(curTime-day*7)+'',seq);
      seq.execute(function(){
        name=name.result;
        note=note.result;
        status=status.result;
        links=links.result;
        var items=new Array();
        for(var i in status){
          items[items.length]=document.createElement('div'); //adds a new div at end of array
          items[items.length-1].time=status[i].time;  // sets time to sort by, type to filter by w/ tabs, class for css, and html to display
          items[items.length-1].type=STATUS;
          items[items.length-1].class='item';
          items[items.length-1].innerHTML='<div class="img"><img src="status.jpg"/></div> <a href="http://www.facebook.com/profile.php?id='+
                                          status[i].uid +'" target="_blank">'+getName(status[i].uid)+'</a> '+
                                          status[i].message+' <em>'+timeToText(curTime-status[i].time)+'</em>';
        }
        for(var i in note){
          items[items.length]=document.createElement('div');
          items[items.length-1].time=note[i].created_time;
          items[items.length-1].type=NOTE;
          items[items.length-1].class='item';
          items[items.length-1].innerHTML='<div class="img"><img src="note.jpg"/></div> <a href="http://www.facebook.com/profile.php?id='+
                                          note[i].uid+'" target="_blank">'+getName(note[i].uid)+
                                          '</a> posted the note "<a href="http://www.facebook.com/note.php?note_id='+
                                          note[i].note_id+'" target="_blank">'+note[i].title+'</a>"  <em>'+
                                          timeToText(curTime-note[i].created_time)+'</em>';
        }
        for(var i in links){
          items[items.length]=document.createElement('div');
          items[items.length-1].time=links[i].created_time;
          items[items.length-1].type=LINK;
          items[items.length-1].class='item';
          items[items.length-1].innerHTML='<div class="img"><img src="link.jpg"/></div> <a href="http://www.facebook.com/profile.php?id='+
                                          links[i].owner+'" target="_blank">'+getName(links[i].owner)+
                                          '</a> posted the link "<a href="'+links[i].url+'" target="_blank">'+
                                          repURL(links[i].title)+'</a>"  <em>'+timeToText(curTime-links[i].created_time)+'</em>';
        }
        
        items=items.sort(chron);  //sort all content items
        var allTab=document.createElement('div'); //create divs for each tab
        var statTab=document.createElement('div');
        var linkTab=document.createElement('div');
        var noteTab=document.createElement('div');
        allTab.id='all'; // ids for css
        statTab.id='stat';
        linkTab.id='link';
        noteTab.id='note';
        for(var i in items){
            if(items[i].type==STATUS) //fill divs by content type (since will also be in allTab use copy)
              statTab.appendChild(items[i].cloneNode(true));
            if(items[i].type==LINK)
              linkTab.appendChild(items[i].cloneNode(true));
            if(items[i].type==NOTE)
              noteTab.appendChild(items[i].cloneNode(true));
            allTab.appendChild(items[i]);
        }
        document.body.appendChild(allTab); //add allTab to page, ran out of time to add tab functionality
        var clock=document.createElement('div');
        clock.id='clock';  //display time page was created so '5 minutes ago' can be in reference to something
        clock.innerHTML='<em>Last updated at '+d.getHours()+':'+(d.getMinutes()<10?'0':'')+d.getMinutes()+'</em>';
        document.body.appendChild(clock);
      });
    }); 
  }); 
}); 
//]]> 
