/*  CONSIDER RE-FACTORING THESE GLOBAL CONSTANTS OUT */

var TIME_TO_LOAD = (5*1000); // 5 seconds between refreshes
var TIME_TO_CHILL = (60*1000); // one minute between refreshes
var LOADING = 1;

// create the div container
document.write('<div id="commish-recent-registrations"></div>');

jQuery(document).ready(function(){
  // load the first 10 registrations to display
  jQuery.getJSON('http://commi.sh:80/registrations.json?callback=?',

  function(data){
    arr = eval(data);
    jQuery(arr).each(function(el){
      jQuery("#commish-recent-registrations").append(createRegRow(this, "inherit")); 
    });
  });
});

function lastRegFunc(x) { 
  jQuery.getJSON('http://commi.sh:80/registrations.json?callback=?&last_id=' + jQuery('.commish-reg-item:first').attr('id'), 

  function(data){
    arr = eval(data);
    if (arr.length > 0) {
      jQuery(".commish-reg-item:first").before(createRegRow(arr[0], "none")); 
      jQuery(".commish-reg-item:first").slideDown(1000); 
      jQuery(".commish-reg-item:last").remove().hide();
    }
  });
  if (x++ == 5) { LOADING = 0; }
  if (x < 20) {
    if (LOADING) {
      setTimeout('lastRegFunc('+x+')', TIME_TO_LOAD);
    } else {
      setTimeout('lastRegFunc('+x+')', TIME_TO_CHILL);
    }
  }
}; 

setTimeout('lastRegFunc(1)', TIME_TO_LOAD);

function createRegRow(data, display) {
  var str = '<div style="display:'+display+'" class="commish-reg-item" id="'+data['id']+'">\
  <img src="'+data['avatar']+'" height="50" width="50" />\
  <div class="commish-reg-message">'+ data['name']+
  ' <a href="http://commi.sh/seasons/'+data['season_id']+'">registered<a/> for '+
  data['league']['name'] +' <div class="commish-reg-time">'+
  relativeTime(data['created_at'])+'</div></div>\
  </div>';
  return str;
}

function relativeTime(pastTime)
{
	// Generate a JavaScript relative time for the tweets
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	var difference = parseInt((currentStamp - origStamp)/1000);

	if(difference < 0) return false;

	if(difference <= 5)			return "Just now";
	if(difference <= 20)			return "Seconds ago";
	if(difference <= 60)			return "A minute ago";
	if(difference < 3600)		return parseInt(difference/60)+" minutes ago";
	if(difference <= 1.5*3600) 	return "One hour ago";
	if(difference < 23.5*3600)	return Math.round(difference/3600)+" hours ago";
	if(difference < 1.5*24*3600)	return "One day ago";

	// If the tweet is older than a day, show an absolute date/time value;
        return formatDate(new Date(origStamp));
}

function formatDate(value)
{  
   return value.getMonth()+1 + "/" + value.getDate() + "/" + value.getFullYear();
}

