/**
 * Copyright 2006, Internet Broadcasting Systems. All Rights Reserved.
 * Version:   $Name: REL_2_39_0 $
 * ID:        $Id: StatsUpdater.js,v 1.12 2006/12/07 19:33:28 breisinger Exp $
*/

using("nbcsp");
/************
* StatsUpdater - uses Ajax to update objects on a particular page.  
* 	breisinger
* @element = HTML Element to update. Must contain class name @updateableClassName to re-update. 
	Gets blown away with each update.
* @url = Url to find new fragment
* @refreshRate = in seconds
* @updateableClassName = string - class name to look for to see if thing is updateable again
* @updatingClassName = string - class name to give thing when updating it for visual indication of update
*************/
nbcsp.updaters = new Array();
nbcsp.StatsUpdater = function(element,url,refreshRate,updateableClassName,updatingClassName,onUpdate,onProgress) {
	var self = this;
	this.element = element; 	/* element to wipe with new stuff */
	this.parent = this.element.parentNode;
	this.updatingClassName = updatingClassName;
	this.updateableClassName = updateableClassName;
	this.refreshRate = refreshRate; 		/* refresh request rate, in seconds */
	this.url = url;
	this.onUpdate = typeof onUpdate == "function" ? onUpdate : false;
	this.onProgress = typeof onProgress == "function" ? onProgress : false;
	this.headers = [		/* HTTP Request headers */
		'X-DHTML','true'
	];
	this.progress = 1;
	//setTimeout(function() {
		self.createNewUpdater();
	//},this.refreshRate*1000);
}
nbcsp.StatsUpdater.prototype = {
	createNewUpdater: function() {
		var self = this;
		this.requestor = new Ajax.PeriodicalUpdater(
			this.parent,
			this.url,
			{
				frequency: this.refreshRate,
				requestHeaders: this.headers,
				method: 'get',
				onLoading: function() {
					/* add class name to show that an element is in the process of updating */
					Element.addClassName(self.element,self.updatingClassName);
					self.progress = "loading";
				},
				onSuccess: function(response) {
					window.setTimeout(function() {
						//see if we need to stop based on the presence of another one
						//of these els with the update class name
						var elsWithUpdateClassName = document.getElementsByClassName(self.updateableClassName,self.parent);
						if(elsWithUpdateClassName.length < 1) {
							self.stopUpdater();
						}
						if(self.onUpdate) {
							self.onUpdate();
						}
						self.resetProgressTimer();
					},100);
				}
			}
		);
		this.startProgressTimer();
	},
	/***
	* stop updating content, stop keeping time to next update
	***/
	stopUpdater: function() {
		this.requestor.stop();
		this.stopProgressTimer();
	},
	/***
	* calculate seconds elapsed 
	***/
	reportProgress: function() {
		var retVal = {};
		if(!isNaN(parseInt(this.progress))) {
			retVal.percentDone = parseInt((this.progress - 1)/this.refreshRate * 100);
			retVal.secondsElapsed = this.progress - 1;
		} else {
			retVal.percentDone = retVal.secondsElapsed = this.progress;
		}
		retVal.rate = this.refreshRate;
		if(this.onProgress) {
			try {
				this.onProgress();
			} catch(e) {};
		}
		return retVal;
	},
	/***
	* start counting how much time until next refresh
	***/
	startProgressTimer: function() {
		var self = this;
		this.progressTimer = window.setInterval(function() {
			if(!isNaN(parseInt(self.progress))) {
				self.progress++;
			}
			self.reportProgress();
		},1000);
	},
	/***
	* stop counting time until next refresh
	***/
	stopProgressTimer: function() {
		try { 
			window.clearInterval(this.progressTimer);
			this.progressTimer = null;
		} catch(e){};
	},
	/***
	* restart count to next refresh
	****/
	resetProgressTimer: function() {
		this.progress = 1;
		if(!this.progressTimer) {
			this.startProgressTimer();
		}
	},
	/***
	* reset refresh rate to given int
	****/
	changeAutoRefreshRate: function(seconds) {
		if(parseInt(seconds)) {
			this.stopUpdater();
			//for our wrapper
			this.refreshRate = seconds;
			//for prototype updater
			this.requestor.frequency = seconds;
			this.requestor.timer = setTimeout(this.requestor.onTimerEvent.bind(this.requestor),this.requestor.decay * this.requestor.frequency * 1000);
			this.resetProgressTimer();
		} else {
			this.stopUpdater();
		}
	}
}


/***
* WRAPPER TO CREATE A NEW UPDATER INLINE
* var el = $('fkjdf;dkljf');
* ncbsp.createStatsUpdaterInline(el,394803,60);
***/
nbcsp.createStatsUpdaterInline = function(htmlElement,coid,refreshRate) {
	var url = "/_object/" + coid + "/feature.html";
	//create new requester
	var u = new nbcsp.StatsUpdater(
		htmlElement,	//html element
		url,	
		refreshRate,	//refresh rate
		"updateable",
		"updating"
	);
}


/****
* WRAPPER TO SCAN PAGE AND CREATE ALL UPDATERS. Keys off class name "updateable".  
****/
nbcsp.enableStatsUpdaters = function() {
	var tables = document.getElementsByClassName("updateable");
	tables.each(function(value,index) {
		//where to find new content
		var url = "/ttl_1m/_object/" + value.getAttribute("coid") + "/index.html";
		//create new requester
		nbcsp.updaters.push(new nbcsp.StatsUpdater(
			value,	//html element
			url,	
			60,	//refresh rate
			"updateable",
			"updating"
		));
	});
}

/* only look for stats updaters on shedule or scoreboard pages */
ibsys.DomLoadedEvent.add(function() {
	if(window.location.href.match(/_schedule|_scoreboard/)) {
		nbcsp.enableStatsUpdaters();
	}
});

