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

}

SceneFavorites.isNew = {
	programs: false,
	movies: false,
	arcPlus: false
};

SceneFavorites.prototype.initialize = function () {
	Logger.write("SceneFavorites.initialize()", "Favorites");
	// 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
	
	$("#favoritesNoData").html(Resources.getResources().NoData);
	$("#lblFavoritesTitle").sfLabel({text: Resources.getResources().LabelFavorites.toLowerCase()});
	SceneFavorites.initData();
	SceneFavorites.loadData();
}

SceneFavorites.initData = function () {
	this.activePanel = "";
	this.visiblePrograms = 9;
	this.mode = null;
	
	$("#panelFavoritesCategories").empty();
	$("#favoriteMovies").empty();
	$("#favoriteSorting").empty();

	this.categoriesPanel = new SlidingPanel(0, 0, [], "Category", this.onCategoriesSelectionChanged, 40, orientations.vertical, false, 320, "categoriesElement", 1000);
	$('#panelFavoritesCategories').append(this.categoriesPanel.panel);
	
	this.moviesPanel = new MoviesPanel(125, 299, 595, 80, 5, function() { }, "panelFavMovies", function() {}, function() { SceneFavorites.hideLoading(); SceneFavorites.moviesPanel.displayCounter(); }, 90);
    this.moviesPanel.itemPrefix = "favoriteMovie";
    $(this.moviesPanel.panel).css('visibility', 'collapse');
    $('#favoriteMovies').append(this.moviesPanel.panel);
	
	var sortingOrders = [new PanelElement("item_date", Resources.getResources().Date), new PanelElement("rating", Resources.getResources().Rating) , new PanelElement("name", Resources.getResources().Name)];
    this.sortingPanel = new SlidingPanel(80, 300, sortingOrders, "SortBy", this.onSortingOrderChanged, 90, orientations.horizontal, false, 1000); 
	$("#favoriteSorting").append(this.sortingPanel.panel);
}

SceneFavorites.translate = function () {
    if (SceneFavorites.currentLang != AppContext.ClientSettings.Language) {
		$("#favoritesNoData").html(Resources.getResources().NoData);
		$("#lblFavoritesTitle").sfLabel({text: Resources.getResources().LabelFavorites.toLowerCase()});
		SceneFavorites.showLoading();
		SceneFavorites.loadCategories();
		SceneFavorites.focusCategories();
		SceneFavorites.categoriesPanel.invokeSelectedChangedCallback();
		
		SceneFavorites.setHelpBar();
		SceneFavorites.currentLang = AppContext.ClientSettings.Language;
    }
}

SceneFavorites.setHelpBar = function () {
	var keys = {};
	keys['red'] = Resources.getResources().LabelSettings;
	if (SceneFavorites.mode === "arcplus") {
		keys['green'] = Resources.getResources().ShowEpisodes;
	}
	keys['yellow'] = Resources.getResources().Info;
	if (ScenePlayer.isPlaying) {
		keys['blue'] = Resources.getResources().Player;
		keys['Stop'] = Resources.getResources().Stop;
	}
	keys['updown'] = '';
	keys['leftright'] = Resources.getResources().MoveCursor;
	keys['enter'] = Resources.getResources().Select;
	keys['return'] = Resources.getResources().BackToMainMenu;
	$('#keysFavorites').sfKeyHelp(keys);
}

SceneFavorites.refresh = function () {
	SceneFavorites.isNew = {
		programs: false,
		movies: false,
		arcPlus: false
	};
	$("#favoritesNoData").hide();
	$("#favoritePrograms").hide();
	$("#favoriteMovies").hide();
	SceneFavorites.initData();
	SceneFavorites.loadData();
}

SceneFavorites.onSortingOrderChanged = function (orderId) {
	SceneFavorites.showLoading();
	var regex = /^\#divSortBy(\w+)/;
	var result = regex.exec(orderId);
	if (SceneFavorites.mode === "movies") {
		SceneFavorites.moviesPanel.sortMovies(result[1]);
	} else {
		var sortBy = result[1];
		var subSortBy = null;
		if (sortBy.indexOf("item_date") > -1) {
			sortBy = "recentAirTime";
			subSortBy = "startTime";
		}
		if (SceneFavorites.mode === "arcplus") {
			SceneFavorites.arcPlusPrograms = Helpers.sortByField(SceneFavorites.arcPlusPrograms, sortBy, false, subSortBy);
			SceneFavorites.bindPrograms(SceneFavorites.arcPlusPrograms, true);
		} else {
			SceneFavorites.programs = Helpers.sortByField(SceneFavorites.programs, sortBy, false, subSortBy);
			SceneFavorites.bindPrograms(SceneFavorites.programs);
		}
	}
	SceneFavorites.hideLoading();
}

SceneFavorites.onCategoriesSelectionChanged = function (elementName) {
	if (elementName.indexOf("programs") > -1 && SceneFavorites.mode != "programs") {
		SceneFavorites.loadFavPrograms();
	} else if (elementName.indexOf("movies") > -1 && SceneFavorites.mode != "movies") {
		SceneFavorites.loadFavMovies();
	} else if (elementName.indexOf("arcplus") > -1 && SceneFavorites.mode != "arcplus") {
		SceneFavorites.loadFavArcPlus();
	}
}

SceneFavorites.loadData = function () {
	this.showLoading();
	
	this.offset = AppContext.getNaEstUtcOffset();
	this.loadCategories();
	this.focusCategories();
	this.categoriesPanel.invokeSelectedChangedCallback();
}

SceneFavorites.loadCategories = function () {
	var elements = [];
	if (Helpers.checkServiceStatus("DVR", "NA", false)) {
		elements.push(new PanelElement("programs", Resources.getResources().FavoritesPrograms));
	}
	if (Helpers.checkServiceStatus("VOD", "NA", false)) {
		elements.push(new PanelElement("movies", Resources.getResources().FavoritesMovies));
	}
	if (Helpers.checkServiceStatus("ArcPlus", "NA", false)) {
		elements.push(new PanelElement("arcplus", Resources.getResources().FavoritesArcPlus));
	}
	
	SceneFavorites.categoriesPanel.loadData(elements);
}

SceneFavorites.loadFavPrograms = function (loadOnly, cb) {
	Logger.write("SceneFavorites.loadFavPrograms()");
	SceneFavorites.showLoading();
	
	var callback = function (result) {
		SceneFavorites.onProgramsLoaded(result);
		if (!loadOnly) {
			SceneFavorites.bindPrograms(SceneFavorites.programs);
		} else {
			if (cb) {
				cb();
			}
		}
	};
	
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Favorites", true, textStatus, jqXHR);
	};
	
	JsonServices.content.GetFavPrograms(AppContext.user.sid, "DVR", 100, 1, callback, errCallback);
}

SceneFavorites.loadFavArcPlus = function (loadOnly) {
	Logger.write("SceneFavorites.loadFavPrograms()");
	SceneFavorites.showLoading();
	
	var callback = function (result) {
		SceneFavorites.onArcPlusLoaded(result);
		if (!loadOnly) {
			SceneFavorites.bindPrograms(SceneFavorites.arcPlusPrograms, true);
		}
	};
	
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Favorites", true, textStatus, jqXHR);
	};
	
	JsonServices.content.GetFavPrograms(AppContext.user.sid, "ArcPlus", 100, 1, callback, errCallback);
}

SceneFavorites.loadFavMovies = function (loadOnly) {
	Logger.write("SceneFavorites.loadFavMovies()");
	SceneFavorites.showLoading();
	
	var callback = function (result) {
		SceneFavorites.onMoviesLoaded(result);
		if (!loadOnly) {
			SceneFavorites.bindMovies(SceneFavorites.movies);
		}
	};
	
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Favorites", true, textStatus, jqXHR);
	};
	
	JsonServices.content.GetFavOnDemandContentFilter(AppContext.user.sid, "VOD", 100, 1, callback, errCallback);
}

SceneFavorites.onProgramsLoaded = function (result) {
	Logger.write("SceneFavorites.onProgramsLoaded()", "Favorites", true);
	SceneFavorites.programs = result.items;
	SceneFavorites.programs = Helpers.sortByField(SceneFavorites.programs, "recentAirTime", false, "startTime");
	SceneFavorites.isNew.programs = true;
	SceneFavorites.hideLoading();
}

SceneFavorites.onArcPlusLoaded = function (result) {
	SceneFavorites.arcPlusPrograms = result.items;
	SceneFavorites.arcPlusPrograms = Helpers.sortByField(SceneFavorites.arcPlusPrograms, "recentAirTime", false, "startTime");
	SceneFavorites.isNew.arcPlus = true;
	SceneFavorites.hideLoading();
}

SceneFavorites.onMoviesLoaded = function (result) {
	SceneFavorites.movies = result.items || [];
	SceneFavorites.movies = Helpers.sortByField(SceneFavorites.movies, "MovieDate", false);
	SceneFavorites.isNew.movies = true;
	SceneFavorites.hideLoading();
}

SceneFavorites.bindPrograms = function (programs, isArcPlus) {
	var len = programs.length;
	$("#favoriteMovies").hide();
	SceneFavorites.mode = isArcPlus ? "arcplus" : "programs";
	if (len > 0) {
		$('#lbFavoritePrograms').show();

		if (len > SceneFavorites.visiblePrograms) {
			$('#scrollFavoritePrograms').show();
			$('#scrollFavoritePrograms').css('visibility', 'visible');
		} else {
			$('#scrollFavoritePrograms').hide();
			$('#scrollFavoritePrograms').css('visibility', 'hidden');
		}
		
		Logger.write("Total programs: " + len, "Favorites", true);
		var lbElems = [];
		for (var i = 0; i < len; i++) {
			lbElems.push(SceneFavorites.getProgramHtml(programs[i], isArcPlus));
		}
		
		var perPage = SceneFavorites.visiblePrograms > len ? len : SceneFavorites.visiblePrograms;
		$('#lbFavoritePrograms').sfList({data: lbElems, index: '0', itemsPerPage: perPage});
		$('#lbFavoritePrograms').sfList('blur');
		
		var pagesNum = Math.ceil(len / SceneFavorites.visiblePrograms);
		Logger.write("PagesNum: " + pagesNum, "Favorites", true);
		$("#scrollFavoritePrograms").sfScroll({page: pagesNum});
		$("#favoritePrograms").show();
		$("#favoritesNoData").hide();
		SceneFavorites.showPager();
		
		if (SceneFavorites.activePanel === "programs") {
			SceneFavorites.focusPrograms();
		} else if (SceneFavorites.activePanel === "categories") {
			SceneFavorites.focusCategories();
		} else {
			SceneFavorites.focusSorting();
		}
	} else {
		$('#scrollFavoritePrograms').hide();
		$('#scrollFavoritePrograms').css('visibility', 'hidden');
		$('#lbFavoritePrograms').sfList('clear');
		$('#lbFavoritePrograms').hide();
		$("#favoritesNoData").show();
		SceneFavorites.hidePager();
		
		if (SceneFavorites.activePanel === "sorting") {
			SceneFavorites.focusSorting();
		} else {
			SceneFavorites.focusCategories();
		}
	}
	SceneFavorites.setHelpBar();
	SceneFavorites.hideLoading();
}

SceneFavorites.bindMovies = function (movies) {
	$("#lbFavoritePrograms").hide();
	SceneFavorites.hidePager();
	if (movies.length > 0) {
		SceneFavorites.moviesPanel.loadData(movies);
		$("#favoriteMovies").show();
		$("#favoritesNoData").hide();
	} else {
		$("#favoriteMovies").hide();
		$("#favoritesNoData").show();
	}
	SceneFavorites.hideLoading();
	SceneFavorites.mode = "movies";
	SceneFavorites.setHelpBar();
	SceneFavorites.hidePager();
	if (SceneFavorites.activePanel == "movies") {
		SceneFavorites.moviesPanel.focus();
	}
}

SceneFavorites.removeFromFavoritePrograms = function (id) {
	if (!SceneFavorites.programs) {
		return;
	}
	
	for (var i = 0; i < SceneFavorites.programs.length; i++) {
		if (SceneFavorites.programs[i].id == id) {
			SceneFavorites.programs.splice(i, 1);
			break;
		}
	}
	
	if (SceneFavorites.mode && SceneFavorites.mode === "programs") {
		var idx = $('#lbFavoritePrograms').sfList('getIndex');
		SceneFavorites.bindPrograms(SceneFavorites.programs, false);
		var idx = idx < SceneFavorites.programs.length ? idx : SceneFavorites.programs.length - 1;
		if (SceneFavorites.programs.length > 0) {
			$('#lbFavoritePrograms').sfList('move', idx);
			$('#lbFavoritePrograms').sfList('focus');
			SceneFavorites.showPager();
		} else {
			SceneFavorites.focusCategories();
		}
	}
}

SceneFavorites.removeFromFavoriteMovies = function (id) {
	if (!SceneFavorites.movies) {
		return;
	}
	
	for (var i = 0; i < SceneFavorites.movies.length; i++) {
		if (SceneFavorites.movies[i].id == id) {
			SceneFavorites.movies.splice(i, 1);
			break;
		}
	}
	
	if (SceneFavorites.mode && SceneFavorites.mode === "movies") {
		var idx = SceneFavorites.moviesPanel.index;
		SceneFavorites.bindMovies(SceneFavorites.movies);
		idx = idx < SceneFavorites.movies.lenght ? idx : SceneFavorites.movies.lenght - 1;
		if (SceneFavorites.movies.lenght > 0) {
			SceneFavorites.moviesPanel.focusItem(idx);
		} else {
			SceneFavorites.focusCategories();
		}
	}
}

SceneFavorites.removeFromFavoriteArcPlus = function (id) {
	if (!SceneFavorites.arcPlusPrograms) {
		return;
	}
	
	for (var i = 0; i < SceneFavorites.arcPlusPrograms.length; i++) {
		if (SceneFavorites.arcPlusPrograms[i].id == id) {
			SceneFavorites.arcPlusPrograms.splice(i, 1);
			break;
		}
	}
	
	if (SceneFavorites.mode && SceneFavorites.mode === "arcplus") {
		var idx = $('#lbFavoritePrograms').sfList('getIndex');
		SceneFavorites.bindPrograms(SceneFavorites.arcPlusPrograms, true);
		var idx = idx < SceneFavorites.arcPlusPrograms.length ? idx : SceneFavorites.arcPlusPrograms.length - 1;
		if (SceneFavorites.arcPlusPrograms.length > 0) {
			$('#lbFavoritePrograms').sfList('move', idx);
			$('#lbFavoritePrograms').sfList('focus');
			SceneFavorites.showPager();
		} else {
			SceneFavorites.focusCategories();
		}
	}
}

SceneFavorites.getProgramHtml = function (program, isArcPlus) {
	var result = "";
	var date = new Date(program.recentAirTime.startTime);
	Logger.write("device offset: " + AppContext.deviceOffset, "Favorites", true);
	date.setHours(date.getHours() + SceneFavorites.offset - AppContext.deviceOffset/60);
	result += "<span class='programDate'>" + DateHelper.getArchPlusDate(date) + "</span>";
	var url = AppContext.ImageUrlTemplate.replace("{0}", program.recentAirTime.channelID).replace("{1}", isArcPlus ? 25 : 4).replace("{2}", 1) + "&width=28";
	result += "<div class='logoBack'><img  width='28' height='28' src='" + url + "' /></div>";
	result += "<span class='programTime'>" + date.toLocaleFormat("%H:%M") + "</span>";
	var titleClass = "programTitle";
	var hasSeries = program.isContainer && program.episodeNum === 1 || program.episodeNum > 1;
	if (hasSeries) {
		titleClass += " series";
	}
	var name = program.name.length > 28 ? program.name.substring(0, 25) + "..." : program.name;
	result += "<span class='" + titleClass + "'>" + name + "</span>";

	return result;
}

SceneFavorites.playMovie = function () {
	var movie = SceneFavorites.moviesPanel.getCurrentMovie();
	var callback = function (response) {
		try {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('Player');
			movie.url = response.URL;
			movie.playlist = response.Playlist;
			movie.contentType = "VOD";
			ScenePlayer.setContent(movie, "Favorites");
			SceneFavorites.setHelpBar();
			$.sfScene.focus('Player'); 
		} catch (error) {
			ErrorHandler.HandleError(error, "Favorites");  
		}  
    }
    var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Favorites", true, textStatus, jqXHR);  
	} 
    
	JsonServices.media.GetClientStreamUri(AppContext.user.sid, "VOD", movie.id,
		AppContext.ClientSettings.bAId, AppContext.ClientSettings.cdnId,
		AppContext.ClientSettings.qualityPreset, AppContext.ClientSettings.shiftTimeZoneName,
		callback, errCallback
	);
}

SceneFavorites.playDvr = function () {
	var idx = $('#lbFavoritePrograms').sfList('getIndex');
	var program = SceneFavorites.programs[idx];
	SceneFavorites.playProgram(program, "DVR");
}

SceneFavorites.playArcPlus = function () {
	var idx = $('#lbFavoritePrograms').sfList('getIndex');
	var program = SceneFavorites.arcPlusPrograms[idx];
	SceneFavorites.playProgram(program, "ArcPlus");
}

SceneFavorites.playVod = function () {
	SceneFavorites.playMovie();
}

SceneFavorites.playProgram = function (program, contentType) {
    var callback = function (response) {
		try {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('Player');
			ASXLoader.loadProgramsDuration([]);
			var video = program;
			video.currentTime = 0;
			video.url = response.URL;
			video.playlist = response.Playlist;
			video.contentType = contentType;
			ar = video.contentType == "ArcPlus"
				? SceneArchPlus.getChannelAr(program.recentAirTime.channelID)
				: SceneArchTv.getChannelAr(program.recentAirTime.channelID);
			if (ar) {
				video.ar = ar;
			}
			SceneFavorites.setHelpBar();
			ScenePlayer.setContent(video, "Favorites");
			$.sfScene.focus('Player');
		} catch (error) {
			ErrorHandler.HandleError(error, "Favorites");
		}
    }
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Favorites", true, textStatus, jqXHR);
	}
	
    try {
		JsonServices.media.GetClientStreamUri(
			AppContext.user.sid, contentType, program.id,
			AppContext.ClientSettings.bAId, AppContext.ClientSettings.cdnId,
			AppContext.ClientSettings.qualityPreset, AppContext.ClientSettings.shiftTimeZoneName,
			callback, errCallback
		);
	} catch (error) {
        ErrorHandler.HandleError(error, "Favorites");  
	}
}

SceneFavorites.isElementsAvailable = function () {
	if ((SceneFavorites.mode === "arcplus" && SceneFavorites.arcPlusPrograms.length > 0) ||
		SceneFavorites.mode === "programs" && SceneFavorites.programs.length > 0 ||
		SceneFavorites.mode === "movies" && SceneFavorites.movies.length > 0) {
		return true;
	}
	
	return false;
}

SceneFavorites.showPager = function () {
	Logger.write("Showing pager", "Favorites", true);
	var pagerInfo = "";
	if (SceneFavorites.mode === "arcplus" && SceneFavorites.arcPlusPrograms.length > 0) {
		pagerInfo = (parseInt($("#lbFavoritePrograms").sfList("getIndex")) + 1) + " | " + SceneFavorites.arcPlusPrograms.length;
	} else if (SceneFavorites.mode === "programs" && SceneFavorites.programs.length > 0) {
		pagerInfo = (parseInt($("#lbFavoritePrograms").sfList("getIndex")) + 1) + " | " + SceneFavorites.programs.length;
	}
	
	Logger.write("Pager info: " + pagerInfo, "Favorites", true);
	if (pagerInfo && pagerInfo.length > 0) {
		$("#favoritesPagerInfo").html(pagerInfo);
		$("#favoritesPagerInfo").show();
	} else {
		SceneFavorites.hidePager();
	}
}

SceneFavorites.hidePager = function () {
	Logger.write("Hiding pager", "Favorites", true);
	$("#favoritesPagerInfo").hide();
}

SceneFavorites.focusCategories = function () {
	SceneFavorites.activePanel = "categories";
	SceneFavorites.categoriesPanel.focusPanel();
}

SceneFavorites.focusPrograms = function () {
	SceneFavorites.activePanel = "programs";
	$("#lbFavoritePrograms").sfList("focus");
	SceneFavorites.showPager();
}

SceneFavorites.focusMovies = function () {
	SceneFavorites.activePanel = "movies";
	SceneFavorites.moviesPanel.focus();
	SceneFavorites.hidePager();
}

SceneFavorites.focusActiveElements = function () {
	var category = this.categoriesPanel.getFocusedId();
	if (category.indexOf("movies") > -1) {
		this.focusMovies();
	} else {
		this.focusPrograms();
	}
}

SceneFavorites.focusSorting = function () {
	SceneFavorites.activePanel = "sorting";
	SceneFavorites.sortingPanel.focusPanel();
}

SceneFavorites.backToMainMenu = function () {
    try {
		$.sfScene.hide('Favorites');
		SceneMainMenu.show();
    } catch (error) {
        ErrorHandler.HandleError(error, "Favorites");
    }  
}

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

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

SceneFavorites.handleLeft = function () {
	if (this.activePanel === "movies" || this.activePanel === "programs") {
		this.activePanel === "movies" ? this.moviesPanel.blur() : $("#lbFavoritePrograms").sfList("blur");
		this.focusCategories();
		return true;
	} else if (this.activePanel === "sorting") {
		this.sortingPanel.focusPrev();
	}
}

SceneFavorites.handleRight = function () {
	if (this.activePanel === "categories") {
		if (this.isElementsAvailable()) {
			this.categoriesPanel.blurPanel();
			this.focusActiveElements();
		}
	} else if (this.activePanel === "sorting") {
		this.sortingPanel.focusNext();
	}
}

SceneFavorites.handleUp = function () {
	if (this.activePanel === "categories") {
		if (this.categoriesPanel.index == 0) {
			this.categoriesPanel.blurPanel();
			this.focusSorting();
		}
		this.categoriesPanel.focusPrev();
	} else if (this.activePanel === "programs") {
		var idx = $("#lbFavoritePrograms").sfList("getIndex");
		if (idx > 0) {
			$("#lbFavoritePrograms").sfList("prev");
			var pageNumber = Math.ceil((idx + 1) / this.visiblePrograms) - 1;
			$("#scrollFavoritePrograms").sfScroll("move", pageNumber);
			this.showPager();
		} else {
			$("#lbFavoritePrograms").sfList("blur");
			this.focusSorting();
		}
	} else if (this.activePanel === "movies") {
		if (this.moviesPanel.index > 0) {
			this.moviesPanel.focusPrev();
		} else {
			this.moviesPanel.blur();
			this.focusSorting();
		}
	}
}

SceneFavorites.handleDown = function () {
	if (this.activePanel === "categories") {
		this.categoriesPanel.focusNext();
	} else if (this.activePanel === "programs") {
		var idx = $("#lbFavoritePrograms").sfList("getIndex");
		var len = this.mode === "programs" ? this.programs.length : this.arcPlusPrograms.length;
		if (idx == (len - 1)) {
			return;
		}
		$("#lbFavoritePrograms").sfList("next");
		var pageNumber = Math.ceil((idx + 1) / this.visiblePrograms) - 1;
		Logger.write("Page number: " + pageNumber, "Favorites", true);
		$("#scrollFavoritePrograms").sfScroll("move", pageNumber);
		this.showPager();
	} else if (this.activePanel === "movies") {
		this.moviesPanel.focusNext();
	} else if (this.activePanel === "sorting") {
		this.sortingPanel.blurPanel();
		if (this.isElementsAvailable()) {
			this.focusActiveElements();
		} else {
			this.focusCategories();
		}
	}
}

SceneFavorites.handleEnter = function () {
	if (this.activePanel == "categories") {
		return;
	}
	
	if (this.activePanel == "programs") {
		if (this.mode == "programs" && this.programs.length > 0) {
			SceneFavorites.playDvr();
		} else if (this.arcPlusPrograms.length > 0) {
			SceneFavorites.playArcPlus();
		}
	} else if (this.activePanel == "movies" && this.movies.length > 0) {
		var movie = SceneFavorites.moviesPanel.getCurrentMovie();
		var hasSeries = movie.isContainer && movie.episodeNum === 1 || movie.episodeNum > 1;
		if (hasSeries) {
			$.sfScene.hide(AppContext.CurrentScene);
			SceneSeries.setMovie(movie, "Favorites");
		} else {
			SceneFavorites.playVod();
		}
	}
}

SceneFavorites.handleYellow = function () {
	if (this.activePanel == "categories" || this.activePanel == "sorting") {
		return;
	}
	
	if (this.activePanel == "programs") {
		var idx = $('#lbFavoritePrograms').sfList('getIndex');
		var isDvr = SceneFavorites.mode === "programs";
		Logger.write("Is DVR: " + isDvr, "Favorites", true);
		var item = isDvr ? SceneFavorites.programs[idx] : SceneFavorites.arcPlusPrograms[idx];
		item.bookmarked = true;
		ScenePopUp.setWindow("Favorites", item);
	} else if (this.activePanel == "movies") {
		var item = SceneFavorites.moviesPanel.getCurrentMovie();
		item.bookmarked = true;
		ScenePopUp.setWindow("Favorites", item);
	}
	
	ScenePopUp.show();
}

SceneFavorites.handleGreen = function () {
	if (SceneFavorites.activePanel === "programs" && SceneFavorites.mode === "arcplus") {
		var idx = $('#lbFavoritePrograms').sfList('getIndex');
		var item = SceneFavorites.arcPlusPrograms[idx];
		var hasSeries = item.isContainer && item.episodeNum === 1 || item.episodeNum > 1;
		if (hasSeries) {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('ProgramEpisodes');
			$.sfScene.focus('ProgramEpisodes');
			SceneProgramEpisodes.loadEpisodes(item.id, "Favorites");
		}
	} else if (SceneFavorites.activePanel === "movies") {
		var movie = SceneFavorites.moviesPanel.getCurrentMovie();
		var hasSeries = movie.isContainer && movie.episodeNum === 1 || movie.episodeNum > 1;
		if (hasSeries) {
			$.sfScene.hide(AppContext.CurrentScene);
			SceneSeries.setMovie(movie, "Favorites");
		}
	}
}

SceneFavorites.handleReturn = function () {
	if (this.activePanel == "sorting" || !this.handleLeft()) {
		SceneFavorites.backToMainMenu();
	}
}

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

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

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

SceneFavorites.prototype.handleFocus = function () {
	alert("SceneFavorites.handleFocus()");
	// this function will be called when the scene manager focus this scene
	AppContext.CurrentScene = "Favorites";
	if (ScenePlayer.isPlaying == true) {
	    Helpers.setBackgroundOpacity();
	}
	SceneFavorites.setHelpBar();
	if (ErrorHandler.NeedToRefresh[AppContext.CurrentScene]) {
		SceneFavorites.refresh();
		ErrorHandler.NeedToRefresh[AppContext.CurrentScene] = false;
	} else {
		if (SceneFavorites.mode === "programs" && !SceneFavorites.isNew.programs) {
			SceneFavorites.loadFavPrograms();
		} else if (SceneFavorites.mode === "movies" && !SceneFavorites.isNew.movies) {
			SceneFavorites.loadFavMovies();
		} else if (SceneFavorites.mode === "arcplus" && !SceneFavorites.isNew.arcPlus) {
			SceneFavorites.loadFavArcPlus();
		}
		
		if (SceneFavorites.isLoading) {
			Helpers.showLoading();
		} 
	}
}

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

SceneFavorites.prototype.handleKeyDown = function (keyCode) {
	alert("SceneFavorites.handleKeyDown(" + keyCode + ")");
	// TODO : write an key event handler when this scene get focued
	if (Helpers.handleGlobalKeys(keyCode)) {
		return;
	}
	switch (keyCode) {
		case $.sfKey.LEFT:
			SceneFavorites.handleLeft();
			break;
		case $.sfKey.RIGHT:
			SceneFavorites.handleRight();
			break;
		case $.sfKey.UP:
			SceneFavorites.handleUp();
			break;
		case $.sfKey.DOWN:
			SceneFavorites.handleDown();
			break;
		case $.sfKey.ENTER:
			SceneFavorites.handleEnter();
			break;
		case $.sfKey.BLUE:
			if (ScenePlayer.isPlaying == true) {
				$.sfScene.hide('Favorites');
				$.sfScene.show('Player');
				$.sfScene.focus('Player');
			}
			break;
		case $.sfKey.YELLOW:
			SceneFavorites.handleYellow();
            break;
		case $.sfKey.GREEN:
			SceneFavorites.handleGreen();
            break;
		case $.sfKey.RED:
			try {
                $.sfScene.hide('Favorites');
                $.sfScene.show('Settings');
                $.sfScene.focus('Settings');
                SceneSettings.selectAccount();
            } catch (error) {
                ErrorHandler.HandleError(error, "Favorites");
            } 
            break;
		case $.sfKey.STOP:
			if (ScenePlayer.isPlaying == true) {
				ScenePlayer.stop();
				SceneFavorites.setHelpBar();
			}
			break;
		case $.sfKey.RETURN:
            widgetAPI.blockNavigation(event);
			SceneFavorites.handleReturn();
			break;
		case $.sfKey.EXIT:
			try {
				widgetAPI.blockNavigation(event);
				SceneFavorites.handleExit();
			} catch (error) {
				ErrorHandler.HandleError(error, "Favorites");
			}
			break;
	}
}