     
     /*
	 * JavaScript Pretty Date
	 * Copyright (c) 2008 John Resig (jquery.com)
	 * Licensed under the MIT license.
	 */
	// converts ISO time to casual time
	function prettyDate(time){
		var date = new Date((time || "").replace(/-/g,"/").replace(/TZ/g," ")),
			diff = (((new Date()).getTime() - date.getTime()) / 1000),
			day_diff = Math.floor(diff / 86400);
				
		if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
			return;
		var v = day_diff == 0 && (
				diff < 60 && "just now" ||
				diff < 120 && "1 minute ago" ||
				diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
				diff < 7200 && "1 hour ago" ||
				diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
			day_diff == 1 && "Yesterday" ||
			day_diff < 7 && day_diff + " days ago" ||
			day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
		if (!v)
			window.console && console.log(time);
		return v ? v : '';
	}
   
      function formatFBTime(fbDate){  
        var arrDateTime = fbDate.split("T");  
        var strTimeCode = arrDateTime[1].substring(0,  arrDateTime[1].indexOf("+")); 

        var arrDateCode = arrDateTime[0].split("-"); 
        var arrTimeCode = strTimeCode.split(":");  

        var valid_date = new Date();

        valid_date.setFullYear(arrDateCode[0]);  
        valid_date.setMonth(parseInt(arrDateCode[1], 10)-1)  ;
        valid_date.setDate(arrDateCode[2]);  


        valid_date.setHours(arrTimeCode[0]);  
        valid_date.setMinutes(arrTimeCode[1])  ;
        valid_date.setSeconds(arrTimeCode[2]);  
        return valid_date;  
    }
    
    
// Object of type socialMessage
function socialMessage(from_user, avatar_url, message_text,hours_ago,created_time, message_href)
{
  // Declare Object Properties
  this.from_user = from_user;
  this.avatar_url = avatar_url;
  this.message_text=message_text;
  this.hours_ago=hours_ago;
  this.created_time=created_time;
  this.message_href=message_href;
 
  // Declare Object Methods
  this.socialBox=socialBox;
}

function socialBox()
{
  var html =  '<li>';
      var d = prettyDate(this.created_time);
      var imgwidth;
      
      if (this.avatar_url != "/images/header-icon.gif")
        imgwidth = 'width:48px;';
      else
        imgwidth = 'width:30px;margin-left:9px;';
 
      html += '<div class="social_img"><img src="' + this.avatar_url + '" style="'+imgwidth+'" /></div>';
      html += '<div class="title"><a href="'+this.message_href+'/" target="_blank" style="textDecoration:none;color:#3B5998">'+ this.from_user + '</a></div>';
	  html += '<div class="social_message">' + this.message_text + '</div>';
      html += '<div class="spacer"></div></li>';
   
    return html;
}

// function handler for sorting Array of SocialMessages by hour      
function sortHoursAscendingHandler(thisObject,thatObject){
  if (thisObject.hours_ago > thatObject.hours_ago){
      return 1;
  }
  else if (thisObject.hours_ago < thatObject.hours_ago){
      return -1;
  }
  return 0;
}

function socialFeed()
{       
  // Declare variables to hold twitter API url and user name                                                             
  var twitter_num_posts = 4;
  var twitter_user    = 'worxbranding';
  var twitter_api_url = 'http://search.twitter.com/search.json?callback=?&q=' + twitter_user;
 //var twitter_api_url = '/js/localjson.json';
 
  // Declare variables to hold facebook API url
  var facebook_api_url = "https://graph.facebook.com/111838075532903/feed?access_token=AAAETUwDJAWwBAE4JzOF471UtFATX17Y6R3zDqOx7FeldlqMRUpnxB07ALKqfPtxZC4b7NcPqa5Ik1qr2REBdVirSWH0lpgTuyfraZAGAZDZD&callback=?"; 
 
 
  // Enable caching
  $.ajaxSetup({ cache: true });       
 
  // Declare socialFeed used to hold Array of socialMessages  
  var socialFeed = new Array();
 
  // Declare variable used for counting number of messages
  var count = 0;
 
  // Send JSON request
  // The returned JSON object will have a property called "results" where we find
  // a list of the tweets matching our request query
  $.getJSON(twitter_api_url, function(data){
     
    //loop through and within data array's retrieve the message variable.
    $.each(data.results, function(i, tweet){
   
      // Before continue - check for data
      if(tweet.text !== undefined) {
        // Calculate how many hours ago the tweet was posted
        var date_posted = new Date(tweet.created_at);
        var date_now   = new Date();
        var date_diff  = date_now - date_posted;
        var hours      = Math.round(date_diff/(1000*60*60));
             
        var link_href = 'http://www.twitter.com/worxbranding/';          
          
        if (hours < 1344)
        {
          // create SocialMessage object and assign it to socialFeed Array
          socialFeed[count] = new socialMessage(tweet.from_user, tweet.profile_image_url, tweet.text,hours,tweet.created_at, link_href);
         
          // increment count for socialFeed Array  
          count++;
        }
      }
    });  // end 'each' for data.results

   
    // Send Second JSON request
    // Do inside other JSON request due to fact that it is
    // a callback function and can not access data until ready
    // The returned JSON object will have a property called "results" where we find
    // a list of the tweets matching our request query
    $.getJSON(facebook_api_url, function(json){
   
      //loop through and within json array's retrieve the message variable.
      $.each(json.data,function(i,fb){
    
        // Before continue - check for data
        if(fb.message !== undefined) {
          // Calculate how many hours ago the facebook post was posted
          var date_posted = new formatFBTime(fb.created_time);
          var date_now   = new Date();
          var date_diff  = date_now - date_posted;
          var hours      = Math.round(date_diff/(1000*60*60));
         
          // check to make sure link is defined
          var link_href = (typeof(fb.link) != "undefined") ? fb.link : "http://www.facebook.com/WorxBranding";
          
          var img_url = '';
          if (fb.picture !== undefined)
          {
            img_url = fb.picture;
          }
          else{
            img_url = '/images/header-icon.gif';
          }
          
  
          if (hours < 1344)
          {
            // create SocialMessage object and assign it to socialFeed Array
            socialFeed[count] = new socialMessage('WorxBranding', img_url, fb.message,hours,fb.created_time.replace("+0000", ""), link_href);
        
            // increment count for socialFeed Array                        
            count++;
          }
        }  
                   
      }); // end 'each' for json.data                                                         
     
   
      // Build Feed
      // Do inside twitter JSON request due to fact that it is
      // a callback function and can not access data until ready
     
      // Sort by hours ago 
      socialFeed.sort(sortHoursAscendingHandler);
     
      // Append data to SocialFeed div
      for (var row = 0; row < socialFeed.length; row++) {
        $('.social_feed').append(socialFeed[row].socialBox());
      }
     
    }); // end Facebook getJSON call
  });
  
 // end Twitter getJSON call
    $(".social_feed").ajaxStop(function(){
    
            $(".social_feed").fadeIn('slow');
            
			var first = 0;
			var speed = 1000;
			var pause = 5000;
			
		function removeFirst(){
			first = $('ul.social_feed li:first').html();
			heightFirst = $('ul.social_feed li:first').height();                          
			$('ul.social_feed li:first')
			.animate({marginTop: "-="+heightFirst+"px"}, speed, "linear",  function(){$(this).remove(); });
			addLast(first);
		}
		
		function addLast(first){
			last = '<li style="display:none">'+first+'</div>';
			$('ul.social_feed').append(last)
			$('ul.social_feed li:last')
			.animate({opacity: 1}, speed)
			.fadeIn('slow')
		}
	
	interval = setInterval(removeFirst, pause);
		});
} // end socialFeed function



