MN.EPG = {EPGList : new Array()};

//Adds content to obtain 'program guide' information for.  If the user wants to have this
//library handle event listening for the content (and do something via a callback function),
//they need to pass in a reference to the player wrapper that will be playing the content
//when calling this function.
MN.EPG.AddContent = function(name, startURL, backLimit){
	this.EPGList[name]= new MN.EPG.EPG(startURL, backLimit);
}
//Starts obtaining the valid urls(qvt urls) for the given content.  When a url has been loaded,
//it will call the callback function passed in, giving it the updated url list, and a flag
//indicating if it has gotten all of the valid urls.  The user can optionally pass in a delay
//to wait inbetween loading urls.
MN.EPG.StartInitLoad = function(name, callback, delay){
	log('start init load');
	var epg = this.EPGList[name];
	if(epg){
		epg.callback = callback;
		if(delay)
			epg.delay = delay * 1000; //delay input is in seconds, setTimeout takes milliseconds	
		epg.GetQVT();
	}
	log('done init load');
}
//This will refresh the url list with a new starting url
MN.EPG.Refresh = function(name, callback, newStartURL){
	var epg = this.EPGList[name];
	if(epg){
		epg.urlList = new Array();
		epg.callback = callback;
		epg.delay = 0;
		epg.startURL = newStartURL;
		epg.url = newStartURL;	
		epg.GetQVT();
	}
}

//The EPG.EPG class represents an electronic programming guide.
MN.EPG.EPG = MN.Class();

MN.EPG.EPG.prototype.initialize = function(startURL, backLimit){
	this.startURL = startURL;
	this.backLimit = backLimit;
	this.urlList = new Array();
	this.initLoadDone = false;
	this.delay = 0;
	this.callback = null;
	this.url = startURL; //see explanation in OnQVTLoaded
}
MN.EPG.EPG.prototype.GetQVT = function(){
	log('getting qvt: ', this.url);
	var qvt = MN.QVT.AcquireQVT(this.url);  //see explanation in EPG.EPG.OnQVTLoaded
	if(qvt.IsLoading())
		MN.Event.Observe(qvt, 'TimelineLoaded', this.OnQVTLoaded);
	else
		this.OnQVTLoaded(qvt);	
}
MN.EPG.EPG.prototype.OnQVTLoaded = function(qvt){
	log('onQVTLoaded epg');
	MN.Event.StopObserving(qvt, 'TimelineLoaded', this.OnQVTLoaded);
	
	this.urlList.push(qvt.PrimaryURL());
	if(this.urlList.length != this.backLimit && qvt.PrevURL() != null){
		this.callback(this.urlList, false);
		var prevURL = qvt.PrevURL();
		log('getting with delay: ', this.delay);
		//in the correctly bound setTimeout function found below, there is no way
		//to pass in parameters to the function, but GetQVT needs to know what url
		//to get the QVT for.  The only way to overcome that obstacle is to set a
		//variable within the EPG.EPG instance and grab that via GetQVT. 
		this.url = prevURL; 
		setTimeout(this.GetQVT, this.delay); 
	}
	else{
		log('done loading urls');
		this.callback(this.urlList, true);
		this.initLoadDone = true;
	}
	MN.QVT.ReleaseQVT(qvt);
}




