//set up initial interval to check for new data
document.observe("dom:loaded",function(){
	new PeriodicalExecuter(function(pe) {
	  query.checkTimestamp(TIMESTAMP, this);
	}, 60);  //interval is in seconds
});

var query = {
	checkTimestamp: function(timestamp, pe)
	{
		new Ajax.Request(BASE_URL+'billboard/ajax_timestamp/'+CLIENT_NAME+'/'+PROJECT_NAME,{
			onSuccess: function(reply)
			{
				// if timestamp is different, update metrics
				if (timestamp != reply.responseText) {
					pe.stop(); //stop checking for updates
					
					if (reply.responseText == ""){
						new_timestamp = 0;
					} else {
						new_timestamp = reply.responseText;
					}
					query.updateMetrics(new_timestamp);
				} 
			}
		});	
	},
	
	updateMetrics: function(timestamp)
	{
		new Ajax.Request(BASE_URL+'billboard/ajax_refresh/'+CLIENT_NAME+'/'+PROJECT_NAME, {
			onSuccess: function(reply)
			{
				//set global TIMESTAMP
				TIMESTAMP = timestamp;
				
				//reload the metrics
				$('dynamic-content').update(reply.responseText);
				
				//reload the Flash
				//swfobject method call must match the one in the view
				swfobject.embedSWF(swf_url, content_id, swf_width, swf_height, swf_version, express_url, flashvars, params, attributes);

				//set up a new interval
				new PeriodicalExecuter(function(pe) {
				  query.checkTimestamp(TIMESTAMP, this)
				}, 60);  //interval is in seconds
				
			}
		});
	}
}