// Facebook status
// More documentation on: http://developers.facebook.com/docs/api

function displayMsg(link,dots,msg){
	$('#'+link).hide();
	$('#'+dots).hide();
	$('#'+msg).fadeIn();
}

function FBStatus(facebookId,maxNumItems,readAllText,maxNumChars,displayComments,displayLikes,displayAll){
  //Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
  var feedUrl = "https://graph.facebook.com/"+facebookId+"/feed?callback=?"; // set limit: &limit=10
  var maxNum = maxNumItems;
  var maxNumChars = Number(maxNumChars);
  //Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
  $.getJSON(feedUrl,function(json){
    var html = '<ul class="fb-status-list">';
    var count = 1;
    //loop through and within data array's retrieve the message variable.
    $.each(json.data,function(i,fb){
      if((fb.from.id==facebookId || displayAll==1) && fb.type=='status' && count <= maxNum){
        count = count+1;
        var msg = fb.message;
        var msgLength = msg.length;
        if(maxNumChars!=''){
          //alert(msg.length);
          if(msgLength > maxNumChars){
            msgEnd = '<span id="msg-end-'+count+'" class="fb-msg-end" style="display:none;">'+msg.substring(maxNumChars,msgLength)+'</span>';
			msgDots = '<span id="dots-'+count+'" class="dots">...</span> <a href="javascript:displayMsg(\'link-'+count+'\',\'dots-'+count+'\',\'msg-end-'+count+'\')" id="link-'+count+'" class="readAllLink">'+readAllText+'</a>';
            msg = msg.substring(0,maxNumChars);
            msg+=msgEnd+msgDots;
          }
        }
        html += '<li class="fb-status">';
        html += '<img src="https://graph.facebook.com/'+fb.from.id+'/picture" alt="'+fb.from.name+'"/><span class="fb-name"><b>'+fb.from.name+'</b></span> <span class="fb-msg">' + msg + '</span>'
		if(fb.likes && displayLikes==1){
			html+= '<div class="fb-likes">'+fb.likes+'</div>';
		}
		// Displaying comments
        if(fb.comments && displayComments==1){
          html += '<ul>'
		  if(fb.comments.data){
          $.each(fb.comments.data,function(i,fb){
            html += '<li class="fb-comment"><img src="https://graph.facebook.com/'+fb.from.id+'/picture" alt="'+fb.from.name+'"/><span class="fb-name"><b>'+fb.from.name+'</b></span> <span class="fb-msg">' + fb.message + '</span></li>'
          });
		  }
          html += '</ul>'
        }
        html += '</li>'
      }
    });
    html += '</ul>'
    //A little animation once fetched
    $('#fbFeed').animate({opacity:0}, 500, function(){
      $('#fbFeed').html(html);
    });
    $('#fbFeed').animate({opacity:1}, 500);
  });
}
