$(document).ready(function() {
  
  search_twitter_for("%23ufc100+OR+ufc100", '1', "#list");  
  setTimeout('wrapIt();', 2000);
  setTimeout('search_twitter_for("' + terms + '", "' + $("#marker").text() + '", "' + appendto +'")', 180000);
  
});

// 1 minute = 60,000
// 3 minutes = 180,000

function wrapIt() {
  $("#commentary").jCarouselLite({
   vertical: true,
   mouseWheel: true,
   hoverPause: false,
   visible: 4,
   auto: 1000,
   speed: 4500
  });
}

// http://search.twitter.com/search.json?q=%23ufc100+OR+ufc100&rpp=100&show_user=true&callback=?
// Search Twitter for
//
// === Description
//
// This searches twitter for the given terms, builds div's for each result
// and populates them with the avatar, user name, time it was tweet and the
// actual tweet itself.
//
function search_twitter_for(terms, since_id, appendto) {

  $.getJSON("http://search.twitter.com/search.json?q="+terms+"&since_id="+since_id+"&rpp=100&show_user=true&callback=?",
    function(data){
      $.each(data.results, function(index, result){
        $("<li>").attr("class", "tweets").html(
          "<div class='tweet_user'><div class='tweet_user_image'><img src='" + result.profile_image_url + "'  width='50' height='50'/> </div><div class='tweeted_by'><p>"+prettyDate(result.created_at)+" <span class='big'><a href='http://www.twitter.com/"+result.from_user+"'>@" + result.from_user + "</a> said:</span></p></div><div class='tweet_text'><p>" + createLinks(result.text) + "</p></div></div>"
        ).appendTo(appendto);
      });
      
      // set the tweet id
      $("#marker").html(data.results[0].id);
  
    } // function(data)
  ); // getJSON 
}


function createLinks(text) {
  if(text.match("www") || text.match("http")) {
    var words = text.split(' ');
    for(var i in words) {
      if(words[i].match("www") || words[i].match("http")) {
        words[i] = "<a href='"+words[i]+"' target='_blank'>"+words[i]+"</a>";
      }
    }
    return words.join(' ');
  }
  return text;
}


/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
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;
			
	return 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";
}

