var initial = true; // distinguish between page load and incremental updates
var tweet_deck = [];
var last_id = 0;
var page = 0;
var site = "handsoff";
var pagesize = 15;

$(document).ready(function()
                  {
                       // insert the html
                       fetchTweets('handsoff');
                       fetchTweets('HC09');

                       setInterval( function() {updateDates('handsoff')}, 30000 );
                       setInterval( function() {fetchTweets('handsoff')}, 120000 );
                       setInterval( function() {updateDates('HC09')}, 30000 );
                       setInterval( function() {fetchTweets('HC09')}, 120000 );

                  });



function updateDates(hash_tag)
{
     $('#tweetment_' + hash_tag + ' div').each( function(){
               var time = $(this).children('input').val();

               $(this).children('.time').text( relativeTime( time ) );
          });
}

function fetchTweets(hash_tag)
{

     if( page == 0 )
     {
          // fetch the cached tweet list
          var request = lb  + "tweet/list?site=" + hash_tag + "&count=" + pagesize + "&last_id=" + last_id + "&callback=?";
          //alert(request);
          if( initial )
          {
               // on first load, also fetch a totd
               request += "&totd=1";
          }

          $.getJSON( request, function(response) { drawTweetment(response, hash_tag) } );
     }
}

function fetchPaginatedTweets(hash_tag)
{
     // fetch the cached tweet list
     $.getJSON(  lb  + "tweet/list?site=" + site + "&count=" + pagesize + "&page=" + page + "&callback=?", function (response) {drawTweetment(response, hash_tag)} );
}

function drawTweetment( response, hash_tag )
{
     if( initial )
     {
          // set up pagination links
          $('#tweetment_' + hash_tag).empty();
          //$('#tweetment_wrapper').append( "<div id='twidgets'><a id='tw_next'></a><a id='tw_prev'></a></div>");

          //$('#tw_prev').hide();
          $('#tw_prev_' + hash_tag).bind('click', function() {prevPage(hash_tag)} );

          //$('#tw_next').hide();
          $('#tw_next_'+ hash_tag).bind('click', function() {nextPage(hash_tag)} );

          $('#twidgets_' + hash_tag).slideDown( 1600 );
          initial = false;
     }

     if( response.displayable )
     {
          // keep the tweets
          tweet_deck[hash_tag] = response.displayable;

          // show a tweet
          displayNewTweet(hash_tag);
     }
}

function prevPage(hash_tag)
{
     page--;
     if( page < 0 ) page = 0;

     fetchPaginatedTweets(hash_tag);
}

function nextPage(hash_tag)
{
     page++;
     fetchPaginatedTweets(hash_tag);
}

function displayNewTweet(hash_tag)
{
     var tweet = eval( tweet_deck[hash_tag].pop() ); // get a new tweet

     if( tweet )
     {
          var tweet_html = makeHtml( tweet, tweet.id , hash_tag); // make html
          var id = '#g' + tweet.id + hash_tag;
          last_id = Math.max( last_id, tweet.id );

          // inject a new message at the top,
          $('#tweetment_' + hash_tag).prepend( tweet_html );
          $(id).hide();
          $(id).slideDown( 300, function() { didDisplayNewTweet(hash_tag) } );
     }
}

function didDisplayNewTweet(hash_tag)
{
     //      if( $('#tweetment div').size() > pagesize )
     //      {
     //           $('#tweetment div.tweet:last').slideUp( 600, function(){ $('#tweetment div.tweet:last').remove() } );
     //      }

     // loop?
     if( tweet_deck[hash_tag].length > 0 )
     {
          displayNewTweet(hash_tag);
     }
     else
     {
          // show / hide pagination
          $('#tw_next_' + hash_tag).fadeIn( 600 );

          if( page == 0 )
          {
               $('#tw_prev_' + hash_tag).hide();
          }
          else
          {
               $('#tw_prev_' + hash_tag).fadeIn( 600 );
          }
     }
}

// regex method to find links in twitter result.text and turn into anchors.  mas.
String.prototype.linkify = function()
{
     return this.replace( /[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/,
                          function(m) {
                               return m.link( m );
                          });
};


function urlencode( str )
{

     // http://kevin.vanzonneveld.net
     // +   original by: Philip Peterson
     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
     // +      input by: AJ
     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
     // +   improved by: Brett Zamir (http://brett-zamir.me)
     // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
     // +      input by: travc
     // +      input by: Brett Zamir (http://brett-zamir.me)
     // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
     // +   improved by: Lars Fischer
     // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
     // *     example 1: urlencode('Kevin van Zonneveld!');
     // *     returns 1: 'Kevin+van+Zonneveld%21'
     // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
     // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
     // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
     // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

     var histogram = {}, unicodeStr='', hexEscStr='';
     var ret = (str+'').toString();

     var replacer = function(search, replace, str)
          {
               var tmp_arr = [];
               tmp_arr = str.split(search);
               return tmp_arr.join(replace);
          };

     // The histogram is identical to the one in urldecode.
     histogram["'"]   = '%27';
     histogram['(']   = '%28';
     histogram[')']   = '%29';
     histogram['*']   = '%2A';
     histogram['~']   = '%7E';
     histogram['!']   = '%21';
     histogram['%20'] = '+';
     histogram['\u00DC'] = '%DC';
     histogram['\u00FC'] = '%FC';
     histogram['\u00C4'] = '%D4';
     histogram['\u00E4'] = '%E4';
     histogram['\u00D6'] = '%D6';
     histogram['\u00F6'] = '%F6';
     histogram['\u00DF'] = '%DF';
     histogram['\u20AC'] = '%80';
     histogram['\u0081'] = '%81';
     histogram['\u201A'] = '%82';
     histogram['\u0192'] = '%83';
     histogram['\u201E'] = '%84';
     histogram['\u2026'] = '%85';
     histogram['\u2020'] = '%86';
     histogram['\u2021'] = '%87';
     histogram['\u02C6'] = '%88';
     histogram['\u2030'] = '%89';
     histogram['\u0160'] = '%8A';
     histogram['\u2039'] = '%8B';
     histogram['\u0152'] = '%8C';
     histogram['\u008D'] = '%8D';
     histogram['\u017D'] = '%8E';
     histogram['\u008F'] = '%8F';
     histogram['\u0090'] = '%90';
     histogram['\u2018'] = '%91';
     histogram['\u2019'] = '%92';
     histogram['\u201C'] = '%93';
     histogram['\u201D'] = '%94';
     histogram['\u2022'] = '%95';
     histogram['\u2013'] = '%96';
     histogram['\u2014'] = '%97';
     histogram['\u02DC'] = '%98';
     histogram['\u2122'] = '%99';
     histogram['\u0161'] = '%9A';
     histogram['\u203A'] = '%9B';
     histogram['\u0153'] = '%9C';
     histogram['\u009D'] = '%9D';
     histogram['\u017E'] = '%9E';
     histogram['\u0178'] = '%9F';

     // Begin with encodeURIComponent, which most resembles PHP's encoding functions
     ret = encodeURIComponent(ret);

     for (unicodeStr in histogram)
     {
          hexEscStr = histogram[unicodeStr];
          ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
     }

     // Uppercase for full PHP compatibility
     return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
               return "%"+m2.toUpperCase();
          });
}

function makeHtml( tweet, id , hash_tag)
{
     var html = "<div id='g" + id + hash_tag + "' class='tweet'>";
     html += "<div class='profileholder'>";
     html += "<img hspace='5' width='48' height='48' src='" + tweet.profile_image_url + "'/>";
     html += "</div>";
     html += "<div class='tweetbody'>"
          html += "<p style='margin:0px;' class='name'><a  target='_twitter' href='http://twitter.com/" + tweet.screen_name + "' target='_new'>" + tweet.name;

     if( tweet.name != tweet.screen_name )
     {
          html += " / <span style='font-size:14px;'>" + tweet.screen_name + "</span></p>";
     }

     html += "</a>";
     html += ": " + tweet.text.linkify() + "</p>";
     html += "<br clear='all'/><p class='time'>" + relativeTime( tweet.created_at ) ;
     html += "</p><input type='hidden' value='" + tweet.created_at + "' />";
     html += " | <a target='_twitter' href='http://twitter.com/home?status=%40" + urlencode(tweet.screen_name) + "+%23handsoff '>Reply</a> | ";
     html += "<a target='_twitter' href='http://twitter.com/home?status=RT+%40" + urlencode(tweet.screen_name) + "+" + urlencode(tweet.text) + "'>ReTweet</a> ";
     html += "</div></div>";

     return html;
}

// returns relative time, call with twitter time value.
function relativeTime( time_value )
{
     var now = new Date();
     var delta = ( now.getTime() / 1000 ) - time_value;

     if( delta < 60 ) return 'a minute ago';
     if( delta < 180 ) return 'a couple of minutes ago';
     if( delta < (45*60) ) return Math.floor( delta / 60 ) + ' minutes ago';
     if( delta < (120*60) ) return 'an hour ago';
     if( delta < (24*60*60) ) return ( parseInt(delta / 3600)).toString() + ' hours ago';
     if( delta < (48*60*60) ) return '1 day ago';
     return ( parseInt( delta / 86400 ) ).toString() + ' days ago';
}
