var timer;  
   
 $(document).ready(function() {  
 
     get_search();
   
 });  
   
 function get_search() {  
    clearTimeout(timer);  
    var query = "from%3Amediatemple";  
    var tweets = 100; 
    var latest_id = $.session("latest_tweet");
    var first_tweet = 0;
    var last_tweet;


        // The initial page load function. Just grabs the latest tweets 
        $.getJSON('http://search.twitter.com/search.json?callback=?&q='+query+'&rpp='+tweets, function(data){
            
            // iterate over the newfound json object 
            $.each(data.results, function(i, item){
                   if (!item.to_user) { //don't show replies
                      // automagically replace urls with hyperlinks, usernames with links to their page, and hashes with twitter search links
                      item.text = item.text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
    	                  return url.link(url);
                      });
                      item.text = item.text.replace(/@([a-zA-Z0-9\_\-]+)/g,'<a href=\"http://www.twitter.com/$1\" rel="nofollow">\@$1</a>');
                      item.text = item.text.replace(/#([a-zA-Z0-9\_\-]+)/g,'<a href=\"http://search.twitter.com/search?q=%23$1\" rel="nofollow">#$1</a>');
                      item.text = item.text.replace(/\^([a-zA-Z0-9\_\-]+)/g,''); //strip out tweeter signature
                      item.text = item.text.replace(/#fb/g,''); //strip out #fb hashes (used to post things to our facebook fan page)

                      // create the div with all the stuff we want to show up
                      var newDiv = '<p class="tweet">'+item.text+'</p>';
                 
                      // add it to the page
                      $('#twitter p').replaceWith(newDiv).animate({opacity: 'show', height: 'show'},300);

                      // the first one to come in is really the last, so we want to save that for new tweets that come in
                      if (first_tweet++ == 0) {
                         $.session("latest_tweet",item.id);
                      }
 
                      // we also want to save the last one to come in, which is really the first for the next 20 link
                      $.session("first_tweet",item.id);
                   
                      // no explicit way to break out of an each loop in jquery? Thanks for that.  
                      return false;  
                   } 
            });
        });
     
    timer = setTimeout('get_search()', 60000);  

  }
