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

// dynamically load any javascript file.
vs_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)
}

vs_stats_widget.tryReady = function(time_elapsed, api_url, token, challenge, region, vs_challenge, vs_region) {
  // 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("vs_stats_widget.tryReady(" + (time_elapsed + 200) + ", '" + api_url + "', '" + token + "', '" + challenge + "', '" + region + "', '" + vs_challenge + "', '" + vs_region + "')", 200); // set a timer to check again in 200 ms.
    } else {
      alert("Timed out while loading statistics widget.");
    }
  } else {
	jQuery.getJSON(api_url, { token: token, challenge_id: challenge, region: region},
   		function(data) {
			html = jQuery('div#c4c_widget_vs_stats').html();
			html = html.replace("_new_", data.participating_rookies);
			jQuery('div#c4c_widget_vs_stats').html(html);
		}
	);
	jQuery.getJSON(api_url, { token: token, challenge_id: vs_challenge, region: vs_region},
   		function(data) {
			html = jQuery('div#c4c_widget_vs_stats').html();
			html = html.replace("_vs_new_", data.participating_rookies);
			jQuery('div#c4c_widget_vs_stats').html(html);
			jQuery('div#c4c_widget_vs_stats').show();
		}
	);	
  }
}

