function SceneProgramEpisodes(options) {
	this.options = options;
	

}

SceneProgramEpisodes.prototype.initialize = function () {
	alert("SceneProgramEpisodes.initialize()");
	// this function will be called only once when the scene manager show this scene first time
	// initialize the scene controls and styles, and initialize your variables here 
	// scene HTML and CSS will be loaded before this function is called
	
	SceneProgramEpisodes.initData();
}

SceneProgramEpisodes.initData = function () {
	SceneProgramEpisodes.episodes = [];
	SceneProgramEpisodes.currentId = -1;
	
	SceneProgramEpisodes.visibleEpisodes = 7;
	SceneProgramEpisodes.itemsOnPage = SceneProgramEpisodes.visibleEpisodes * 3;
}

SceneProgramEpisodes.translate = function () {
    if (SceneProgramEpisodes.currentLang != AppContext.ClientSettings.Language)
    {
		$("#programEpisodesLabel").sfLabel({text:Resources.getResources().Episodes});
		
        SceneProgramEpisodes.currentLang = AppContext.ClientSettings.Language;
        SceneProgramEpisodes.setHelpBar();
    }  
}

SceneProgramEpisodes.setHelpBar = function () {
    if (ScenePlayer.isPlaying) {
        $("#programEpisodesKeys").sfKeyHelp({
			'number': Resources.getResources().Episode,
			'red': Resources.getResources().LabelSettings, 
			'green': Resources.getResources().Refresh,
			'yellow': Resources.getResources().Info,
			'blue': Resources.getResources().Player, 
			'stop': Resources.getResources().Stop,
			'updown': Resources.getResources().MoveCursor, 
			'enter': Resources.getResources().Select, 
			'return': Resources.getResources().BackToMainMenu
		});
    } else {
        $("#programEpisodesKeys").sfKeyHelp({
			'number': Resources.getResources().Episode,
			'red': Resources.getResources().LabelSettings, 
			'green': Resources.getResources().Refresh,
			'yellow': Resources.getResources().Info,
			'updown': Resources.getResources().MoveCursor, 
			'enter': Resources.getResources().Select,
			'return': Resources.getResources().BackToMainMenu
		});
    }
}

SceneProgramEpisodes.loadEpisodes = function (programId, sender) {
	$("#programEpisodes").hide();
	SceneProgramEpisodes.showLoading();
	sender = sender || "ArchPlus";
	SceneProgramEpisodes.currentId = programId;
	SceneProgramEpisodes.sender = sender;
	SceneProgramEpisodes.episodes = null;
	SceneProgramEpisodes.pager = null;
	var callback = function (result) {
		if (result) {
			SceneProgramEpisodes.bindEpisodes();
			SceneProgramEpisodes.hideLoading();
		}
	};
			
	SceneProgramEpisodes.loadEpisodesPage(SceneProgramEpisodes.itemsOnPage, 1, callback);
}

SceneProgramEpisodes.onPageChanging = function (onPage, pageNumber, pageChangedCallback) {
	Logger.write("SceneProgramEpisodes.onPageChanging(" + onPage + ", " + pageNumber + ")");
	SceneProgramEpisodes.showLoading();
	if (SceneProgramEpisodes.episodes[onPage * (pageNumber - 1)]) {
		SceneProgramEpisodes.bindEpisodes(pageNumber);
		pageChangedCallback(true);
		$('#scrollProgramEpisodes').sfScroll('move', SceneProgramEpisodes.pager.scroll.pageNumber);
		SceneProgramEpisodes.hideLoading();
		return;
	}
	
	var callback = function (result) {
		pageChangedCallback(result);
		if (result) {
			SceneProgramEpisodes.bindEpisodes();
			SceneProgramEpisodes.hideLoading();
		}
	}
	
	SceneProgramEpisodes.loadEpisodesPage(onPage, pageNumber, callback);
}

SceneProgramEpisodes.onPageLoaded = function (result) {
	if (!SceneProgramEpisodes.pager) {
		SceneProgramEpisodes.pager = new ListPager(result.paging, "#lbProgramEpisodes", SceneProgramEpisodes.visibleEpisodes, SceneProgramEpisodes.onPageChanging);
		//SceneProgramEpisodes.episodesPanel.paging = SceneProgramEpisodes.pager.paging;
	}
	
	var episodes = result.items;
	if (!SceneProgramEpisodes.episodes) {
		SceneProgramEpisodes.episodes = [];
	}
	
	var startIndex = result.paging.itemsOnPage * (result.paging.pageNumber - 1);
	for (var i = startIndex; i < (startIndex + result.paging.itemsOnPage); i++) {
		SceneProgramEpisodes.episodes[i] = episodes.shift();
	}
}

SceneProgramEpisodes.loadEpisodesPage = function (onPage, pageNumber, pageLoadedCallback) {
	var callback = function (episodes, paging) {
		SceneProgramEpisodes.onPageLoaded(episodes, paging);
		pageLoadedCallback(true);
	}
	
	var errorCallback = function(jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error,"ProgramEpisodes",true, textStatus, jqXHR);
		Logger.write("text status=" + textStatus, "ProgramEpisodes");
		pageLoadedCallback(false);
	}; 

	JsonServices.content.GetClientRelatedProgramGuide(
		AppContext.user.sid, "ArcPlus", "children", 
		SceneProgramEpisodes.currentId, null, onPage, pageNumber, 
		callback, errorCallback
	);
}

SceneProgramEpisodes.bindEpisodes = function (pageNumber) {
	pageNumber = pageNumber || SceneProgramEpisodes.pager.paging.pageNumber;
	var firstEpisode = SceneProgramEpisodes.pager.paging.itemsOnPage * (pageNumber - 1);
	var lastEpisode = (firstEpisode + SceneProgramEpisodes.pager.paging.itemsOnPage) < SceneProgramEpisodes.pager.paging.totalItems 
			? firstEpisode + SceneProgramEpisodes.pager.paging.itemsOnPage
			: SceneProgramEpisodes.pager.paging.totalItems;
	var episodes = SceneProgramEpisodes.episodes.slice(firstEpisode, lastEpisode);
	Logger.write("FirstEpisode: " + firstEpisode + "; episodes length: " + episodes.length, "ProgramEpisodes", true);
	
	var len = episodes.length;
	var lbElems = [];
	for (var i = 0; i < len; i++) {
		lbElems.push(SceneProgramEpisodes.getEpisodeHtml(episodes[i], SceneProgramEpisodes.pager.paging.totalItems - (i + firstEpisode)));
	}
	var perPage = len > SceneProgramEpisodes.visibleEpisodes ? SceneProgramEpisodes.visibleEpisodes : len;
	$('#lbProgramEpisodes').sfList({data: lbElems, index: '0', itemsPerPage: perPage});
	var pagesNum = SceneProgramEpisodes.pager.scroll.getTotalPages();
	Logger.write("Total items: " + SceneProgramEpisodes.pager.paging.totalItems + "; total pages: " + pagesNum, "ProgramEpisodes", true);
	$('#scrollProgramEpisodes').sfScroll({page: pagesNum});
	$('#scrollProgramEpisodes').sfScroll('move', SceneProgramEpisodes.pager.scroll.pageNumber);
	$("#scrollProgramEpisodes").show();
	$('#lbProgramEpisodes').sfList("focus");
	SceneProgramEpisodes.showDescription();
}

SceneProgramEpisodes.getEpisodeHtml = function (episode, index) {
	var result = "";
	var numberClass = "episodeNumber";
	Logger.write("Index: " + index, "ProgramEpisodes", true);
	if (index.toString().length > 3) {
		Logger.write("Length > 3", "ProgramEpisodes", true);
		numberClass += " long";
	}
	result += "<div class='"+numberClass+"'>" + index + ".</div>";
	result += "<div class='episodeTitle'>" + episode.name + "</div>";
	result += "<div class='episodeDate'>(" + DateHelper.getArchPlusDate(episode.recentAirTime.startTime) + ")</div>";

	return result;
}

SceneProgramEpisodes.back = function ()
{
	try {
		$.sfScene.hide('ProgramEpisodes');
		$.sfScene.show(SceneProgramEpisodes.sender);
		$.sfScene.focus(SceneProgramEpisodes.sender);
	} catch (error) {
		ErrorHandler.HandleError(error, "ProgramEpisodes");
	}
}

SceneProgramEpisodes.handleExit = function () {
	var resultCallback = function (result) {
		if (result) {
			AppEvents.Exit();
		}
	};
	SceneDialogPopUp.showExitDialog("ProgramEpisodes", resultCallback);
}

SceneProgramEpisodes.refresh = function () {
	try {
		SceneProgramEpisodes.showLoading();
		var first = SceneProgramEpisodes.episodes[0];
		SceneProgramEpisodes.loadEpisodes(first.id, SceneProgramEpisodes.sender);
		AppContext.CurrentScene = "ProgramEpisodes"; 
		if  (ScenePlayer.isPlaying == true) {
			Helpers.setBackgroundOpacity();
		}
		SceneProgramEpisodes.setHelpBar();
	} catch (error) {
		ErrorHandler.HandleError(error, "ProgramEpisodes");
	}
}

SceneProgramEpisodes.openPlayer = function () {
	SceneProgramEpisodes.loadEpisode(SceneProgramEpisodes.pager.paging.getTotalIndex());
}

SceneProgramEpisodes.loadEpisode = function (index) {
	if (index >= SceneProgramEpisodes.pager.paging.totalItems) {
		return false;
	}
	
	if (SceneProgramEpisodes.episodes[index]) {
		SceneProgramEpisodes.loadEpisodeStream(index);
	} else {
		var callback = function (result) {
			if (result) {
				SceneProgramEpisodes.loadEpisodeStream(index);
			}
		}
		var onPage = SceneProgramEpisodes.pager.paging.itemsOnPage;
		var page = Math.ceil((index + 1) / onPage);
		SceneProgramEpisodes.loadEpisodesPage(SceneProgramEpisodes.pager.paging.itemsOnPage, page, callback);
	}
}

SceneProgramEpisodes.loadEpisodeStream = function (index) {
	Logger.write("SceneProgramEpisodes.loadEpisodeStream("+index+")", "ProgramEpisodes", true);
	var item = SceneProgramEpisodes.episodes[index];
	
	var callback = function (response) {
		try {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('Player');
			var video = item;
			video.currentTime = 0;
			video.url = response.URL;
			video.playlist = response.Playlist;
			video.contentType = "ArcPlus";
			var ar = SceneArchPlus.getChannelAr(item.recentAirTime.channelID);
			if (ar) {
				Logger.write("AR gotten: " + ar.x + ":" + ar.y, "ArchPlus", true);
				video.ar = ar;
			}
			Logger.write("Index: " + index, "ProgramEpisodes", true);
			ScenePlayer.episodePicker = new ArchProgramPicker(SceneProgramEpisodes.episodes, SceneProgramEpisodes.loadEpisode, index);
			ScenePlayer.episodePicker.count = SceneProgramEpisodes.pager.paging.totalItems;
			ScenePlayer.setContent(video, "ProgramEpisodes");
			$.sfScene.focus('Player');
		} catch (error) {
			ErrorHandler.HandleError(error, "ProgramEpisodes");
		}
    }
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "ProgramEpisodes", true, textStatus, jqXHR);
	}
	
    try {
		JsonServices.media.GetClientStreamUri(
			AppContext.user.sid, "ArcPlus", item.id,
			AppContext.ClientSettings.bAId, AppContext.ClientSettings.cdnId,
			AppContext.ClientSettings.qualityPreset, AppContext.ClientSettings.shiftTimeZoneName,
			callback, errCallback
		);
	} catch (error) {
        ErrorHandler.HandleError(error, "ProgramEpisodes");  
	}
}

SceneProgramEpisodes.showDescription = function () {
	var episode = SceneProgramEpisodes.episodes[SceneProgramEpisodes.pager.paging.getTotalIndex()];
	if (episode) {
		var imageUrl = AppContext.ImageUrlTemplate.replace("{0}", episode.id).replace("{1}", "16").replace("{2}", "1") + "&width=152";
		$("#imgProgramEpisode").sfImage({src: imageUrl});
		$("#episodeDetails .description").html(episode.description);
	}
}

SceneProgramEpisodes.handleUp = function () {
	if (SceneProgramEpisodes.isLoading) {
		return;
	}
	try {
		SceneProgramEpisodes.pager.prev();
		$('#scrollProgramEpisodes').sfScroll('move', SceneProgramEpisodes.pager.scroll.pageNumber);
		SceneProgramEpisodes.showDescription();
	} catch (error) {
		ErrorHandler.HandleError(error, "ProgramEpisodes");
	}
}

SceneProgramEpisodes.handleDown = function () {
	if (SceneProgramEpisodes.isLoading) {
		return;
	}
	try {
		SceneProgramEpisodes.pager.next();
		$('#scrollProgramEpisodes').sfScroll('move', SceneProgramEpisodes.pager.scroll.pageNumber);
		SceneProgramEpisodes.showDescription();
	} catch (error) {
		ErrorHandler.HandleError(error, "ProgramEpisodes");
	}
}

SceneProgramEpisodes.handleEnter = function () {
	SceneProgramEpisodes.openPlayer();
}

SceneProgramEpisodes.handleYellow = function () {
	if (SceneProgramEpisodes.isLoading) {
		return;
	}
	try {
        var itemIndex = SceneProgramEpisodes.pager.paging.getTotalIndex();
		var item = SceneProgramEpisodes.episodes[itemIndex];
		ScenePopUp.setWindow("ProgramEpisodes", item);
		$.sfScene.show('PopUp');
		$.sfScene.focus('PopUp');
    } catch(error) {
        ErrorHandler.HandleError(error, "ProgramEpisodes");
    }
}

SceneProgramEpisodes.handleNum = function (number) {
	Logger.write("handling num: " + number, "ProgramEpisodes", false);
	var num = parseInt(this.newEpisode + number, 10);
	if (num <= SceneProgramEpisodes.pager.paging.totalItems) {
		this.newEpisode += number;
	
		if (SceneProgramEpisodes.seriesTimeout) {
			clearTimeout(SceneProgramEpisodes.seriesTimeout);
		}
		
		$("#programEpisodesNum").show();
		$("#programEpisodesNum").html(this.newEpisode + "-");

		var callback = function () {
			var newIndex = parseInt(SceneProgramEpisodes.newEpisode);
			newIndex = SceneProgramEpisodes.pager.paging.totalItems - newIndex + 1;
			var onPage = SceneProgramEpisodes.pager.paging.itemsOnPage;
			var pageNumber = SceneProgramEpisodes.pager.paging.pageNumber;
			var page = Math.ceil(newIndex / onPage);
			
			if (page == pageNumber) {
				var episodeNumber = newIndex - (onPage * (pageNumber - 1));
				SceneProgramEpisodes.pager.paging.index = episodeNumber - 1;
				$("#lbProgramEpisodes").sfList('move', SceneProgramEpisodes.pager.paging.index);
			} else {
				var idx = newIndex - (page - 1) * onPage - 1;
				Logger.write("Page: " + page + "; index: " + idx, "ProgramEpisodes", true);
				SceneProgramEpisodes.pager.setPageNumber(page, idx);
			}
			
			$("#programEpisodesNum").show();
			$("#programEpisodesNum").html(SceneProgramEpisodes.newEpisode);
			setTimeout(function () { 
				if (!SceneProgramEpisodes.newEpisode) {
					$("#programEpisodesNum").hide();
				}
			}, 2000);
			SceneProgramEpisodes.newEpisode = "";
		};
		SceneProgramEpisodes.seriesTimeout = setTimeout(callback, 2000);
	}
}

SceneProgramEpisodes.showLoading = function () {
    SceneProgramEpisodes.isLoading = true;
	if (AppContext.CurrentScene == "ProgramEpisodes") {
		Helpers.showLoading();
	}
    SceneProgramEpisodes.dataLoaded = false;
}

SceneProgramEpisodes.hideLoading = function () {
    SceneProgramEpisodes.isLoading = false;
	if (AppContext.CurrentScene == "ProgramEpisodes") {
		Helpers.hideLoading();
	}
    SceneProgramEpisodes.dataLoaded = true;
}

SceneProgramEpisodes.prototype.handleShow = function () {
	alert("SceneProgramEpisodes.handleShow()");
	// this function will be called when the scene manager show this scene 
	SceneProgramEpisodes.translate();
	SceneProgramEpisodes.newEpisode = "";
}

SceneProgramEpisodes.prototype.handleHide = function () {
	alert("SceneProgramEpisodes.handleHide()");
	// this function will be called when the scene manager hide this scene  
	Helpers.hideLoading();
}

SceneProgramEpisodes.prototype.handleFocus = function () {
	alert("SceneProgramEpisodes.handleFocus()");
	// this function will be called when the scene manager focus this scene
	AppContext.CurrentScene = "ProgramEpisodes";
	if (ScenePlayer.isPlaying == true) {
		Helpers.setBackgroundOpacity();
	}
	
	if (SceneProgramEpisodes.isLoading) {
		Helpers.showLoading();
	}
}

SceneProgramEpisodes.prototype.handleBlur = function () {
	alert("SceneProgramEpisodes.handleBlur()");
	// this function will be called when the scene manager move focus to another scene from this scene
}

SceneProgramEpisodes.prototype.handleKeyDown = function (keyCode) {
	alert("SceneProgramEpisodes.handleKeyDown(" + keyCode + ")");
	// TODO : write an key event handler when this scene get focued
	if (Helpers.handleGlobalKeys(keyCode)) {
		return;
	}
	switch (keyCode) {
		case $.sfKey.N0:
			if (SceneProgramEpisodes.newEpisode) {
				SceneProgramEpisodes.handleNum("0");
			}
			break;
		case $.sfKey.N1:
			SceneProgramEpisodes.handleNum("1");
			break;
		case $.sfKey.N2:
			SceneProgramEpisodes.handleNum("2");
			break;
		case $.sfKey.N3:
			SceneProgramEpisodes.handleNum("3");
			break;
		case $.sfKey.N4:
			SceneProgramEpisodes.handleNum("4");
			break;
		case $.sfKey.N5:
			SceneProgramEpisodes.handleNum("5");
			break;
		case $.sfKey.N6:
			SceneProgramEpisodes.handleNum("6");
			break;
		case $.sfKey.N7:
			SceneProgramEpisodes.handleNum("7");
			break;
		case $.sfKey.N8:
			SceneProgramEpisodes.handleNum("8");
			break;
		case $.sfKey.N9:
			SceneProgramEpisodes.handleNum("9");
			break;
		case $.sfKey.UP:
            SceneProgramEpisodes.handleUp();
			break;
		case $.sfKey.DOWN:
            SceneProgramEpisodes.handleDown();
			break;
		case $.sfKey.ENTER:
            SceneProgramEpisodes.handleEnter();
			break;
        case $.sfKey.STOP:
            if  (ScenePlayer.isPlaying == true) {
				ScenePlayer.stop();
				SceneProgramEpisodes.setHelpBar();
            }
            break;
        case $.sfKey.RETURN:
            widgetAPI.blockNavigation(event);
            SceneProgramEpisodes.back();
			break;
        case $.sfKey.YELLOW:
            SceneProgramEpisodes.handleYellow();
			break;
        case $.sfKey.GREEN:
            SceneProgramEpisodes.refresh();
			break;
		case $.sfKey.BLUE:
            if  (ScenePlayer.isPlaying == true) {
                $.sfScene.hide('ProgramEpisodes');
                $.sfScene.show('Player');
                $.sfScene.focus('Player');
            }
            break;
		case $.sfKey.RED:
            try {
                $.sfScene.hide('ProgramEpisodes');
                $.sfScene.show('Settings');
                $.sfScene.focus('Settings');
                SceneSettings.selectAccount();
            } catch(error) {
                ErrorHandler.HandleError(error, "ProgramEpisodes");
            }  
            break;
		case $.sfKey.EXIT:
            try {
                widgetAPI.blockNavigation(event);
				SceneProgramEpisodes.handleExit();
            } catch(error) {
                ErrorHandler.HandleError(error, "ProgramEpisodes");
            }  
            break;
        default:
            widgetAPI.blockNavigation(event);
            break;
	}
}
