/**
 * @author EvgeniyV
 */
function SceneSeries(options) {
	this.options = options;
}

/*
Sets helpbar
*/
SceneSeries.setHelpBar = function () {
	var keys = {};
    if (ScenePlayer.isPlaying)
    {
		keys = {
			'number': Resources.getResources().Episode,
			'red': Resources.getResources().LabelSettings,
			'green': "",
			'yellow': Resources.getResources().Info,
			'blue': Resources.getResources().Player, 
			'stop': Resources.getResources().Stop,
			'updown': Resources.getResources().MoveCursor, 
			'enter': Resources.getResources().Select, 
			'return': Resources.getResources().BackToMainMenu
		};
		if (SceneSeries.sortDirection === "DESC") {
			keys['green'] = Resources.getResources().SeriesAZ;
		} else {
			keys['green'] = Resources.getResources().SeriesZA;
		}
    }
    else
    {
		keys = {
			'number': Resources.getResources().Episode,
			'red': Resources.getResources().LabelSettings, 
			'green': "",
			'yellow': Resources.getResources().Info,
			'updown': Resources.getResources().MoveCursor, 
			'enter': Resources.getResources().Select,
			'return': Resources.getResources().BackToMainMenu
		};
		if (SceneSeries.sortDirection === "DESC") {
			keys['green'] = Resources.getResources().SeriesAZ;
		} else {
			keys['green'] = Resources.getResources().SeriesZA;
		}
    }
	$("#seriesKeys").sfKeyHelp(keys);
}

SceneSeries.prototype.initialize = function () {
	Logger.write("SceneSeries.initialize()", "Series");
    SceneSeries.initData();
}

/*
Hides image of vod
*/
SceneSeries.hideImg = function(){
    $("#movieSeriesImg").sfImage({src:""});
    $("#movieSeriesImg").css({'visibility':'hidden'});
}

/*
Loads image of vod
*/
SceneSeries.loadImg = function(){
    var imgSrc = AppContext.ImageUrlTemplate.replace("{0}", SceneSeries.movie.id).replace("{1}", 1).replace("{2}", "1") + "&width=176";
    $("#movieSeriesImg").sfImage({src: imgSrc});
    $("#movieSeriesImg").css({'visibility':'visible'});
}

/*
Loads series for vod
*/
SceneSeries.loadSeries = function () {
	onPage = SceneSeries.itemsOnPage;
	pageNumber = 1;
	SceneSeries.pager = null;
    if (SceneSeries.movie != null)
    {
		$("#movieSeries").hide();
		var callback = function (result)
		{
			if (result) {
				SceneSeries.bindEpisodes();
				SceneSeries.hideLoading();
			}
		};
				
		SceneSeries.loadEpisodesPage(onPage, pageNumber, callback);
    }
}

SceneSeries.onPageLoaded = function (result) {
	if (!SceneSeries.pager) {
		SceneSeries.pager = new ListPager(result.paging, "#lbMovieSeries", SceneSeries.visibleEpisodes, SceneSeries.onPageChanging);
	}
	
	var episodes = result.items;
	Logger.write("Episodes: " + episodes.length, "Series", true);
	if (!SceneSeries.episodes) {
		SceneSeries.episodes = [];
	}
	
	var startIndex = result.paging.itemsOnPage * (result.paging.pageNumber - 1);
	Logger.write("StartIndex: " + startIndex, "Series", true);
	Logger.write("EndIndex: " + (startIndex + episodes.length), "Series", true);
	var len = startIndex + episodes.length;
	for (var i = startIndex; i < len; i++) {
		SceneSeries.episodes[i] = episodes.shift();
		SceneSeries.episodes[i].bookmarked = SceneSeries.movie.bookmarked;
	}
}

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

SceneSeries.getEpisodeHtml = function (episode, index) {
	var result = "";
	result += "<div class='episodeNumber'>" + index + ".</div>";
	result += "<span class='episodeTitle'>" + episode.name + "</span>";

	return result;
}

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

	JsonServices.content.GetClientRelatedOnDemandContent(
		AppContext.user.sid, "VOD", "children", 
		SceneSeries.movie.id, "name " + SceneSeries.sortDirection,
		onPage, pageNumber, 
		callback, errorCallback
	);
}

SceneSeries.setFavoriteStatus = function (status) {
	if (!SceneSeries.episodes || !SceneSeries.episodes.length) {
		return;
	}
	SceneSeries.movie.bookmarked = status;
	for (var i = 0; i < SceneSeries.episodes.length; i++) {
		var episode = SceneSeries.episodes[i];
		if (!!episode && typeof episode.bookmarked === "boolean") {
			episode.bookmarked = status;
		}
	}
}

SceneSeries.onPageChanging = function (onPage, pageNumber, pageChangedCallback) {
	Logger.write("SceneSeries.onPageChanging(" + onPage + ", " + pageNumber + ")");
	SceneSeries.showLoading();
	if (SceneSeries.episodes[onPage * (pageNumber - 1)]) {
		SceneSeries.bindEpisodes(pageNumber);
		pageChangedCallback(true);
		SceneSeries.hideLoading();
		return;
	}
	
	var callback = function (result) {
		pageChangedCallback(result);
		if (result) {
			SceneSeries.bindEpisodes();
			SceneSeries.hideLoading();
		}
	}
	
	SceneSeries.loadEpisodesPage(onPage, pageNumber, callback);
}

/*
Creates series panel
*/
SceneSeries.initData = function() {
	 SceneSeries.visibleEpisodes = 7;
	 SceneSeries.itemsOnPage = SceneSeries.visibleEpisodes * 3;
}

/*
Sets current vod
*/
SceneSeries.setMovie = function (movie, sender) {
	SceneSeries.movie = movie;
	SceneSeries.sender = sender;
	SceneSeries.sortDirection = "ASC";
	SceneSeries.episodes = null;
	SceneSeries.pager = null;
	$.sfScene.show('Series');
	$.sfScene.focus('Series');
	SceneSeries.refresh();
}

/*
* Shows loading image
*/
SceneSeries.showLoading = function () {
    SceneSeries.isLoading = true;
	if (AppContext.CurrentScene == "Series") {
		Helpers.showLoading();
	}
    SceneSeries.dataLoaded = false;
}

/*
* Hides loading image
*/
SceneSeries.hideLoading = function () {
    SceneSeries.isLoading = false;
	if (AppContext.CurrentScene == "Series") {
		Helpers.hideLoading();
	}
    SceneSeries.dataLoaded = true;
}

SceneSeries.prototype.handleShow = function () {
	Logger.write("SceneSeries.handleShow()", "Series");
	// this function will be called when the scene manager show this scene 
    SceneSeries.loadImg();
	SceneSeries.newEpisode = "";
}

SceneSeries.prototype.handleHide = function () {
	Logger.write("SceneSeries.handleHide()", "Series");
	// this function will be called when the scene manager hide this scene  
    SceneSeries.hideImg();
	Helpers.hideLoading();
}

SceneSeries.prototype.handleFocus = function () {
	Logger.write("SceneSeries.handleFocus()", "Series");
	// this function will be called when the scene manager focus this scene
	if (ScenePlayer.isPlaying == true) {
		Helpers.setBackgroundOpacity();
	}
    SceneSeries.setHelpBar();
	AppContext.CurrentScene = "Series";
	if (SceneSeries.isLoading) {
		Helpers.showLoading();
	}
}

SceneSeries.prototype.handleBlur = function () {
	Logger.write("SceneSeries.handleBlur()", "Series");
	// this function will be called when the scene manager move focus to another scene from this scene
}

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

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

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

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

/*
Refreshes scene
*/
SceneSeries.refresh = function () {
	try {
		SceneSeries.showLoading();
		SceneSeries.loadSeries();
		SceneSeries.loadImg();
		$("#movieSeriesName").sfLabel({text: SceneSeries.movie.name});
		$("#movieEpisodeDescription").sfLabel({text: SceneSeries.movie.description});
		AppContext.CurrentScene = "Series"; 
		if  (ScenePlayer.isPlaying == true) {
			Helpers.setBackgroundOpacity();
		}
		$("#seriesLabel").sfLabel({text:Resources.getResources().Episodes});
		SceneSeries.setHelpBar();
	} catch (error) {
		ErrorHandler.HandleError(error, "Series");
	}
}

/*
Plays movie
*/ 
SceneSeries.handleEnter = function () {
	SceneSeries.loadEpisode(SceneSeries.pager.paging.getTotalIndex());
}

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

SceneSeries.loadEpisodeStream = function (index) {
	var callback = function (response) {
		try {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('Player');
			var movie = SceneSeries.episodes[index];
			movie.url = response.URL;
			movie.playlist = response.Playlist;
			movie.contentType = "VOD";
			ScenePlayer.episodePicker = new ArchProgramPicker(SceneSeries.episodes, SceneSeries.loadEpisode, index);
			ScenePlayer.episodePicker.count = SceneSeries.pager.paging.totalItems;
			ScenePlayer.setContent(movie, "Series");
			$.sfScene.focus('Player'); 
		} catch (error) {
			ErrorHandler.HandleError(error, "Series");
		}
    };
	
    var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Series", true, textStatus, jqXHR);
	};
	
	var id = SceneSeries.episodes[index].id;
	JsonServices.media.GetClientStreamUri(
		AppContext.user.sid, "VOD", id,
		AppContext.ClientSettings.bAId, AppContext.ClientSettings.cdnId,
		AppContext.ClientSettings.qualityPreset, AppContext.ClientSettings.shiftTimeZoneName,
		callback, errCallback
	);
}

/*
Shows pop up
*/ 
SceneSeries.handleYellow = function () {
	if (SceneSeries.isLoading) {
		return;
	}
    try {
        var episode = SceneSeries.episodes[SceneSeries.pager.paging.getTotalIndex()];
		var cb = function (status) {
			SceneSeries.setFavoriteStatus(status);
		};
		ScenePopUp.setWindow("Series", episode, cb);
        $.sfScene.show('PopUp');
        $.sfScene.focus('PopUp');
    } catch (error) {
        ErrorHandler.HandleError(error, "Series");
    }
}

SceneSeries.handleGreen = function () {
	SceneSeries.sortDirection = SceneSeries.sortDirection === "DESC" ? "ASC" : "DESC";
	SceneSeries.setHelpBar();
	SceneSeries.showLoading();
	SceneSeries.loadSeries();
}

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

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

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