
/* EPG Object */
function EPG_obj(curTime){
	this.xmlDoc = "";
	this.rootNode = "";
	this.channelCollection = new Object();
	this.categoryCollection = new Object();
	this.loadTime = new Date();
	this.lastServerTime = new Date();
	this.gridStart = new Date();
	this.gridEnd = new Date();
	this.earliestTime = new Date();
	this.latestTime = new Date();
	this.XMLrequestURL = "";
	this.htmlTargetID = "";
	this.statusCode = "";
	this.timeSelectBuilt = false;
	this.categorySelectBuilt = false;
	this.genreSelectBuilt = false;
	this.timezoneOffset = 0;
	this.channelArray = new Array();
	this.selectedTab = "schedule";
	this.setTimes(curTime);
	this.isDirty = true;
	this.savedScroll = 0;
}

EPG_obj.prototype.setDirty = function() {
	this.isDirty = true;
}

EPG_obj.prototype.setTimes = function(curTime) {
	// 1000 * 60 seconds * 180 minutes
	var threeHours = 1000 * 60 * 180;
	
	this.loadTime.setTime(curTime);
	this.gridStart.setTime(curTime);
	this.earliestTime.setTime(curTime);

	if(this.gridStart.getMinutes() >= 25 && this.gridStart.getMinutes() < 55) {
		this.gridStart.setMinutes(30,0,0);
	} else if(this.gridStart.getMinutes() >= 55) {
		this.gridStart.setMinutes(60,0,0);
	} else {
		this.gridStart.setMinutes(0,0,0);
	}
		
	this.gridEnd.setTime(this.gridStart.getTime() + threeHours);	
	
	this.earliestTime.setHours(0,0,0,0);
	this.latestTime.setTime(this.earliestTime.getTime() + 1209600000 + 86399000);
}

EPG_obj.prototype.addChannel = function(chName,chKey,chNumber,chTag,chShortDesc,chLink,chLogo,catKey,genreKey,genreName) {
	if(typeof this.categoryCollection[catKey] == "undefined") {
		var catName = "";
		if(catKey == "Music")
			catName = "Music";
		else if(catKey == "Best of SIRIUS")
			catName = "Best of SIRIUS";
		else if(catKey == "News")
			catName = "News";
		else if(catKey == "Sports")
			catName = "Sports";
		else if(catKey == "Talk & Entertainment")
			catName = "Talk & Entertainment";
		else
			catName = catKey;
			
		this.categoryCollection[catKey] = new EPG_Category(catKey,catName,this);
	}
	
	this.categoryCollection[catKey].addGenre(genreKey,genreName,chNumber);

	if(chNumber.indexOf('-') != -1) {
		var numArray = chNumber.split('-');
		
		for(i = numArray[0]; i <= numArray[1]; i++) {
			if(typeof this.channelCollection[i] == "undefined") {
				this.channelCollection[i] = new EPG_Channel(chName,chKey,i,chTag,chShortDesc,chLink,chLogo,this);
				
				this.categoryCollection[catKey].addChannel(i);
				
				if(this.channelArray.indexOf(i) == -1) {
					this.channelArray.push(i);
				}		
			}			
		}
	} else {
		if(typeof this.channelCollection[chNumber] == "undefined") {
			this.channelCollection[chNumber] = new EPG_Channel(chName,chKey,chNumber,chTag,chShortDesc,chLink,chLogo,this);
			
			this.categoryCollection[catKey].addChannel(chNumber);
			
			if(this.channelArray.indexOf(chNumber) == -1) {
				this.channelArray.push(chNumber);
			}		
		}	
	}

	


}

EPG_obj.prototype.addCategory = function(catKey,catName) {
	if(typeof this.categoryCollection[catKey] == "undefined"){
		this.categoryCollection[catKey] = new EPG_Category(catKey,catName);
	}
}

EPG_obj.prototype.addProgram = function(channelNum,pgName,pgKey,pgScheduleId,pgLink,pgShortDesc,pgLongDesc,pgStartTime,pgEndTime,pgDuration) {
	if(typeof this.channelCollection[channelNum].programCollection[pgScheduleId] == "undefined") {
		this.channelCollection[channelNum].programCollection[pgScheduleId] = new EPG_Program(pgName,pgKey,pgScheduleId,pgLink,pgShortDesc,pgLongDesc,pgStartTime,pgEndTime,pgDuration,this.channelCollection[channelNum]);
	}
}

EPG_obj.prototype.setTimezone = function(offset) {
	// need to take into account where the timezone was currently set
	var adjustment = offset - this.timezoneOffset;
	this.timezoneOffset = offset;
	
	var timeAdjust = 1000 * 60 * 60 * adjustment;
	var threeHours = 1000 * 60 * 180;	
}

EPG_obj.prototype.syncJumptime = function() {
	this.buildTimeSelect();
	$('jump_to_time').value = this.gridStart.getTime();
}

EPG_obj.prototype.navEarlierLater = function(multiplier) {
	var adjust = 1000 * 60 * 60 * multiplier;
	var threeHours = 1000 * 60 * 180;
	
	this.gridStart.setTime(this.gridStart.getTime() + adjust);
	this.gridEnd.setTime(this.gridStart.getTime() + threeHours);
	
	this.displayResults();	

	var direction = 0;
	
	if(multiplier < 0) {
		direction = -1;
	} else {
		direction = 1;
	}
	
	
	
	highlightBox(this.gridStart.formatDate("Ymd"), direction);

	this.syncJumptime();
}

EPG_obj.prototype.navDate = function(time) {
	var threeHours = 1000 * 60 * 180;
	var tempDate = new Date();
	
	
	tempDate.setDate(time.substring(6,8));
	tempDate.setMonth(time.substring(4,6)-1);
	tempDate.setDate(time.substring(6,8)); // setting date twice to ensure its correct on months where there's no 31st, etc. 
	tempDate.setYear(time.substring(0,4));
	
	this.gridStart.setDate(tempDate.getDate());
	this.gridStart.setMonth(tempDate.getMonth());
	this.gridStart.setDate(tempDate.getDate());// setting date twice to ensure its correct on months where there's no 31st, etc. 
	this.gridStart.setFullYear(tempDate.getFullYear());
	
	this.gridEnd.setTime(this.gridStart.getTime() + threeHours);
	
	this.displayResults();		
	
}

EPG_obj.prototype.navTime = function(time) {
	
	var threeHours = 1000 * 60 * 180;
	var tempDate = new Date();
	tempDate.setTime(time);
	this.gridStart.setHours(tempDate.getHours(), tempDate.getMinutes(), 0, 0);
	this.gridEnd.setTime(this.gridStart.getTime() + threeHours);
	
	this.displayResults();			
}

EPG_obj.prototype.buildCategorySelect = function() {

	var collection = this.categoryCollection;
	var catSelect = document.getElementById('channel_category');
	
	catSelect.options.length = 0;
	
	var index = 1;
	catSelect.options[0] = new Option("Please Select", "default");	
	for (category in collection) {
		catSelect.options[index] = new Option(collection[category].categoryName,category);
		index++;
	}
	
	this.categorySelectBuilt = true;

	if (readCookie('channel_category') != null)
		catSelect.value = readCookie('channel_category');
	
}

EPG_obj.prototype.buildGenreSelect = function(catKey) {

	if(catKey != 'default' && catKey != '' && this.selectedTab == "schedule") {
		var collection = this.categoryCollection[catKey].genreCollection;
		var genreSelect = document.getElementById('channel_genre');
	
		genreSelect.options.length = 0;
		
		var index = 1;
		
		genreSelect.options[0] = new Option("Please Select", "default");
	
		for (genre in collection) {
			genreSelect.options[index] = new Option(collection[genre].genreName,genre);
			index++;
		}	
	}

	if(index > 2) 
		document.getElementById("genreContainer").style.visibility = "visible";	
	else
		document.getElementById("genreContainer").style.visibility = "hidden";
		
	this.genreSelectBuilt = true;

	if (readCookie('channel_genre') != null && genreSelect) {
		var found = false;
		for(i = 0; i < genreSelect.options.length; i++) {
			if(genreSelect.options[i].value == readCookie('channel_genre')) {
				genreSelect.value = readCookie('channel_genre');
				found = true;
			}
		}

		if(found == false)
			createCookie('channel_genre','', 7);
	}
}

EPG_obj.prototype.buildTimeSelect = function() {

	var timeSelect = document.getElementById('jump_to_time');

	timeSelect.options.length = 0;
	
	var tempDate = new Date();
	tempDate.setTime(this.gridStart.getTime());
	
	tempDate.setHours(0, 0, 0, 0);
	var index = 0;
	var hour = 0;
	var ampm = "AM";
	var curHourMin = this.gridStart.getHours() + ":" + this.gridStart.getMinutes();
	
	for(var i=0;i<24;i++) {
		index = i * 2;
		hour = i;
		if(i == 0)
			hour = 12;
		if(i >= 13)
			hour = hour - 12;
		if(i >= 12)
			ampm = "PM";
				
		tempDate.setHours(i, 0, 0, 0);
		timeSelect.options[index] = new Option(hour + ":00 " + ampm, tempDate.getTime());
		if(tempDate.getHours() + ":" + tempDate.getMinutes() == curHourMin) {
			timeSelect.selectedIndex = index;
		}
		tempDate.setHours(i, 30, 0, 0);		
		timeSelect.options[index + 1] = new Option(hour + ":30 " + ampm, tempDate.getTime());
		if(tempDate.getHours() + ":" + tempDate.getMinutes() == curHourMin) {
			timeSelect.selectedIndex = index + 1;
		}		
	}
	
	this.timeSelectBuilt = true;
}

EPG_obj.prototype.createDTHeader = function() {
	var weekday=new Array(7)
	weekday[0]="SUNDAY"
	weekday[1]="MONDAY"
	weekday[2]="TUESDAY"
	weekday[3]="WEDNESDAY"
	weekday[4]="THURSDAY"
	weekday[5]="FRIDAY"
	weekday[6]="SATURDAY"

	var month=new Array(12)
	month[0]="JAN"
	month[1]="FEB"
	month[2]="MAR"
	month[3]="APR"
	month[4]="MAY"
	month[5]="JUN"
	month[6]="JUL"
	month[7]="AUG"
	month[8]="SEP"
	month[9]="OCT"
	month[10]="NOV"
	month[11]="DEC"


	tempDiv = document.createElement('div');
	tempDiv.id = 'epg_grid_header';
	
	dateContainer = document.createElement('div');
	dateContainer.id = 'date_container';
	var month = this.gridStart.getMonth() + 1;
	dateContainer.innerHTML = weekday[this.gridStart.getDay()] + ", " + month + "/" + this.gridStart.getDate();
		
	tempDiv.appendChild(dateContainer);
	
	tempDate = new Date();
	tempDate.setTime(this.gridStart.getTime());
		
	var timer = tempDate.getTime();
	var hour = '';
	var min = '';

	while(timer < this.gridEnd.getTime()) {
	
	  var timeContainer = document.createElement('div');	  
	  timeContainer.className = 'time_container';
  
	  min = tempDate.getMinutes();
	  if(min < 10) 
	  	min = "0" + min.toString();
	  	
	  if(tempDate.getHours() >= 13) {
	  	hour = (tempDate.getHours() - 12) + ":" + min + " PM";
	  } else {
	  	if(tempDate.getHours() == 0)
		  	hour = "12:" + min + " AM";
		else if(tempDate.getHours() == 12)
			hour = "12:" + min + " PM";
	  	else 
		  	hour = tempDate.getHours() + ":" + min + " AM";
	  }
	  	
	  timeContainer.innerHTML = hour;
	  
	  tempDiv.appendChild(timeContainer);
	  
	  // increment 30 mins (1800000 milliseconds = 1000m * 60s * 30m)
	  timer += 1800000;
	  tempDate.setTime(tempDate.getTime() + 1800000);
	}
	
	return tempDiv;
}

//var showChannels = Array(184,187,178,191,200,197,113,179,189,16,190,241,199,186,203,193,177,188,198,181,195,176,196,183,180,174,182,185,201,242,194,192);

var showChannels;
var globalScheduleId;
var globalChannelNum;

EPG_obj.prototype.loadChannelPageData = function() {
	var obj = this;
	var timeAdjust = 1000 * 60 * 60 * this.timezoneOffset;	
	
	var errFunc = function(t) {
	    alert('Error ' + t.status + ' -- ' + t.statusText);
	}	
	
	var programHandler = function(t) {
		var JSON_string = t.responseText;
		var myObject = eval('(' + JSON_string + ')');

		id = myObject.program.programId;
		document.getElementById("whats-on-sub-" + id).innerHTML = myObject.program.description;

		var addfav = document.createElement('span');	
		addfav.className = 'fav-span';
						
		if(myObject.program.isGapProgram == false) {
			if((isFavoriteShow(globalScheduleId))) {
				addfav.innerHTML = 'Already a Favorite: <a href="/onxm/index.cfm?view=favorites">View My Favorite Shows</a>';
			} else if (myObject.program.series) {
				if (isFavoriteSeries(myObject.program.series.programGroupId)) 
					addfav.innerHTML = 'Already a Favorite: <a href="/onxm/index.cfm?view=favorites">View My Favorite Shows</a>';			
				else if (!(isFavoriteSeries(myObject.program.series.programGroupId)))
					addfav.innerHTML = '<a onClick="showWeekAddFavoriteShow(' + globalChannelNum + ',' + globalScheduleId + ',' + myObject.program.series.programGroupId + ')">Add to My Favorite Shows</a>';
			} else {
				addfav.innerHTML = '<a onClick="showWeekAddFavoriteShow(' + globalChannelNum + ',' + globalScheduleId + ', null)">Add to My Favorite Shows</a>';
			}
		}
						
		if(typeof myObject.program.showPageLink != "undefined") {
			document.getElementById("whats-on-white").innerHTML += "<a href='" + myObject.program.showLink + "'>View Show Page</a> | ";
		}		

		document.getElementById("whats-on-white").appendChild(addfav);				
	}
		
	var handlerFunc = function(t) {
		var JSON_string = t.responseText;
		var myObject = eval('(' + JSON_string + ')');

		document.getElementById("whats-on-white").innerHTML = "";

		var limit = 0;
		if(myObject.programScheduleList.length < 10)
			limit = myObject.programScheduleList.length;
		else
			limit = 10;
		
		for (var i=0; i<limit; i++) {
			obj.addProgram(myObject.programScheduleList[i].channelNum,myObject.programScheduleList[i].epgProgram.name,myObject.programScheduleList[i].epgProgram.programId,myObject.programScheduleList[i].scheduleId,'','','',myObject.programScheduleList[i].startTime,myObject.programScheduleList[i].endTime,myObject.programScheduleList[i].duration,'');		
			whats_on_main = document.createElement("p");
			whats_on_main.className = "whats-on-main";
			whats_on_main.innerHTML = myObject.programScheduleList[i].epgProgram.name + "<br/>";

			programStartTime = myObject.programScheduleList[i].startTime;
			parsedProgramStartTime = new Date(programStartTime.substring(0,4),(programStartTime.substring(5,7)-1),programStartTime.substring(8,10),programStartTime.substring(11,13),programStartTime.substring(14,16));
			parsedProgramStartTime.setTime(this.parsedProgramStartTime.getTime() - timeAdjust);			
			formattedProgramStartTime = parsedProgramStartTime.formatDate("g:i A");

			programEndTime = myObject.programScheduleList[i].endTime;
			parsedProgramEndTime = new Date(programEndTime.substring(0,4),(programEndTime.substring(5,7)-1),programEndTime.substring(8,10),programEndTime.substring(11,13),programEndTime.substring(14,16));					
			parsedProgramEndTime.setTime(this.parsedProgramEndTime.getTime() - timeAdjust);
			formattedProgramEndTime = parsedProgramEndTime.formatDate("g:i A");	
								
			whats_on_main.innerHTML += formattedProgramStartTime + " - " + formattedProgramEndTime;

			whats_on_sub = document.createElement("p");
			whats_on_sub.className = "whats-on-sub";
			whats_on_sub.id = "whats-on-sub-" + myObject.programScheduleList[i].epgProgram.programId;

			document.getElementById("whats-on-white").appendChild(whats_on_main);
			document.getElementById("whats-on-white").appendChild(whats_on_sub);

			globalScheduleId = myObject.programScheduleList[i].scheduleId;
			globalChannelNum = myObject.programScheduleList[i].channelNum;

			param_string = "programId=" + myObject.programScheduleList[i].epgProgram.programId;
			new Ajax.Request('/epg.program_details.cfm', {parameters:param_string, asynchronous: false, onSuccess:programHandler, onFailure:errFunc});	
		}		
	}
	
	var highlightHandler = function(t) {
		var JSON_string = t.responseText;
		var myObject = eval('(' + JSON_string + ')');

		if(typeof myObject.highlightScheduleList[0] != "undefined") {

			whats_on_main = document.createElement("p");
			whats_on_main.className = "whats-on-main";

			whats_on_main.innerHTML = myObject.highlightScheduleList[0].epgProgram.name + "<br/>";

			programStartTime = myObject.highlightScheduleList[0].startTime;
			parsedProgramStartTime = new Date(programStartTime.substring(0,4),(programStartTime.substring(5,7)-1),programStartTime.substring(8,10),programStartTime.substring(11,13),programStartTime.substring(14,16));
			parsedProgramStartTime.setTime(this.parsedProgramStartTime.getTime() - timeAdjust);			
			formattedProgramStartTime = parsedProgramStartTime.formatDate("g:i A");

			programEndTime = myObject.highlightScheduleList[0].endTime;
			parsedProgramEndTime = new Date(programEndTime.substring(0,4),(programEndTime.substring(5,7)-1),programEndTime.substring(8,10),programEndTime.substring(11,13),programEndTime.substring(14,16));		
			parsedProgramEndTime.setTime(this.parsedProgramEndTime.getTime() - timeAdjust);			
			formattedProgramEndTime = parsedProgramEndTime.formatDate("g:i A");	
								
			whats_on_main.innerHTML += formattedProgramStartTime + " - " + formattedProgramEndTime;

			whats_on_sub = document.createElement("p");
			whats_on_sub.className = "whats-on-sub";
			whats_on_sub.innerHTML = myObject.highlightScheduleList[0].epgProgram.description;

			document.getElementById("whats-on-yellow").innerHTML = "";
			document.getElementById("whats-on-yellow").appendChild(whats_on_main);
			document.getElementById("whats-on-yellow").appendChild(whats_on_sub);
			
			if(typeof myObject.highlightScheduleList[0].epgProgram.showPageLink != "undefined") {
				document.getElementById("whats-on-yellow").innerHTML += "<a href='" + myObject.highlightScheduleList[0].epgProgram.showPageLink.url + "'>View Show Page</a> | ";
			}
			
			var addfav = document.createElement('span');	
			addfav.className = 'fav-span';
			var highlightId = myObject.highlightScheduleList[0].scheduleId
				
			if((isFavoriteShow(highlightId))) {
				addfav.innerHTML = 'Already a Favorite: <a href="/onxm/index.cfm?view=favorites">View My Favorite Shows</a>';
			} else if (myObject.highlightScheduleList[0].epgProgram.series) {
				if (isFavoriteSeries(myObject.highlightScheduleList[0].epgProgram.series.programGroupId)) 
					addfav.innerHTML = 'Already a Favorite: <a href="/onxm/index.cfm?view=favorites">View My Favorite Shows</a>';			
				else if (!(isFavoriteSeries(myObject.highlightScheduleList[0].epgProgram.series.programGroupId)))
					addfav.innerHTML = '<a onClick="showWeekAddFavoriteShow(' + globalChannelNum + ',' + highlightId + ',' + myObject.highlightScheduleList[0].epgProgram.series.programGroupId + ')">Add to My Favorite Shows</a>';
			} else {
				addfav.innerHTML = '<a onClick="showWeekAddFavoriteShow(' + globalChannelNum + ',' + highlightId + ', null)">Add to My Favorite Shows</a>';
			}	
			
			document.getElementById("whats-on-yellow").appendChild(addfav);			
			document.getElementById("whats-on-yellow").style.visibility = "visible";
			document.getElementById("whats-on-yellow").style.display = "";

        }
	}

	var padHandler = function(t) {
		var XML_string = t.responseXML;

		rootNode = XML_string.getElementsByTagName('paddata').item(0);
		events = rootNode.getElementsByTagName('event');
		if(events[0].getElementsByTagName('artist').item(0).firstChild) {
			artist = events[0].getElementsByTagName('artist').item(0).firstChild.data;
			song = events[0].getElementsByTagName('songtitle').item(0).firstChild.data;
			
			document.getElementById("on-xm-pad-data").innerHTML = artist + " - " + song;
		}
	}	

	
	showChannels = this.channelArray;
	var channel_string = showChannels.join(',') 
	// this shouldn't be necessary
	channel_string = channel_string.replace(/-/g,"");

	collection = this.channelCollection;
	for (channel in collection) {
		collection[channel].programCollection = new Object();
	}
	
	var tempStartDate = new Date();
	var tempEndDate = new Date();
	var threeHours = 1000 * 60 * 1440;	

	tempStartDate.setTime(this.gridStart.getTime());
	tempEndDate.setTime(tempStartDate.getTime() + threeHours);

	var startDate = tempStartDate.formatDate("dmYHi") + '00';	
	var endDate = tempEndDate.formatDate("dmYHi") + '00';	
	
	param_string = 'channelNums=' + channel_string + '&startDate=' + startDate + '&endDate=' + endDate;
	highlight_param_string = 'channelNums=' + channel_string + '&startDate=' + startDate + '&endDate=' + endDate + '&resultCount=1';	
	pad_param_string = 'channel=' + channel_string;
	
	new Ajax.Request('/epg.program_schedules.cfm', {parameters:param_string, onSuccess:handlerFunc, onFailure:errFunc});	
	new Ajax.Request('/epg.highlight_schedules.cfm', {parameters:highlight_param_string, onSuccess:highlightHandler, onFailure:errFunc});		
	new Ajax.Request('http://www.xmradio.com/padData/pad_provider.jsp', {parameters:pad_param_string, onSuccess:padHandler, onFailure:errFunc});		
}


EPG_obj.prototype.displayResults = function() {

	this.savedScroll = $('epg_grid_scroll').scrollTop;
	
	//hide and display previous and next buttons based on time
	var loadDateElements = document.getElementById('dategrid');
	if(loadDateElements) {
		var startCheck = new Date();
		startCheck.setTime(this.loadTime.getTime());
			
		startCheck.setHours(startCheck.getHours());
		startCheck.setHours(3);
		startCheck.setMinutes(0);
		
		if (this.gridStart < startCheck) {
			$('earlier').style.display = 'none';
		}
			
		else
			$('earlier').style.display = '';
	
			
		var endCheck = new Date();
		endCheck.setTime(this.loadTime.getTime());
		
		endCheck.setHours(endCheck.getHours() + 312);
		endCheck.setHours(21);
		endCheck.setMinutes(0);
	
	
		if (this.gridStart > endCheck) {
			$('later').style.display = 'none';
			this.gridStart.setHours(21);
			this.gridStart.setMinutes(0);
			this.gridEnd.setHours(0);
			this.gridEnd.setMinutes(0);
			this.syncJumptime();
		}
			
		else
			$('later').style.display = '';
	}
			
	if ($('schedule_content').style.display == 'none')
		return;

	if(loadDateElements) {
		var rigEnd = new Date(this.gridStart);
		rigEnd.setHours(rigEnd.getHours() + 24);
		this.loadFeaturedHighlight(this.gridStart.getTime(), rigEnd.getTime(), 1);
	}
		
	var scroll_div = document.getElementById('epg_grid_scroll_inner');
	
	if(scroll_div) {
		scroll_div.innerHTML = "";
		var temp_div = document.createElement('DIV');
		temp_div.id = "loadingDiv";
		loadingImg = document.createElement('IMG');
		loadingImg.setAttribute("src","/images/epg/main_loading.gif");
		loadingImg.setAttribute("width","134");
		loadingImg.setAttribute("height","113");
		loadingImg.setAttribute("border","0");
		loadingImg.setAttribute("alt","Loading...");
		temp_div.appendChild(loadingImg);
		scroll_div.appendChild(temp_div);
	}
	
	var obj = this;
	
	var handlerFunc = function(t) {
	
		var JSON_string = t.responseText;
		var myObject = eval('(' + JSON_string + ')');
		
		for (var i=0; i<myObject.programScheduleList.length; i++) {
			obj.addProgram(myObject.programScheduleList[i].channelNum,myObject.programScheduleList[i].epgProgram.name,myObject.programScheduleList[i].epgProgram.programId,myObject.programScheduleList[i].scheduleId,'','','',myObject.programScheduleList[i].startTime,myObject.programScheduleList[i].endTime,myObject.programScheduleList[i].duration,'');		
		}

		obj.printResults();		
		$('epg_grid_scroll').scrollTop = obj.savedScroll;
	}
	
	var errFunc = function(t) {
	    alert('Error ' + t.status + ' -- ' + t.statusText);
	}	


	var catSelect = document.getElementById('channel_category');
	var genreSelect = document.getElementById('channel_genre');
	
	if(catSelect.value != '' && catSelect.value != 'default') {
		if(genreSelect.value != '' && genreSelect.value != 'default')
			showChannels = this.categoryCollection[catSelect.value].genreCollection[genreSelect.value].channelArray;
		else 
			showChannels = this.categoryCollection[catSelect.value].channelArray;
		
		if(loadDateElements) {
			if($F('show_only_favorites') == 'on') {
				var newChannelArray = new Array();
				var favChannels = saved_favorites_array;
				var index = 0;
				for(var j = 0;j < favChannels.length; j++) {
					index = showChannels.indexOf(favChannels[j]);
					if(index != -1) {
						newChannelArray.push(showChannels[index]);
					}
				}
				showChannels = newChannelArray;
			}
		}		
	} else {
		
		if(loadDateElements && $F('show_only_favorites') == 'on') {
			showChannels = saved_favorites_array;
		} else {
			showChannels = this.channelArray;
		}
	}
	
	if(showChannels.length == 0) { 
		obj.printResults();
	} else  {	
	
		var channel_string = showChannels.join(',') 
		// this shouldn't be necessary
		channel_string = channel_string.replace(/-/g,"");

		collection = this.channelCollection;
		for (channel in collection) {
			collection[channel].programCollection = new Object();
		}
		
		var tempStartDate = new Date();
		var tempEndDate = new Date();
		var timeAdjust = 1000 * 60 * 60 * this.timezoneOffset;
		var threeHours = 1000 * 60 * 180;	
	
		tempStartDate.setTime(this.gridStart.getTime() + timeAdjust);
		tempEndDate.setTime(tempStartDate.getTime() + threeHours);
		
		var startDate = tempStartDate.formatDate("dmYHi") + '00';	
		var endDate = tempEndDate.formatDate("dmYHi") + '00';	

		param_string = 'channelNums=' + channel_string + '&startDate=' + startDate + '&endDate=' + endDate;
		new Ajax.Request('/epg.program_schedules.cfm', {parameters:param_string, onSuccess:handlerFunc, onFailure:errFunc});
	}
	

	
	
}

EPG_obj.prototype.printResults = function() {

	var loadDateElements = document.getElementById('dategrid');

	if(!this.timeSelectBuilt) {
		if(loadDateElements)
			this.buildTimeSelect();
	}
 	if(!this.categorySelectBuilt)
		this.buildCategorySelect();
	if(!this.genreSelectBuilt)
		this.buildGenreSelect(document.getElementById('channel_category').value);

	collection = this.channelCollection;

	var curDT = document.getElementById("epg_grid_header");
	var curScroll = document.getElementById("epg_grid_scroll_inner");
	var epg_scroll_outer = document.getElementById("epg_grid_scroll");
	var sched = document.getElementById("schedule");
	
	
	sched.replaceChild(this.createDTHeader(), curDT);	
	//document.getElementById('schedule').innerHTML = "";
	//document.getElementById('schedule').appendChild(this.createDTHeader());
	
	epg_scroll = document.createElement('div');
	epg_scroll_holder = document.createElement('div');



		
/*
	var all_collection = collection;	

	collection = new Object();
	
	for (var i=0; i<showChannels.length; i++) {
		var channel_num = showChannels[i];
		collection[channel_num] = all_collection[channel_num];	
	}
*/

	var tempStartDate = new Date();
	var tempEndDate = new Date();
	var timeAdjust = 1000 * 60 * 60 * this.timezoneOffset;
	var threeHours = 1000 * 60 * 180;	

	tempStartDate.setTime(this.gridStart.getTime() + timeAdjust);
	tempEndDate.setTime(tempStartDate.getTime() + threeHours);

	var counter = 0;
	
	if (showChannels.length < 1) {
	
		var blankFavorites = document.createElement('div');
		blankFavorites.id = 'blankFavorites';

		$('loadingDiv').innerHTML = '';	
		
	
		$('loadingDiv').appendChild(blankFavorites);
	
	
		if (navigator.cookieEnabled == 0) {
			blankFavorites.innerHTML = $('nofavorites_error1').innerHTML;
		}
		
		
		else if (readCookie('saved_favorites') == '' || readCookie('saved_favorites') == null) {
			blankFavorites.innerHTML = $('nofavorites_error2').innerHTML;
		}
		
		else {
			blankFavorites.innerHTML = $('nofavorites_error3').innerHTML;		
		}
	
		return;
	}
	
	for (channel in collection) {

		if(showChannels.indexOf(channel) != -1) {
		
		tempDiv1 = document.createElement('div');
		tempDiv1.className = 'channel-row';
		
		ct = document.createElement('div');
		ct.id = 'channel-' + channel + '-tooltip';
		ct.className = 'channel-tooltip';
		
		cttop = document.createElement('div');
		cttop.className = 'channel-tooltip-top';
		ct.appendChild(cttop);
		
		ctmiddle = document.createElement('div');
		ctmiddle.className = 'channel-tooltip-middle';
		
		cttitle = document.createElement('div');
		cttitle.className = 'channel-tooltip-title';
		cttitle.innerHTML = '<b>' + collection[channel].channelNumber + '</b> ' + collection[channel].channelName;
		ctmiddle.appendChild(cttitle);
	
	
		ctdesc1 = document.createElement('div');
		ctdesc1.className = 'channel-tooltip-desc1';	
		ctdesc1.innerHTML = collection[channel].channelTag;	
		ctmiddle.appendChild(ctdesc1);	
		
		ctdesc2 = document.createElement('div');
		ctdesc2.className = 'channel-tooltip-desc2';	
		ctdesc2.innerHTML = collection[channel].channelShortDesc;
		ctmiddle.appendChild(ctdesc2);	
		
		ct.appendChild(ctmiddle);		

		ctbottom = document.createElement('div');
		ctbottom.className = 'channel-tooltip-bottom';
		ct.appendChild(ctbottom);

		tempDiv1.appendChild(ct);	
	
//		document.getElementById('schedule').appendChild(tempDiv1);


		tempDiv2 = document.createElement('div');
		tempDiv2.className = 'channel';
		tempDiv2.id = channel + '-channel-cell';
	
		logo_img = document.createElement('img');
		logo_img.className = 'channel_logo';
//		logo_img.src = '/images/epg/channel-logo.gif';
		logo_img.src = '/images/channels/logos/small/' + collection[channel].channelNumber + '.gif';
//		logo_img.hspace = "5";
		logo_img.align = "left";
		
		var channel_p = document.createElement('span');
		
		var channel_number = document.createElement('span');
		channel_number.className = 'pad_number';
		
		var spaces = '';
		if(collection[channel].channelNumber < 10)
			spaces = '&nbsp;&nbsp;';
		else if(collection[channel].channelNumber < 100)
			spaces = '&nbsp;';
			
		channel_number.innerHTML = spaces + collection[channel].channelNumber;
		
		var channel_wrapper = document.createElement('div');
		channel_wrapper.id = "name_wrapper";
		
		var channel_float = document.createElement('div');
		channel_float.id = "floating";
		
		var channel_name_wrapper_1 = document.createElement('div');
		var channel_name_wrapper_2 = document.createElement('div');		
		channel_name_wrapper_2.id = channel + '-name-wrapper';
		
		var name_p = document.createElement('p');
		
		var channel_link = document.createElement('a');
		channel_link.className = 'channel_name';
		channel_link.innerHTML = collection[channel].channelName;
		channel_link.setAttribute("onMouseOver", "channeltooltip(" + channel + ")");
		channel_link.setAttribute("onMouseOut", "exitchanneltooltip(" + channel + ")");
		channel_link.setAttribute("onClick", "rig.channelCollection[" + channel + "].showDetails('details_" + collection[channel].channelNumber + "')");

		name_p.appendChild(channel_link);
		
		channel_name_wrapper_2.appendChild(name_p);
		channel_name_wrapper_1.appendChild(channel_name_wrapper_2);
		channel_float.appendChild(channel_name_wrapper_1);
		channel_wrapper.appendChild(channel_float);
			
		channel_p.appendChild(channel_number);
		channel_p.appendChild(channel_wrapper);

		tempDiv2.appendChild(logo_img);
		tempDiv2.appendChild(channel_p);	
		

		tempDiv1.appendChild(tempDiv2);
		
		tempdate = new Date();
		
		for (program in collection[channel].programCollection) {

			prog = document.createElement('div');
			prog.className = 'program';
			prog.id = program + '-program-cell'
			var durationHours = collection[channel].programCollection[program].programDuration/3600000;
			var trueDurationHours = Math.round((collection[channel].programCollection[program].programDuration/3600000) * 60);
			var programStartTime = collection[channel].programCollection[program].programStartTime;
			var programEndTime = collection[channel].programCollection[program].programEndTime;
			
			var parsedProgramStartTime = new Date(programStartTime.substring(0,4),(programStartTime.substring(5,7)-1),programStartTime.substring(8,10),programStartTime.substring(11,13),programStartTime.substring(14,16));
			var parsedProgramEndTime = new Date(programEndTime.substring(0,4),(programEndTime.substring(5,7)-1),programEndTime.substring(8,10),programEndTime.substring(11,13),programEndTime.substring(14,16));		

			if (parsedProgramStartTime < tempStartDate) {
				//the actual duration is set to the start
				parsedProgramStartTime = tempStartDate;
				durationHours = (parsedProgramEndTime - parsedProgramStartTime)/3600000;
			}
			
			if (parsedProgramEndTime >= tempEndDate) {
				parsedProgramEndTime = tempEndDate;
				durationHours = (parsedProgramEndTime - parsedProgramStartTime)/3600000;
			}
			
			// temporary frontend fix for programs less than 1 min long. Shouldn't be programs <1 min. 
			if (durationHours < 0.0167){
			durationHours = 0.0167;
			}
			var programWidth = (durationHours * 180) - 1;
			
			prog.style.width = programWidth + 'px';
			prog.id = program + '-program-cell';
			
			program_name = document.createElement('a');
			program_name.className = 'channel_name';
			program_name.innerHTML = collection[channel].programCollection[program].programName;
			program_name.setAttribute("onMouseOver", "collection[" + channel + "].programCollection[" + program + "].showTooltip()");
			program_name.setAttribute("onMouseOut", "collection[" + channel + "].programCollection[" + program + "].exitTooltip()");
			program_name.setAttribute("onClick", "collection[" + channel + "].programCollection[" + program + "].showDetails('details_" + collection[channel].channelNumber + "')");

			prog.appendChild(program_name);

			ct = document.createElement('div');
			ct.id = 'program-' + program + '-tooltip';
			ct.className = 'channel-tooltip';
			
			cttop = document.createElement('div');
			cttop.className = 'channel-tooltip-top';
			ct.appendChild(cttop);
			
			ctmiddle = document.createElement('div');
			ctmiddle.className = 'channel-tooltip-middle';
			
			cttitle = document.createElement('div');
			cttitle.className = 'program-tooltip-title';
			cttitle.innerHTML = collection[channel].programCollection[program].programName;
			ctmiddle.appendChild(cttitle);
			
			ctdesc2 = document.createElement('div');
			ctdesc2.className = 'program-tooltip-desc1';	
			durationMinutes = durationHours * 60;
			ctdesc2.innerHTML = '<b>' + channel + '</b>&nbsp;' + collection[channel].channelName + ' (' + trueDurationHours + ' mins)';	
			ctmiddle.appendChild(ctdesc2);	
			
			ct.appendChild(ctmiddle);		
	
			ctbottom = document.createElement('div');
			ctbottom.className = 'channel-tooltip-bottom';
			ct.appendChild(ctbottom);
	
			prog.appendChild(ct);
			tempDiv1.appendChild(prog);			
		}		

		counter++;

		if(counter == 8) {
			// this is an optimization - appending each child to epg scroll takes a very long time for a lot of channels
			epg_scroll.appendChild(epg_scroll_holder);																		
			epg_scroll_holder = document.createElement('div');
			counter = 0;
		}		

		epg_scroll_holder.appendChild(tempDiv1);

		//hack
		//document.getElementById('schedule').innerHTML += "<div style='clear: both'></div>";
		epg_scroll_holder.innerHTML += "<div style='clear: both'></div>";
	
	
		hiddenDiv = document.createElement('div');
		hiddenDiv.className = 'details_hidden_div';
		hiddenDiv.id = 'details_' + collection[channel].channelNumber;
		
		epg_scroll_holder.appendChild(hiddenDiv);
		
		}
	}
	
	epg_scroll.appendChild(epg_scroll_holder);
	
	/* adds a gray background below the channels if there are not enough to fill out the space */
	if(showChannels.length < 6) {
		var diff = 6 - showChannels.length;
		var spacer_div = document.createElement('div');
		spacer_div.style.height = (40 * diff) + 'px';
		
		epg_scroll.appendChild(spacer_div);
	}

	epg_scroll.id = 'epg_grid_scroll_inner';	
	epg_scroll.className = "tempclass";
	if(loadDateElements) 
		epg_scroll.setAttribute("onScroll", "rig.showFeaturedCollapsed()");
	epg_scroll_outer.replaceChild(epg_scroll, curScroll);
	
	// need this because we couldn't get the channel names to vertically align
	var temp_object;
	var version = parseFloat(navigator.appVersion.split("MSIE")[1]);
	
	if (version > 6) {
		for (channel in collection) {
			temp_object = document.getElementById(channel + '-name-wrapper');

			if(temp_object) {
				if(temp_object.offsetHeight > 50) {
					temp_object.style.margin = '-7px 0px 0px 0px';
				}
			}
		}
	}
//	sched.appendChild(epg_scroll);	
}

EPG_obj.prototype.loadFeaturedHighlight = function(startDate, endDate, resultCount) {

	var obj = this;
	var timeAdjust = 1000 * 60 * 60 * this.timezoneOffset;

	var tempStartDate = new Date();
	var tempEndDate = new Date();
	tempStartDate.setTime(startDate + timeAdjust);
	tempEndDate.setTime(endDate + timeAdjust);

	var handlerFunc = function(t) {

		var JSON_string = t.responseText;
		var myObject = eval('(' + JSON_string + ')');

		name = myObject.highlightScheduleList[0].epgProgram.name;
		channelNum = myObject.highlightScheduleList[0].channelNum
		var description = myObject.highlightScheduleList[0].epgProgram.description;
		
		programStartTime = myObject.highlightScheduleList[0].startTime;
		parsedProgramStartTime = new Date(programStartTime.substring(0,4),(programStartTime.substring(5,7)-1),programStartTime.substring(8,10),programStartTime.substring(11,13),programStartTime.substring(14,16));
		parsedProgramStartTime.setTime(parsedProgramStartTime.getTime() - timeAdjust);
		formattedProgramStartTime = parsedProgramStartTime.formatDate("g:i A");

		programEndTime = myObject.highlightScheduleList[0].endTime;
		parsedProgramEndTime = new Date(programEndTime.substring(0,4),(programEndTime.substring(5,7)-1),programEndTime.substring(8,10),programEndTime.substring(11,13),programEndTime.substring(14,16));		
		parsedProgramEndTime.setTime(parsedProgramEndTime.getTime() - timeAdjust);
		formattedProgramEndTime = parsedProgramEndTime.formatDate("g:i A");	
		
		channelName = obj.channelCollection[channelNum].channelName;
		channelLink = obj.channelCollection[channelNum].channelLink;		

		var content = document.getElementById("featured-highlight-expanded-inner");
		var expanded = document.getElementById("featured-highlight-expanded");
		
		var collapseLink = document.createElement("a");
		collapseLink.href = "javascript:rig.showFeaturedCollapsed();";
		
		collapseImg = document.createElement("img");
		collapseImg.src = "/images/epg/btn/x.jpg";
		collapseImg.align = "right";
		collapseImg.alt = "";
	
		collapseLink.appendChild(collapseImg);
									
		var leftDiv = document.createElement("DIV");
		leftDiv.id = "featured-highlight-left";
							
		var timeSpan = document.createElement("SPAN");
		timeSpan.className = "featured_highlight_time";
		timeSpan.innerHTML = formattedProgramStartTime + " &ndash; " + formattedProgramEndTime;

		var logo_img = document.createElement('img');
		logo_img.src = '/images/channels/logos/large/' + channelNum + '.jpg';
				
		var firstPar = document.createElement('p');
		var firstAnchor = document.createElement('a');
		firstAnchor.href = channelLink;
		firstAnchor.innerHTML = channelName;
		firstPar.appendChild(firstAnchor);

		var secondPar = document.createElement('p');
		var secondAnchor = document.createElement('a');
		secondAnchor.href = channelLink;		
		secondAnchor.innerHTML = "XM " + channelNum;
		secondPar.appendChild(secondAnchor);
		
		leftDiv.appendChild(timeSpan);
		leftDiv.appendChild(logo_img);
		leftDiv.appendChild(firstPar);
		leftDiv.appendChild(secondPar);		

		var rightDiv = document.createElement("DIV");
		rightDiv.id = "featured-highlight-right";
		
		var showTitle = document.createElement("H1");
		showTitle.innerHTML = name;
	
		var thirdPar = document.createElement('p');	
		thirdPar.innerHTML = description;

		var fourthPar = document.createElement('p');
		fourthPar.style.margin = "12px 0px 0px 0px";
//		fourthPar.className = "featured_highlight_links";
		var thirdAnchor = document.createElement("a");
		thirdAnchor.href = "/onxm/this-week-on-xm.cfm";
		thirdAnchor.className = "dotted_top";
		thirdAnchor.innerHTML = "View This Week\'s Featured Shows";
		fourthPar.style.padding = "5px 0px 0px 0px";		
		fourthPar.appendChild(thirdAnchor);
	
		rightDiv.appendChild(showTitle);
		rightDiv.appendChild(thirdPar);
		rightDiv.appendChild(fourthPar);
		
		content.innerHTML = '';
		content.appendChild(collapseLink);
		content.appendChild(leftDiv);
		content.appendChild(rightDiv);
		content.innerHTML += "<div style='clear: both;'>&nbsp;</div>";		

		if(expanded.offsetHeight != 0) {
			if(expanded.offsetHeight > 140) {
				var delta = 108 + (expanded.offsetHeight - 140);
				expanded.style.marginTop = "-" + delta + "px";
			} else {
				expanded.style.marginTop = "-108px";
			}
		}
				
		$('featured-highlight-content').innerHTML = '<strong>' + name + '</strong> | ' + channelName + ' | ' + formattedProgramStartTime + ' - ' + formattedProgramEndTime;
	}
	
	var errFunc = function(t) {
	    alert('Error ' + t.status + ' -- ' + t.statusText);
	}	
	
	var paramStartDate = tempStartDate.formatDate('dmYHi') + '00';
	var paramEndDate = tempEndDate.formatDate('dmYHi') + '00';
	
	param_string = 'startDate=' + paramStartDate + '&endDate=' + paramEndDate + '&resultCount=' + resultCount;
	new Ajax.Request('/epg.highlight_schedules.cfm', {parameters:param_string, onSuccess:handlerFunc, onFailure:errFunc});
}

EPG_obj.prototype.showFeaturedExpanded = function() {
		
	var expanded = document.getElementById("featured-highlight-expanded");
	var collapsed = document.getElementById("featured-highlight");
	
	if(expanded) {
		collapsed.style.visibility = "hidden";
		collapsed.style.display = "none";
		
		expanded.style.visibility = "visible";
		expanded.style.display = "";
	}

	if(expanded.offsetHeight > 140) {
		var delta = 108 + (expanded.offsetHeight - 140);
		expanded.style.marginTop = "-" + delta + "px";
	} else {
		expanded.style.marginTop = "-108px";
	}
}

EPG_obj.prototype.showFeaturedCollapsed = function() {

	var expanded = document.getElementById("featured-highlight-expanded");
	var collapsed = document.getElementById("featured-highlight");

	if(expanded) {	
		expanded.style.visibility = "hidden";
		expanded.style.display = "none";
		
		collapsed.style.visibility = "visible";
		collapsed.style.display = "";
	}
}




