stats_widget = function(url, token, challenge_id) {
	api_url = url + 'api/stats';
	if(typeof jQuery == 'undefined') {
		stats_widget.getScript("http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js");
	}
	stats_widget.tryReady(0, api_url, token, challenge_id);
}

// dynamically load any javascript file.
stats_widget.getScript = function(filename) {
  var script = document.createElement('script')
  script.setAttribute("type","text/javascript")
  script.setAttribute("src", filename)
  if (typeof script!="undefined")
  document.getElementsByTagName("head")[0].appendChild(script)
}

stats_widget.tryReady = function(time_elapsed, api_url, token, challenge_id) {
  // Continually polls to see if jQuery is loaded.
  if (typeof jQuery == "undefined") { // if jQuery isn't loaded yet...
    if (time_elapsed <= 5000) { // and we haven't given up trying...
      setTimeout("stats_widget.tryReady(" + (time_elapsed + 200) + ", '" + api_url + "', '" + token + "', " + challenge_id + ")", 200); // set a timer to check again in 200 ms.
    } else {
      alert("Timed out while loading statistics widget.");
    }
  } else {
	stats_element = jQuery('div#c4c_widget_stats');			
	stats_html = stats_element.html();
	stats_element.html('<div id="c4c_widget_stats_loading">Loading...</div>');
	stats_element.show();
	jQuery.getJSON(api_url, { token: token, challenge_id: challenge_id },
   		function(data){
			var stats = ['organisations', 'departments', 'participating_members', 'members', 'participating_rookies', 'rookies', 'total_trips', 
								'total_distance', 'energy', 'transport_trips', 'distance_transport', 'fat',
 								 'carbon', 'cycle_distance', 'work_trips', 'work_distance', 'commuting_members'];
			
			for(i = 0; i < stats.length; i++) {
				stats_html = stats_html.replace('_' + stats[i] + '_', add_commas(Math.round(data[stats[i]])));
			}
			stats_element.html(stats_html);
		}
	);	
  }
}

function add_commas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
