/*
 * Hello, nosy people.
 */

// How often do clients check for updates?
var refresh_time = 10000;

// ID of the last tweet we displayed.
var max_tweet_id = 0;

// Queue of new tweets waiting to be displayed.
var tweet_queue = new Array();

$(document).ready(function(event)
{
   refresh();
});

/*
 * Ask the server if there are any more sticky tweets to display.
 */
function refresh()
{
   status('Finding some disgusting tweets...', true);

   $.ajax({
         type: "GET"
      ,  url: "/tweets"
      ,  data: {'last': max_tweet_id}
      ,  dataType: "json"
      ,  success: function(tweets)
         {
            if(tweets.length == 0)
            {
               status("Checking for new tweets in a moment.", false);
               setTimeout(refresh, refresh_time);
            }
            else
            {
               tweet_queue = tweets;
               processTweetQueue();
           }
         }
      });
}

/*
 * Fiddle with the status text in the bottom left corner.
 */
function status(message, queue)
{
   // Queue the message, or display it now.
   if(queue)
   {
      // Add a new status message, hidden.
      $('#footer #status').append($('<li>').text(message).hide());

      // Hmm, there's a race condition bug here. TODO: Fix me.
      
      // Fade out and delete the current one.
      $('#footer #status li:first-child').fadeOut(500, function()
         {
            $(this).remove();
            $('#footer #status li:first-child').fadeIn(500);
         });
   }
   else
   {
      // Dump the message queue and display this one immediately.
      $('#footer #status').empty().append($('<li>').text(message));
   }
}

/*
 * Pull one tweet out of the queue and add it to the page.
 */
function processTweetQueue()
{
   //console.debug(tweet_queue);
   if(tweet_queue.length > 0)
   {
      status(sprintf("Ooh, adding %d new tweets!", tweet_queue.length), false);
      var tweet_data = tweet_queue.shift();
   
      if(tweet_data.id > max_tweet_id)
      {
         max_tweet_id = tweet_data.id;
         addTweet(makeTweet(tweet_data));
      }
      else
      {
         //console.debug(sprintf("Skipped %d because < %d", tweet.id, max_tweet_id));
      }
   
      if(tweet_queue.length > 0)
         // Process more tweets if we have any.
         setTimeout(processTweetQueue, 200);
      else
      {
         setTimeout(refresh, refresh_time)
         status("All done! Checking again soon.", true);
      }
   }
}

/*
 * Make a new tweet element.
 */
function makeTweet(tweet_data)
{
   var image = $('<img>').addClass("profile").attr('src', tweet_data.img);
   var name = $('<a>').addClass('name').append(image).append("@" + tweet_data.from).attr('href', sprintf('http://www.twitter.com/%s', tweet_data.from));
   var text = $('<q>').html(tweet_data.text);

   var tweet = $('<div>');
   tweet.attr('id', tweet_data.id);
   tweet.addClass('live');

   var clear = $('<div>').css('clear', 'both');
   
   var rt_content = sprintf('RT www.thingsthatmakeyougo.eu @%s %s', tweet_data.from, tweet_data.text_raw);
   rt_content = rt_content.replace(/ /g, '+');

   var rt_button = $('<a>').append($('<img>').addClass("button").attr('src', '/img/balloon-twitter.png'))
                           .attr('href', sprintf('http://www.twitter.com/?status=%s', rt_content));
   //var vote_button = $('<a>').append($('<img>').addClass("button").attr('src', '/img/icons/icons/thumb-up.png'))
   //                        .attr('href', sprintf('http://www.twitter.com/?status=lol'));

   rt_button.hover(function()
      {
         var tooltip = $('<div>').addClass("tooltip").text("Retweet this!");
         var position = $(this).position();
         tooltip.css({'left': position.left - 30, 'top': position.top - 30});
         $(this).after(tooltip);
      }, function()
      {
         $(this).next('div.tooltip').remove();
      });

   tweet
        .append(name)
        .append(' ')
        .append(' ')
        .append(text)
   //     .append(vote_button)
        .append(rt_button)
        .append(clear);

   tweet.addClass('roundedcorners').addClass('tweet');

   tweet.hover(function()
      {
         $(this).find('.button').show();
      }, function()
      {
         $(this).find('.button').hide();
      });
   roundCorners(tweet);

   return tweet;
}

/*
 * Add a tweet, making new columns (and cleaning old ones) as necessary.
 */
function addTweet(tweet)
{
   // Is it time to add a new column?
   if($('#tweets div.col:first-child').height() + 150 > $(window).height())
   {
      // Add a new column.
      $('#tweets').prepend($('<div>').addClass('col').css('width', '1px'));
      $('#tweets div.col:first-child').animate({'width': '350px'}, 200);

      // Check the existing columns to see if we need to delete one.
      $('#tweets div.col').each(function()
         {
            var pos = $(this).position();
            if(pos.left > $(window).width() + 100)
               $(this).remove();
         });
   }

   // Add this tweet.
   $('#tweets div.col:first-child').prepend(tweet);

   // Funky animation for new tweets.
   tweet.find('div.inner').hide();
   wibble(tweet);
   tweet.find('div.inner').slideDown(300);
}

/*
 * Shake it all about.
 */
function wibble(obj)
{
   $(obj).animate({'width': '350px',  'left': '-=75px', 'top': '-=20px' }, 200)
         .animate({'width': '-=10px', 'left': '+=5px',  'top': '+=5px'  }, 150);
   // Too much animation makes Homer go something-something, where 'Homer' is
   // 'slow machines' and 'go something-something' is 'cry'
   //      .animate({'width': '+=5px',  'left': '-+3px',  'top': '-=3px'  }, 100)
   //      .animate({'width': '-=3px',  'left': '+=1px',  'top': '+=1px'  }, 50);
}

/*
 * Add some silly furniture around an element to give it rounded corners.
 */
function roundCorners(obj)
{
   // If an object (or selector) was provided, use that. Otherwise, use the
   // class 'roundedcorners'
   var selector = (null != obj ? obj : '.roundedcorners');
      
   // Apply rounded corners to everything that wants them.
   $(selector).wrapInner('<div class="inner"></div>')
              .prepend('<b class="rtop"><b class="r1"></b><b class="r2"></b><b class="r3"></b><b class="r4"></b></b>')
              .append('<b class="rbottom"><b class="r4"></b><b class="r3"></b><b class="r2"></b><b class="r1"></b></b>')
              .removeClass('roundedcorners');
}


