/*
 * jQuery Tweed plugin to pull a user's Twitter timeline sensibly;
 *  Version 0.1 by Anny (http://anny.fm/)
 *
 * Requires PHP accompaniment <jquery.tweed.php>
 *
 */

(function($)
{

	$.fn.tweed = function( options )
	{
		options = $.extend( {}, $.fn.tweed.defaults, options );
		return this.each(function()
		{
		  getFeed( $(this), options );
		});
	};

  $.fn.tweed.defaults =
  {
    scriptLocation: "jquery.tweed.php",
    user: "twitter",
    count: 10,
    wrap: 0,
    format: "<h2 id=\"{id}\">{created_at}</h2><p>{text}</p>",
    wrapFormat: "<div class=\"wrap\">{wrap}</div>",
    makeLinks: true,
    dateFormat: false,
  };

  /*
   * Initially called method to load the feed.
   * @param1 object jQuery object
   * @param2 object options
   *
   */
  function getFeed( object, options )
  {
    // Build and call a JSON request URI.
    var uri = autoreplace( options.scriptLocation+"?user={user}&count={count}", options );
    $.getJSON( uri, function( data )
    {
      if( data != undefined && data && typeof(data) == "object" )
        processFeed( object, options, data );
    });
  }

  /*
   * Process feed if loaded okay.
   * @param1 object jQuery object
   * @param2 object options
   * @param3 object JSON data
   *
   */
  function processFeed( object, options, data )
  {
    var items = [];

    for( var d in data )
    {
      // Process data.
      data[d].created_at = processTime( options, data[d].created_at );
      if( options.makeLinks )
      {
        data[d].text = data[d].text.replace( /(((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])|www\.[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function( t ) { return (t.match( /(https?|s?ftp|ssh)\:\/\//g ) == null) ? '<a href="http://'+t+'">'+t+"</a>" : '<a href="'+t+'">'+t+"</a>" });
        data[d].text = data[d].text.replace( /\@([a-z0-9\_]+)/ig, function( t ) { t = t.substring(1,t.length); return "@<a href=\"http://twitter.com/"+t+"\">"+t+"</a>" });
      }

      // Push formatted data into feed items.
      items.push( autoreplace( options.format, data[d] ));
    }

    // Tie together the output of feed items and push out.
    if( options.wrap )
    {
      var html = "", tmp_html = [], count = 0;
      for( var i = 0; i < items.length; i++ )
      {
        tmp_html.push(items[i]);
        if( ++count == options.wrap || i+1 == items.length )
        {
          html += autoreplace( options.wrapFormat, { wrap: tmp_html.join("") });
          count = 0;
          tmp_html = [];
        }
      }
      object.html( html );
    }
    else object.html( items.join(""));
  }

  /*
   * Process a Twitter timestamp into the desired format.
   * @param1 object options
   * @param2 string created_at value from JSON
   *
   */
  function processTime( options, created_at )
  {
    if( ! options.dateFormat )
    {
      // Calculate relative timestamp.
      var a  = created_at.split( " " );
      var b  = a[1] + " " + a[2] + " " + a[5] + " " + a[3];
      var c  = Date.parse( b );
      var d  = new Date();
      var e  = parseInt(( d.getTime()-c )/1000) + ( d.getTimezoneOffset() * 60 );
      return e < 60       ? "Less than a minute ago"                     :
             e < 120      ? "About a minute ago"                         :
             e < 60*60    ? parseInt( e/60 ).toString() + " minutes ago" :
             e < 120*60   ? "About an hour ago"                          :
             e < 24*60*60 ? parseInt( e/3600 ).toString() + " hours ago" :
             e < 48*60*60 ? "One day ago"                                :
                            parseInt( e/86400 ).toString() + " days ago" ;
    }
    else
    {
      // Take timestamp and reformat as desired. (WIP)
      return created_at;
    }
  }

  /*
   * Arbitrary helper function to quickly replace values into a string.
   * @param1 string input
   * @param2 object values
   * @return string replaced input
   *
   */
  function autoreplace( string, values )
  {
    var keys = string.match( /\{([a-z\_]+)\}/gi );
    for( var k in keys )
    {
      k = keys[k].replace(/\{|\}/g,"");
      if( values[k] != undefined )
      {
        string = string.replace( new RegExp("\{"+k+"\}", "gi"), values[k] );
      }
    }
    return string;
  }

})(jQuery);

/* End of jquery.tweed.js */
