/**
 * @author jordand
 * Channels are:
 * The-N (TeenNick) and Noggin, Nicktoons currently do not have a delayed West feed
 * Nick - 11
 * Nicktoons - 37
 * The N (TEENick) - 53
 * Nickjr - 11 but this is taking over Noggin
 * Noggin - 13
 */


if(typeof KIDS == "undefined" || !KIDS) var KIDS = {};
KIDS.namespace("tvSchedule");
KIDS.tvSchedule.weekDaysShort=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
KIDS.tvSchedule.weekDays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
KIDS.tvSchedule.months =["January","February","March","April","May","June","July","August","September","October","November","December"];
KIDS.tvSchedule.seriesList = null;
KIDS.tvSchedule.dateDropdown = null;

$(document).ready(function() {
	//KIDS.tvSchedule.loadSeriesData();
});

KIDS.tvSchedule.initTvSchedule = function(channel, days, startHour, endHour ){
	if(KIDS.tvSchedule.seriesList == null ){
		KIDS.tvSchedule.loadSeriesData(channel, days, startHour, endHour);
	}else{
		KIDS.tvSchedule.setupTVSchedule(channel, days, startHour, endHour );
	}
}

KIDS.tvSchedule.loadSeriesData = function(channel, days, startHour, endHour ){
	var nick_url = KIDS.utils.getNickDomain();
	NICK.request.doRequest({
		dataType:"jsonp",
		url: "http://"+ nick_url + "/sbcom/data/scenic/show_series_data.jhtml",
		data: {},
		onSuccess: function(response) {
			KIDS.utils.doLog("JSON Series Data: onSuccess");
			KIDS.tvSchedule.seriesList = response.data;
			KIDS.tvSchedule.initTvSchedule(channel, days, startHour, endHour );
		},
		onFail: function(errors) {
			for(var error in errors) {
				KIDS.utils.doLog("JSON Response: Error: "+error+" - "+errors[error]);
			}
		}				
	});
	
}

KIDS.tvSchedule.getScheduleTemplate = function(){
	/*
	 * Grab the templates from a table on the page
	 * First tr is the normally viewable row
	 * Second tr is the more information row that is invisible at initialization
	 */
	KIDS.tvSchedule.scheduleTemplate = $("#schedule-list tr").eq(0).clone();
	KIDS.tvSchedule.moreScheduleTemplate = $("#schedule-list tr").eq(1).clone();
	$("#schedule-list table").html("");
}

KIDS.tvSchedule.setupShowSchedule = function(seriesID, days){
	/*Sets up the show schedule with a jhtml that calls multiple channels and combines the information */
	KIDS.utils.doLog("setupShowScedule");
	KIDS.tvSchedule.seriesID = seriesID;
	KIDS.tvSchedule.getScheduleTemplate();
	var nick_url = KIDS.utils.getNickDomain();
	NICK.request.doRequest({
		dataType:"jsonp",
		url: "http://"+ nick_url + "/sbcom/data/json/all_channels_listing.jhtml",
		data: {seriesID:KIDS.tvSchedule.seriesID, days:days},
		onSuccess: function(response) {
			KIDS.utils.doLog("JSON Response: onSuccess");
			
			KIDS.tvSchedule.combineShowSchedule(response.data);
		},
		onFail: function(errors) {
			for(var error in errors) {
				KIDS.utils.doLog("JSON Response: Error: "+error+" - "+errors[error]);
			}
		}				
	});
	
}

KIDS.tvSchedule.setupTVSchedule = function(channel, days, startHour, endHour ){
	/* Sets up the TV schedule for one channel */
	KIDS.utils.doLog("setupTVSchedule");
	KIDS.tvSchedule.currentChannel = channel;
	KIDS.tvSchedule.getScheduleTemplate();
	//Setup the Week Dropdown
	var today = new Date();
	$("#schedule-dateSelected").html( KIDS.tvSchedule.weekDays[today.getDay()] + ", " + KIDS.tvSchedule.months[today.getMonth()] + " " + today.getDate() );
	var dropdownList = $("#schedule-week-dropdown")[0];
	for(var i =0; i < days;i++){
		var navDate=new Date();
		navDate.setDate(navDate.getDate()+i);
		var dateText = KIDS.tvSchedule.weekDaysShort[navDate.getDay()] + " "+ (navDate.getMonth()+1) + "/" + navDate.getDate();
		var option = new Option(dateText, navDate);
		if ($.browser.msie) {
        	dropdownList.add(option);
        }else {
			dropdownList.add(option, null);
		}
	}
	KIDS.tvSchedule.changeSchedule(KIDS.tvSchedule.currentChannel,new Date(),startHour, endHour );
}

KIDS.tvSchedule.changeSchedule = function(channel, date, startHour, endHour, channelButton ){
	/* Changes the TV schedule nav buttons and the timezone notification
	 * Gets the full broadcast day for this channel
	 */ 
	KIDS.utils.doLog("changeSchedule");
	KIDS.tvSchedule.currentChannel = channel;
	
	/*Select the button just pressed */
	if(channelButton != null){
		$("#channel-nav li.active").removeClass("active");
		$(channelButton).parent().addClass('active');
	}
	/*Check the current channel and change the Timezone information if not Nick - channel 11 */
	if (KIDS.tvSchedule.currentChannel == "11" || KIDS.tvSchedule.currentChannel == "41" ) {
		$("#schedule-timezone span").html("ET/PT");
	}else{
		$("#schedule-timezone span").html("ET");
	}
	
	//MM/dd/yyyy
	if (date == null && KIDS.tvSchedule.dateDropdown == null) {
		date = new Date();
	}
	else if(KIDS.tvSchedule.dateDropdown != null){
		date = KIDS.tvSchedule.dateDropdown;
	}
	var lookupDay = (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear();
	var nick_url = KIDS.utils.getNickDomain();
	NICK.request.doRequest({
		dataType:"jsonp",
		url: "http://"+ nick_url + "/sbcom/data/json/broadcast_day_listing.jhtml",
		data: {channelID:channel, day:lookupDay},
		onSuccess: function(response) {
			KIDS.utils.doLog("JSON Response: onSuccess");
			KIDS.tvSchedule.showScheduleGrid(response.data,$("#schedule-list"), startHour, endHour );
		},
		onFail: function(errors) {
			for(var error in errors) {
				KIDS.utils.doLog("JSON Response: Error: "+error+" - "+errors[error]);
			}
		}				
	});
}



KIDS.tvSchedule.showScheduleGrid = function(data,target, startHour, endHour ){
	/* 
	 * Adds dynamic content from json calls into the templates
	 * The schedule can be capped by a start hour and end hour - currently used for Nick JR
	 */
		KIDS.utils.doLog("showScheduleGrid");
		
		/*Clear out the table */
		$("#schedule-list table").html("");
		$("#schedule-list").scrollTop(0);
		
		if(startHour==null){startHour=0;}
		if(endHour==null){endHour=23;}
		var today = new Date();
		var timeZoneOffet = today.getTimezoneOffset()/60;
		KIDS.utils.doLog("offset "+timeZoneOffet);
		//Offset the time for the Nick Channel and nick at nite for any timezone except pacific
		if(timeZoneOffet != 7 || (KIDS.tvSchedule.currentChannel != "11" && KIDS.tvSchedule.currentChannel != "41") )  {
			today = new Date(today.getTime() + (((today.getTimezoneOffset()/60) -4)*60*60*1000) );
		}
		
		var onNow = 0;
		for (var loopID in data) {
			var scheduleData = data[loopID];
			var scheduleDate = new Date(Date.parse(scheduleData.CalendarAirTime));
			//--- Make sure the current time is always showing Eastern
			scheduleDate = new Date(scheduleDate.getTime() + (((today.getTimezoneOffset()/60) -4)*60*60*1000) );
			
			/*Skip itme if its not within the start and end hour cap */
			/* Time should be military */
		if( (startHour <= scheduleDate.getHours()) && (endHour >= scheduleDate.getHours())){
			
			/*------------- Replace content of template with data ----------- */
			var episodeName = scheduleData.EpisodeName != "null" ? KIDS.tvSchedule.treatText(scheduleData.EpisodeName) : "";
			var showThumb = KIDS.tvSchedule.seriesList["showThumb_" + scheduleData.seriesID];
			var showLogo = KIDS.tvSchedule.seriesList["logo_" + scheduleData.seriesID];
			var outputTemplate = KIDS.tvSchedule.scheduleTemplate.clone()
			outputTemplate.attr("loopID", loopID);
			outputTemplate.attr("episodeId", scheduleData.episodeId);
			outputTemplate.attr("seriesID", scheduleData.seriesID);
			outputTemplate.find(".date-output").prepend(KIDS.tvSchedule.formatDateText(scheduleDate));
			outputTemplate.find(".time-output").prepend(KIDS.tvSchedule.convertTime(scheduleDate));
			outputTemplate.find(".network-logo").addClass("logo_"+scheduleData.channelID);
			outputTemplate.find(".episode-name").prepend(episodeName);
			outputTemplate.find(".series-name").prepend(KIDS.tvSchedule.treatText(scheduleData.seriesName));
			outputTemplate.find(".parental-guideline").html(scheduleData.parentalGuideline);
			outputTemplate.find(".expand").prepend("<a href='#' onclick='KIDS.tvSchedule.showMore(this,"+scheduleData.seriesID+","+scheduleData.episodeId+","+loopID+"); return false;'>More</a>");
			if (showThumb != undefined && showThumb != "null" && showThumb != null && showThumb !=""){
				outputTemplate.find(".show-img").prepend('<img width="96" height="54" border="0" src="' + showThumb + '?height=54&amp;width=96&amp;format=jpeg" alt=""/>');
			}else{
				outputTemplate.find(".show-img").addClass("noThumb_"+KIDS.tvSchedule.currentChannel );
			}
			outputTemplate.find(".show-schedule-link").prepend("<a href=''>Show Schedule</a>");
			outputTemplate.appendTo("#schedule-list table");
			
			/*Replace text in the template with data   */
			var isBeforeEnd = today.getTime() <= ( scheduleDate.getTime() + (60000 * 30));
			var isCurrentDay = today.getDate() == scheduleDate.getDate();
			var isCurrentHour = today.getHours() > (scheduleDate.getHours() - 3);
			
			if( isBeforeEnd && isCurrentDay && isCurrentHour && (onNow < 3) ){
				if (onNow == 0) {
					outputTemplate.find(".currently-on").prepend("On Now");
					outputTemplate.find("td").addClass("onNow");
					onNow ++;
				}else if(onNow == 1){
					outputTemplate.find(".currently-on").prepend("Up Next");
					outputTemplate.find("td").addClass("onNext");
					onNow ++;
				}else if(onNow == 2){
					outputTemplate.find(".currently-on").prepend("Later");
					outputTemplate.find("td").addClass("onLater");
					onNow ++;
				}else{
					onNow ++;
					outputTemplate.find(".currently-on").hide();
				}
			}else{
					outputTemplate.find(".currently-on").hide();
			}
			
			
			/*------------- Replace content of template with data for the more info dropdown ----------- */
			var moreTemplate = KIDS.tvSchedule.moreScheduleTemplate.clone();
			moreTemplate.attr("loopID", loopID);
			moreTemplate.attr("episodeId", scheduleData.episodeId)
			moreTemplate.attr("seriesID", scheduleData.seriesID);
			moreTemplate.find(".episode-name").prepend(episodeName);
			if (showLogo != undefined && showLogo != "null" && showLogo != null && showLogo != "") {
				moreTemplate.find(".show-logo").prepend('<img width="145" border="0" src="' + showLogo + '?width=145&amp;format=png" alt="SpongeBob SquarePants game"/>');
			}
			moreTemplate.appendTo("#schedule-list table");
			
			
		}
		}
		if (KIDS.tvSchedule.autoScroll) {
			KIDS.tvSchedule.scrollToNowPlaying(target);
		}
}

KIDS.tvSchedule.scrollToNowPlaying = function(target){
	/*
	 * Handles the scrolling of the schedule div to episodes that are currently playing
	 */
	$("#schedule-list").scrollTop(0);
	var elementTop = target.find("td.onNow").eq(0).offset().top - 425;
	$("#schedule-list").scrollTop(elementTop);
}

KIDS.tvSchedule.showMore = function(button, seriesId, episodeId, loopID){
	/*
	 * Handles the showing of a hidden table row which contains more information on the episode
	 */
	var target = $(".schedule-more-info[loopID="+loopID+"]");
	var moreButton = $(".schedule-row[loopID="+loopID+"]").eq(0).find("span.expand a");
	if (target.css("display") == "none"){
		moreButton.html("Close").addClass("close");
		$("tr.schedule-more-info").hide();
		target.show();
		target.find("h3").show();
	}else{
		moreButton.html("More").removeClass("close");
		target.hide();
	}
	KIDS.tvSchedule.getEpisodeDescription(seriesId,episodeId,KIDS.tvSchedule.currentChannel, target.find("p.episode-description") );
}

KIDS.tvSchedule.getEpisodeDescription = function(seriesId, episodeId, channelID, target){
	/*
	 * Json call made when the more button is pressed
	 * Gets the episodes description and puts it in the target
	 */
	var nick_url = KIDS.utils.getNickDomain();
	NICK.request.doRequest({
		dataType: "jsonp",
		url: "http://" + nick_url + "/sbcom/data/json/episode_details.jhtml",
		data: {
			seriesID: seriesId,
			episodeId: episodeId,
			channelID: channelID
		},
		onSuccess: function(response){
			KIDS.utils.doLog("JSON Response: onSuccess");
			var episodeDescription = response.data.episodeDescription != "null" ? KIDS.tvSchedule.treatText(response.data.episodeDescription) : "No description available.";
			$(target).html(episodeDescription);
		},
		onFail: function(errors){
			for (var error in errors) {
				KIDS.utils.doLog("JSON Response: Error: " + error + " - " + errors[error]);
			}
		}
	});
}

KIDS.tvSchedule.getEpisode = function(seriesId,episodeId,channelID){
	var nick_url = KIDS.utils.getNickDomain();
	NICK.request.doRequest({
		dataType:"jsonp",
		url: "http://"+ nick_url + "/sbcom/data/json/episode_details.jhtml",
		data: {seriesID:seriesId, episodeId:episodeId, channelID:channelID},
		onSuccess: function(response) {
			KIDS.utils.doLog("JSON Response: onSuccess");
			$("#show-schedule-more h4.show-title").html(response.data.seriesName);
			$("#show-schedule-more span.episode-name").html(response.data.EpisodeName);
			$("#show-schedule-more p.episode-details").html(KIDS.tvSchedule.treatText(response.data.episodeDescription));
		},
		onFail: function(errors) {
			for(var error in errors) {
				KIDS.utils.doLog("JSON Response: Error: "+error+" - "+errors[error]);
			}
		}				
	});
}

KIDS.tvSchedule.dropdownSelect = function(dropdown){
	if($(dropdown).val()!= ""){
		KIDS.tvSchedule.dateDropdown = new Date( $(dropdown).val() );
		$("#schedule-dateSelected").html( KIDS.tvSchedule.weekDays[KIDS.tvSchedule.dateDropdown.getDay()] + ", " + KIDS.tvSchedule.months[KIDS.tvSchedule.dateDropdown.getMonth()] + " " + KIDS.tvSchedule.dateDropdown.getDate() );
		KIDS.tvSchedule.changeSchedule(KIDS.tvSchedule.currentChannel,KIDS.tvSchedule.dateDropdown);
	}
}




/*  Schedule Utilities    */

KIDS.tvSchedule.combineShowSchedule = function(data){
	KIDS.utils.doLog("combineShowSchedule");
	var channelsArr = [];
	/*Merge the Channels */
	for(channel in data){
		$.merge(channelsArr,data[channel]);
	}
	/*Sort the array by their dates*/
	channelsArr.sort(KIDS.tvSchedule.sortShowSchedule);

	if($("div.show-schedule").length > 0){
		KIDS.tvSchedule.showScheduleGrid(channelsArr,$("#schedule-list"));
	}
}

KIDS.tvSchedule.convertTime = function(date){
	/*
	 * Convert a time from javascript date to a viewable HH:MM AM/PM format
	 */
	var realHour = date.getHours();
	var minutes = date.getMinutes();
	if (minutes < 10){
		minutes = "0" + minutes
	}
	var amPm = '';
	if(realHour > 11){
		amPm = " PM";
	} else {
		amPm = " AM";
	}
	if (realHour > 12) {
		realHour = realHour -12
	}
	if(realHour < 1){realHour = 12;}
	var timeText = realHour + ":" + minutes + amPm;
	return timeText
}

KIDS.tvSchedule.formatDateText = function(date){
	/*Format a date from javascript date into a format Weekday MM/DD */
	return ( KIDS.tvSchedule.weekDaysShort[date.getDay()] + " " + (date.getMonth()+1) + "/" + (date.getDate()) );
}


KIDS.tvSchedule.sortShowSchedule = function(a,b){
	var x = new Date(a.CalendarAirTime).getTime();
    var y = new Date(b.CalendarAirTime).getTime();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}


KIDS.tvSchedule.treatText = function(text){
	/*Titles and descriptions coming from json calls are treated with an URL encoding
	 * This unescapes the URL encoding, and also replaces the "+" signs with spaces.
	 */
	return unescape(text).replace(/\+/g, " ");
}
