(function($){
 $.fn.twitter = function(options) {
  var defaults = {
   display_count: 3,
   content_refresh: 10000, /* expressed in milliseconds */
   show_user_photo: false,
   user_timeline: false,
   empty_text: "Found 0 results"
  };
  
  var options = $.extend(defaults, options);


  /* function to format the timestamp into something a little nicer on the eyes ala twitter */  
  function relative_time(time_value) {
    var values = time_value.split(" ");
    
    if (options.user_timeline) {time_value = values[2] + " " + values[1] + ", " + values[3] + " " + values[5];}
    else {time_value = values[1] + " " + values[2] + ", " + values[4] + " " + values[3];}    
    
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);  
    var r = '';
    if (delta < 60) {  r = 'a minute ago'; } 
    else if(delta < 120) { r = 'couple of minutes ago'; } 
    else if(delta < (45*60)) { r = (parseInt(delta / 60)).toString() + ' minutes ago'; } 
    else if(delta < (90*60)) { r = 'an hour ago'; }
    else if(delta < (24*60*60)) { r = '' + (parseInt(delta / 3600)).toString() + ' hours ago'; }
    else if(delta < (48*60*60)) { r = '1 day ago'; } 
    else { r = (parseInt(delta / 86400)).toString() + ' days ago'; }
    return r;
  }

  /* function to format links in html as such */  
  function makelink(content) {
    return content.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {return m.link(m); });
  }
  
  return this.each(function() {
      var container = $(this);
      var twitter_params = $(this).attr("title").split('|'); 
      
      /* Define twiiter json url */
      var url = twitter_params[0];
      if (!options.user_timeline) {
        if (url.search("callback=") < 0) { url += "&callback=?";}
      }

      /* Define displayCount:  Looks first for a title atribute then for display_count default upon intitailization and finally if both those are null goes to the display_count deafult set above */
      if (twitter_params[1]) { var displayCount = twitter_params[1] - 1; }
      else {var displayCount = options.display_count - 1;}
      
      /* Define contentRefresh:  looking for title attribute first, default upon initialization second, and content_refresh as fallback */
      if (twitter_params[2]) { var contentRefresh = twitter_params[2]; }
      else {var contentRefresh = options.content_refresh;}
      
      $(this).html('<ul></ul>');
      
      
      /* Call get_the_twitter() defined below first time then recall in interval */     
      get_the_twitter();
      if (contentRefresh > 0) {setInterval(get_the_twitter, contentRefresh);}

  //alert(url);
      function get_the_twitter() {     
      /* GET twitter url and return json */
      $.getJSON(url, function(data){

        if (options.user_timeline) {var results = data}
        else { var results = data['results'];}
        
        /* Check and account for null returned, also accounting for when # returned is less than displayCount */
        var result_length = results.length;
        if (result_length < (displayCount + 1)) {displayCount = result_length - 1;}
        var prev_content = container.children("ul").html();
        if (result_length == 0) {container.html(options.empty_text);return false;}
                  
        var content = '';
	    
	    /* Deal with each tweet returned, format time, make html links, etc. */
	    $.each(results, function(i, item) {

	      if (options.show_user_photo) {
	        if (options.user_timeline) { var user_photo_path = item.user.profile_image_url;}
	        else { var user_photo_path = item.profile_image_url;}
	        var user_photo = '<img src="' + user_photo_path + '" class="user_photo" />';
	      } else { user_photo = ''; }
	      
	      if (options.user_timeline) {
	        content += '<li>'+ user_photo + makelink(item.text) + '<div class="info"><a href="http://twitter.com/' + item.user.name + '/statuses/' + item.id + '" target="_blank">' + relative_time(item.created_at) + '</a> from <strong>' + item.user.name + '</strong></div></li>';
	      } else {
	        content += '<li>'+ user_photo + makelink(item.text) + '<div class="info"><a href="http://twitter.com/' + item.from_user + '/statuses/' + item.id + '" target="_blank">' + relative_time(item.created_at) + '</a> from <strong>' + item.from_user + '</strong></div></li>';
          }	      
	      
	      if ( i == displayCount ) {
	        if (content != prev_content) {
	          container.children("ul").empty();
	          container.children("ul").append(content);
	          container.children("li a").attr("target","_blank");
	        }
	        return false; 
	      } // displayCount
	  }); // each
    }); // getJSON
    } // get_the_twitter
  }); // return
 }; // $.fn.twitter
})(jQuery);
