window.nbaContentReady = function(){};
nbaContentReady.nbaLoadSequencer = function()
{
	var msgLogger		= "onLoad Initialization Sequence Logger\n\n";
	var debugTimeout	= null;
	var debugInterval	= null;
	var elmStack 		= [];
	var isDOMReady 		= false; // has DOMContentLoaded or window.onload fired
	var pollTimer 		= null;
	
	this.setDebug			= _setDebug;
	this.setContentLoaded	= _setContentLoaded; 
	this.setLoggerMsg		= _setLoggerMsg; 
	this.getLoggerMsg		= _getLoggerMsg; 
	this.isContentLoaded 	= _isContentLoaded; 	
	this.onContentAvailable = _onContentAvailable;
	this.shortCircuitPoll	= _shortCircuitPoll;
	
	function _setLoggerMsg(oMsg){
		msgLogger += oMsg;
	}
	function _getLoggerMsg(){
		return msgLogger;
	}
	function _setDebug(oBoolean){
		if (oBoolean){
			_setDebugTimer();
		}else{
			_killDebugTimer();
		} 
	}
	function _setContentLoaded(oBoolean){
		isDOMReady = oBoolean;
	}
	function _isContentLoaded(){
		return isDOMReady;
	}
	function _hasNextSibling(el){
	  return el.nextSibling || (el.parentNode && _hasNextSibling(el.parentNode));
	}
	
	function _onContentAvailable(id, callback) {
		msgLogger += "- onContentAvailable(" + id + ")\n";
		elmStack.push({id:id, callback:callback});  
		_startPolling();
	}
	function _startPolling(){
		msgLogger += "startPolling()\n";
		if (pollTimer === null){
			pollTimer = setInterval(function(){_doPoll();}, 10);
		}  
	}
	function _doPoll(){
		msgLogger += "doPoll()\n";
		var notFound = [];
		for (var i=0; i<elmStack.length; i++) {
			var el = document.getElementById(elmStack[i].id);
			if (el && (_hasNextSibling(el) || isDOMReady === true)) {
				elmStack[i].callback();
			} else {
				notFound.push(elmStack[i]);
			}
		}
		elmStack = notFound;
		if (notFound.length < 1 || isDOMReady === true) {
			_stopPolling();
		}
	}
	function _stopPolling(){
		msgLogger += "stopPolling()\n";
		if (pollTimer != null){
			clearInterval(pollTimer);
			pollTimer = null;
		}
	}
	function _shortCircuitPoll(callBackObj){
		msgLogger += "shortCircuitPoll()\n";
		isDOMReady = true;
		callBackObj.execute();
	}
	function _setDebugTimer(){
		debugTimeout 	= setTimeout('alert(nbaPageLoadSequencer.getLoggerMsg())', 8000);
		debugInterval  	= setInterval('alert(nbaPageLoadSequencer.getLoggerMsg())', 20000);
	}
	function _killDebugTimer(){
		if (debugTimeout){debugTimeout = null;}
		if (debugInterval){
				clearInterval(debugInterval); 
				debugInterval = null;
		}
	}	
}
window.nbaPageLoadSequencer = new nbaContentReady.nbaLoadSequencer();
