/*
* fbActivityFeed.js
* @author Jason Ware
* 
* This gets json feed for a public Facebook fan page and displays recent updates 
* There are a couple additional functions in this file - one to abbreviate usernames, and another to deliver "time ago" for recent updates
*
* Requires jQuery.
* 
*/


$(document).ready(function() {

    
      //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 url = "https://graph.facebook.com/greenworks/feed?limit=7&callback=?&access_token=207117265996200|f6a9e8d685b29da1aee4d965.1-100002461213164|3TS8NDIZfzJ6kYWD1sDpv_ksNS8";
	
	//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
	$.getJSON(url, function(json){
		
		var html = '';
		
		//loop through and within data array's retrieve the message variable.
		$.each(json.data,function(i,fb){		
			
			//first look for messages with no comments and that aren't related to "ratings and reviews"
	    	if(fb.comments == null && fb.attribution != 'ratingsreviews'){
	    	
	      		html += '<li>'+abbreviateName(fb.from.name)+' left a ';
	      		html += '<a href="http://www.facebook.com/greenworks#!/greenworks?v=wall" rel="external">message</a>.';
	      		html += ' <em>'+formatTimeAgo(fb.created_time)+'</em></li>';  
	      	
	      	//next look for ratings and reviews	and display accordingly
	      	}else if(fb.attribution == 'ratingsreviews'){
	      	
	      		html += '<li>'+abbreviateName(fb.from.name);
	      		html += ' <a href="'+fb.link+'" rel="external">reviewed</a> our'; 
	      		html += '<a href="'+ +'">'+fb.name+'</a>';  
	      		html += ' <em>'+formatTimeAgo(fb.created_time)+'</em></li>';
	      	
	      	//if there are comments we can assume that we want to display info about the last comment specifically	
	      	}else if( fb.comments!=null && fb.comments.data==null ) {
		      	html += '<li>'+abbreviateName(fb.from.name)+' <a href="http://www.facebook.com/greenworks#!/greenworks?v=wall" rel="external"> left a message</a>';
		      	html += ' <a href="http://www.facebook.com/greenworks/posts/'+fb.id.split("_")[1]+'" rel="external">('+fb.comments.count+' comments)</a>';
	      		html += ' <em>'+formatTimeAgo(fb.created_time)+'</em></li>';
	      		
	      	} else if(fb.comments != null && fb.comments.data!=null) {	      		      	
	      		
	      		//iterate through the comments within an entry
	      		var commenter = null;	      		
		      	$.each(fb.comments.data, function (commentDataIdx, commentData){		      			      		
		      		//only use the last one as facebook keeps the most recent one in this position
		      		//and grab the user's name
		      		if (commentDataIdx == (fb.comments.data.length - 1)) {
						commenter = commentData.from.name;
					}
		      		
		      	});
		      	
		      	html += '<li>'+abbreviateName(commenter)+' <a href="http://www.facebook.com/greenworks#!/greenworks?v=wall" rel="external">commented</a>';
	      		if(fb.from!=null){ 
	      		html += ' on '+abbreviateName(fb.from.name)+'\'s message.';
	      		}
	      		html += ' <em>'+formatTimeAgo(fb.created_time)+'</em></li>';
	      		  
	      	} 	
	  		
		});

		
		
		//We'll start our ul at a 0 opacity
		$('#recentCommunity').html(html);

		//and animate it in once loaded
	    $('#recentCommunity').animate({opacity:1}, 500);   	

	  
	});

});



//take a username, split it, and return first name + initial for last
function abbreviateName(userName){
	// if string doesn't have " " in it, just return the name; also, don't change "Green Works"
	if( userName.indexOf(" ")==-1 || userName=="Green Works" ) { 
		return userName;
	}
	firstName = userName.split(" ")[0];
	lastInit = userName.split(" ")[1].charAt(0);
	return firstName + ' ' + lastInit.toUpperCase();
}

//take the facebook created date and return the time ago it was posted with some specific formatting
function formatTimeAgo(createdTime){

	//turn facebook's time formatting into something usable
    var arrDateTime = createdTime.split("T");
    
    //this is the time
    var strTimeCode = arrDateTime[1].substring(0,  arrDateTime[1].indexOf("+"));
    
    //we need to break up the year- month-day bit as it seems to get parsed wrong otherwise
    var parts = arrDateTime[0].match(/(\d+)/g);
   
    //and then reassemble the parts to use in a date object
    
    //now we'll take the time and split that up and assign those segments 
    //to the hours/minutes/seconds/properties of the date object
    var arrTimeCode = strTimeCode.split(":");
//    valid_date.setHours(arrTimeCode[0]);    
//    valid_date.setMinutes(arrTimeCode[1]);
//    valid_date.setSeconds(arrTimeCode[2]);    

//    var valid_date = new Date(parts[0], parts[1]-1, parts[2], arrTimeCode[0], arrTimeCode[1], arrTimeCode[2],0);
    
	//now do a date comparison and return "hours/days ago"
	var dateFunc = new Date();
	var timeSince = dateFunc.getTime() - Date.UTC(parts[0], parts[1]-1, parts[2], arrTimeCode[0], arrTimeCode[1], arrTimeCode[2],0);
	
	//time offset between our server time and what facebook says
	//var offsetTimeSince = timeSince + 25000000;
	var offsetTimeSince = timeSince;
	
	var inSeconds = offsetTimeSince / 1000;
	var inMinutes = offsetTimeSince / 1000 / 60;
	var inHours = offsetTimeSince / 1000 / 60 / 60;
	var inDays = offsetTimeSince / 1000 / 60 / 60 / 24;
	var inYears = offsetTimeSince / 1000 / 60 / 60 / 24 / 365;
	
	// in seconds
	if(Math.round(inSeconds) == 1){
		return ("1 second ago");
	}
	else if(inMinutes < 1.01){
		return (Math.round(inSeconds) + " seconds ago");
	}
	
	// in minutes
	else if(Math.round(inMinutes) == 1){
		return ("1 minute ago");
	}
	else if(inHours < 1.01){
		return (Math.round(inMinutes) + " minutes ago");
	}
	
	// in hours
	else if(Math.round(inHours) == 1){
		return ("1 hour ago");
	}
	else if(inDays < 1.01){
		return (Math.round(inHours) + " hours ago");
	}
	
	// in days
	else if(Math.round(inDays) == 1){
		return ("1 day ago");
	}
	else if(inYears < 1.01){
		return (Math.round(inDays) + " days ago");
	}
	
	// in years
	else if(Math.round(inYears) == 1){
		return ("1 year ago");
	}
	else
	{
		return (Math.round(inYears) + " years ago");
	}
}


