function SceneMovies2(options) {
	this.options = options;
}

SceneMovies2.prototype.initialize = function () {
	alert("SceneMovies2.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
	
	SceneMovies2.initData();
	SceneMovies2.loadData();
}

SceneMovies2.initData = function () {
	this.pager = null;
	
	this.onPage = 50;
	
	this.categoryNameLength = 17;
	
	this.currentId = null;
	this.orderBy = null;
	
	$("#panelMovies2Categories").empty();
	
	this.genres = {
		root: null,
		active: null,
		panel: new SlidingPanel(0, 0, [], "category", this.onCategoriesSelectionChanged, 40, orientations.vertical, false, 320, "categoriesElement", 1500),
		history: []
	};
	
	$('#panelMovies2Categories').append(this.genres.panel.panel);
	
	var sortingOrders = [new PanelElement("movie_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); 
    $('#panelMovies2').append(this.sortingPanel.panel);
	this.sortingPanel.setIndex(0);
	
	this.moviesPanel = new MoviesPanel(125, 299, 595, 80, 5, function() { }, "panelMoviesMain", function() {}, function() { SceneMovies2.hideLoading(); SceneMovies2.moviesPanel.displayCounter(); }, 90, false, 34);
    this.moviesPanel.itemPrefix = "mainMovie";
    $(this.moviesPanel.panel).css('visibility', 'collapse');
    $('#panelMovies2').append(this.moviesPanel.panel);
}

SceneMovies2.refresh = function () {
	SceneMovies2.showLoading();
	$("#panelArchPlusPrograms").hide();
	$("#lbArchPlusPrograms").sfList("clear");
	$("#scrollArchPlusPrograms").hide();
	SceneMovies2.initData();
	SceneMovies2.loadData();
}

SceneMovies2.translate = function () {
    if (SceneMovies2.currentLang != AppContext.ClientSettings.Language) {
		$("#lblMovies2Title").sfLabel({text: Resources.getResources().LabelMovies.toLowerCase()});
		var sortingOrders = [new PanelElement("movie_date", Resources.getResources().Date), new PanelElement("rating", Resources.getResources().Rating) , new PanelElement("name", Resources.getResources().Name)];
        var idx = SceneMovies2.sortingPanel.index;
        SceneMovies2.sortingPanel.loadData(sortingOrders);
		SceneMovies2.sortingPanel.focusElement(idx);
		SceneMovies2.sortingPanel.blurPanel();
        SceneMovies2.currentLang = AppContext.ClientSettings.Language;
        SceneMovies2.setHelpBar();
    }
}

SceneMovies2.setHelpBar = function () {
	if (ScenePlayer.isPlaying) {
		$('#keysMovies2').sfKeyHelp({
			'red':Resources.getResources().LabelSettings, 
			'green':Resources.getResources().Search,
			'yellow':Resources.getResources().Info,
			'blue':Resources.getResources().Player, 
			'Stop':Resources.getResources().Stop ,
			'updown':'', 'leftright':Resources.getResources().MoveCursor, 
			'enter':Resources.getResources().Select,
			'return':Resources.getResources().BackToMainMenu
		});
	} else {
		$('#keysMovies2').sfKeyHelp({
			'red':Resources.getResources().LabelSettings, 
			'green':Resources.getResources().Search,
			'yellow':Resources.getResources().Info,
			'updown':'', 'leftright':Resources.getResources().MoveCursor, 
			'enter':Resources.getResources().Select,
			'return':Resources.getResources().BackToMainMenu
		});
	}
}

SceneMovies2.onCategoriesSelectionChanged = function (element, index) {
	Logger.write("New genres element: " + element, "Movies2", true);
	
	var genreId = element.replace("#divcategory", "");
	Logger.write("GenreId: " + genreId, "Movies2");
	if (genreId) {
		var callback = function (ok) {
			if (ok) {
				SceneMovies2.showLoading();
				SceneMovies2.currentId = null;
				SceneMovies2.sortingPanel.blurElement(SceneMovies2.sortingPanel.index);
				SceneMovies2.sortingPanel.index = -1;
				SceneMovies2.sortingPanel.focusElement(0);
				SceneMovies2.sortingPanel.blurPanel();
				SceneMovies2.loadMovies(genreId);
				SceneMovies2.prevCategoryIndex = index;
			} else {
				SceneMovies2.genres.panel.setIndex(SceneMovies2.prevCategoryIndex);
				SceneMovies2.genres.panel.stopTimer();
			}
		}
		
		if (Helpers.isAdultMovieGenre(genreId)) {
			SceneMovies2.checkPinCode(callback);
		} else {
			callback(true);
		}
	}
}

SceneMovies2.onSortingOrderChanged = function(orderId){
    Logger.write("SceneMovies2.onSortingOrderChanged(" + orderId + ")", "Movies2");
	var regex = /^\#divSortBy(\w+)/;
	var result = regex.exec(orderId);
	SceneMovies2.orderBy = result[1];
	if (SceneMovies2.orderBy == "name") {
		SceneMovies2.orderBy += " ASC";
	} else {
		SceneMovies2.orderBy += " DESC";
	}

	if (SceneMovies2.currentId) {
		SceneMovies2.showLoading();
		SceneMovies2.loadMovies(SceneMovies2.currentId);
	}
}

SceneMovies2.loadData = function () {
	SceneMovies2.showLoading();
	this.loadGenres();
}

SceneMovies2.loadGenres = function () {
	var errCallback = function(jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Movies", true, textStatus);
	};
	JsonServices.content.GetClientContentGenres(
		AppContext.user.sid, "VodGenreType", 
		SceneMovies2.onGenresLoaded, errCallback
	);
}

SceneMovies2.loadMovies = function (id, page) {
	SceneMovies2.currentId = id;
	SceneMovies2.showLoading();
	page = page || 1;
	var requestType = null;
	var genreId = null;
	if (parseInt(id)) {
		genreId = id;
	} else {
		requestType = id;
	}
	var errCallback = function(jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Movies", true, textStatus);
	};
	JsonServices.content.GetClientOnDemandContent(
		AppContext.user.sid, requestType, genreId, null, SceneMovies2.orderBy,
		SceneMovies2.onPage, page,
		SceneMovies2.onMoviesLoaded, errCallback
	);
}

SceneMovies2.addCategories = function (genres) {
	var result = [];
	var lastWeek = {
		id: "LastWeek",
		name: Resources.getResources().NewForWeek,
		hasSubCategories: true,
		subCategories: [],
		parent: null
	};
	var ids = ["Today", "Yesterday", "BeforeYesterday", "ThreeDaysAgo", "FourDaysAgo", "FiveDaysAgo", "SixDaysAgo", "SevenDaysAgo"];
	for (var i = 0; i < ids.length; i++) {
		var resource = Resources.getResources()["ArchPlusDay" + i];
		lastWeek.subCategories.push({
			id: ids[i],
			name: resource,
			hasSubCategories: false,
			parent: lastWeek
		});
	}
	result.push(lastWeek);
	result.push({
		id: "JustAdded",
		name: Resources.getResources().NewVideo,
		hasSubCategories: false,
		parent: null
	});
	result.push({
		id: "TopHundredWatched",
		name: Resources.getResources().Top100,
		hasSubCategories: false,
		parent: null
	});
	return result.concat(genres);
}

SceneMovies2.onGenresLoaded = function (result) {
	var genres = Models.ContentGenresTree(result.genres);
	SceneMovies2.genres.root = SceneMovies2.addCategories(genres);
	delete genres;
	SceneMovies2.onDataLoaded();
}

SceneMovies2.onDataLoaded = function () {
	if (SceneMovies2.genres.root.length > 0) {
		$("#movies2NoData").hide();
		SceneMovies2.bindCategories(SceneMovies2.genres.root);
		SceneMovies2.focusCategories();
		SceneMovies2.genres.panel.invokeSelectedChangedCallback();
	} else {
		SceneMovies2.genres.panel.stopTimer();
		$("#movies2NoData").show();
		SceneMovies2.hideLoading();
	}
}

SceneMovies2.onMoviesLoaded = function (movies) {
	SceneMovies2.bindMovies(movies);
}

SceneMovies2.bindCategories = function (categories, idToFocus) {
	var section = SceneMovies2.genres;
	if (!categories || !categories.length || !section || !section.root || !section.root.length) {
		return;
	}
	var elements = [];
	var index = 0;
	for (var i = 0; i < categories.length; i++) {
		var name = categories[i].hasSubCategories ? categories[i].name + ">" : categories[i].name;
		elements[i] = new PanelElement(categories[i].id, name);
		if (idToFocus && categories[i].id == idToFocus) {
			index = i;
		}
		Logger.write("Category name: " + name.replace(" ", "_"), "Movies2", true);
	}
	
	section.active = categories;
	Logger.write("Binding categories, elements length: " + elements.length, "Movies2", true);
	section.panel.loadData(elements);
	if (idToFocus) {
		section.panel.setIndex(index);
	}
}

SceneMovies2.bindMovies = function (movies, genreId) {
	Logger.write("SceneMovies2.bindMovies()", "Movies2");
    movies.items = movies.items || [];

    var finalCount = movies.paging.totalItems;
    SceneMovies2.paging = movies.paging;
    this.lastPage = movies.paging.pageNumber == movies.paging.totalPages; 
	this.moviesPanel.paging = movies.paging;
    (movies.paging.pageNumber == 1) ? this.moviesPanel.loadData(movies.items, "", finalCount) : this.moviesPanel.addData(movies.items);    
    $(this.moviesPanel.panel).css('visibility', 'visible');
}

SceneMovies2.checkPinCode = function (callback) {
	if (!AppContext.isAdultPasswordEntered()) {
		SceneMovies2.showPinWindow(callback);
	} else {
		callback(true);
	}
}

SceneMovies2.showPinWindow = function (callback) {
	var okFunc = function (result) {
		Logger.write("User system password: " + AppContext.user.userSystemPassword, "Movies2", true);
		Logger.write("Result: " + result, "Movies2", true);
		if (result == AppContext.user.userSystemPassword) {
			callback(true);
			AppContext.user.adultPasswordTimestamp = new Date();
		} else {
			ErrorHandler.HandleError(new Error(Resources.getResources().InvalidPinError), "Movies2", false, "", null, true);
			callback(false);
		}
	};
	var cancelFunc = function () {
		callback(false);
	};
	SceneTextboxPopUp.setCallbacks(okFunc, "Movies2", Resources.getResources().EnterPin, cancelFunc);
	SceneTextboxPopUp.show(true);
}

SceneMovies2.focusCategories = function () {
	SceneMovies2.genres.panel.focusPanel();
	SceneMovies2.activePanel = "categories";
}

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

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

SceneMovies2.getChildren = function (items, id) {
	for (var i = 0; i < items.length; i++) {
		if (items[i].id == id) {
			return items[i].subCategories;
		}
	}
	
	return items;
}

SceneMovies2.getParentCategories = function (categories) {
	if (categories && categories.active) {
		var parent = categories.active[0].parent;
		if (parent) {
			if (parent.parent) {
				return parent.parent.subCategories;
			} else {
				return categories.root;
			}
		}
	}
	
	return null;
}

SceneMovies2.moveToPrevCategories = function () {
	var section = SceneMovies2.genres;
	var categories = this.getParentCategories(section);
	
	if (categories) {
		var id = null;
		if (section.active[0].parent) {
			id = section.active[0].parent.id;
		}
		
		Logger.write("Sliding to init position", "SceneMovies2", true);
		this.bindCategories(categories, id);
		section.panel.slide(section.history.pop(), true);
		section.panel.focusPanel();
		return true;
	}
}

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


SceneMovies2.handleLeft = function () {
	if (SceneMovies2.isLoading) {
		return;
	}
	if (this.activePanel == "sorting") {
		this.sortingPanel.focusPrev();
	} else if (this.activePanel == "categories") {
		return this.moveToPrevCategories(this.genres);
	} else if (this.activePanel == "movies") {
		this.moviesPanel.blur();
		this.focusCategories();
		return true;
	}
}

SceneMovies2.handleRight = function () {
	if (SceneMovies2.isLoading) {
		return;
	}
	if (this.activePanel == "sorting") {
		this.sortingPanel.focusNext();
	} else if (this.activePanel == "categories") {
		if (this.moviesPanel.dataCount > 0) {
			this.genres.panel.blurPanel();
			this.focusMovies();
		}
	}
}

SceneMovies2.handleUp = function () {
	if (SceneMovies2.isLoading) {
		return;
	}
	if (this.activePanel == "categories") {
		if (this.genres.panel.index > 0) {
			this.genres.panel.focusPrev();
		} else {
			this.genres.panel.blurPanel();
			this.focusSorting();
		}
	} else if (this.activePanel == "movies") {
		if (this.moviesPanel.index > 0) {
			this.moviesPanel.focusPrev();
		} else {
			this.moviesPanel.blur();
			this.focusSorting();
		}
	}
}

SceneMovies2.handleDown = function () {
	if (SceneMovies2.isLoading) {
		return;
	}
	if (this.activePanel == "sorting") {
		this.sortingPanel.blurPanel();
		if (this.moviesPanel.dataCount > 0) {
			this.focusMovies();
		} else {
			this.focusCategories();
		}
	} else if (this.activePanel == "categories") {
		this.genres.panel.focusNext();
	} else if (this.activePanel == "movies") {
		var page = SceneMovies2.paging.pageNumber;
		var total = SceneMovies2.paging.totalPages;
		if (SceneMovies2.moviesPanel.isLastItem() && page < total) {
			var id = SceneMovies2.genres.panel.getFocusedId().replace("#divcategory", "");
			SceneMovies2.loadMovies(id, page + 1);
		} else {
			SceneMovies2.moviesPanel.focusNext();
		}
	}
}

SceneMovies2.handleEnter = function () {
	if (SceneMovies2.isLoading) {
		return;
	}
	if (this.activePanel == "categories") {
		Logger.write("Current element: " + this.genres.panel.getFocusedId(), "Movies2", true);
		var id = this.genres.panel.getFocusedId().replace("#divcategory", "");
		if (Helpers.isAdultMovieGenre(id) && !AppContext.isAdultPasswordEntered()) {
			return;
		}
		Logger.write("Category ID: " + id, "Movies2", true);
		var genres = this.getChildren(this.genres.active, id);
		if (genres) {
			Logger.write("First genre: " + genres[0].name, "Movies2", true);
			this.bindCategories(genres);
			this.genres.history.push(this.genres.panel.getCurrentPosition());
			this.genres.panel.focusPanel();
			this.genres.panel.invokeSelectedChangedCallback();
		}
	} else if (this.activePanel == "movies") {
		var item = this.moviesPanel.getCurrentMovie();
		var hasSeries = item.isContainer && item.episodeNum === 1 || item.episodeNum > 1;
		if (hasSeries) {
			$.sfScene.hide(AppContext.CurrentScene);
			SceneSeries.setMovie(item, "Movies2");
		} else {
			this.openPlayer(item);
		}
	}
}

SceneMovies2.handleYellow = function () {
	if (SceneMovies2.isLoading) {
		return;
	}
	try {
        if (this.activePanel == "movies") {
			var movie = SceneMovies2.moviesPanel.getCurrentMovie();
            ScenePopUp.setWindow("Movies2", movie);
            ScenePopUp.show();
        }       
    } catch (error) {
        ErrorHandler.HandleError(error,"Movies2");  
    }  
}

SceneMovies2.handleGreen = function () {
	try {
		Logger.write("Showing search window", "Movies2");
		var okFunc = function (result) {
			$.sfScene.hide('Movies2');
			SceneMoviesSearchResult.show();
			SceneMoviesSearchResult.loadResults(result);
		}
		SceneTextboxPopUp.setCallbacks(okFunc, "Movies2");
		SceneTextboxPopUp.show();
	} catch (error) {
		ErrorHandler.HandleError(error, "Movies2");
	}
}

SceneMovies2.handleRed = function () {
	try {
		$.sfScene.hide('Movies2');
		$.sfScene.show('Settings');
		$.sfScene.focus('Settings');
		SceneSettings.selectAccount();
	} catch (error) {
		ErrorHandler.HandleError(error, "Movies2");
	}
}

SceneMovies2.handleReturn = function () {
	var result = SceneMovies2.handleLeft();
	Logger.write("Result: " + result, "ArchPlus", true);
	if (!result) {
		SceneMovies2.backToMainMenu();
	}
}

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

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

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

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

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

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

SceneMovies2.prototype.handleFocus = function () {
	alert("SceneMovies2.handleFocus()");
	// this function will be called when the scene manager focus this scene
	AppContext.CurrentScene = "Movies2";
	
	if (ScenePlayer.isPlaying == true) {
		Helpers.setBackgroundOpacity();
	}
	SceneMovies2.setHelpBar();
	if (ErrorHandler.NeedToRefresh[AppContext.CurrentScene]) {
		SceneMovies2.refresh();
		ErrorHandler.NeedToRefresh[AppContext.CurrentScene] = false;
    }
	
	if (SceneMovies2.isLoading) {
		Logger.write("Showing loading indicator [handleFocus]", "Movies2");
		Helpers.showLoading();
	}
}

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

SceneMovies2.prototype.handleKeyDown = function (keyCode) {
	alert("SceneMovies2.handleKeyDown(" + keyCode + ")");
	// TODO : write an key event handler when this scene get focued
	if (Helpers.handleGlobalKeys(keyCode)) {
		return;
	}
	switch (keyCode) {
		case $.sfKey.LEFT:
            SceneMovies2.handleLeft();
			break;
		case $.sfKey.RIGHT:
            SceneMovies2.handleRight();
			break;
		case $.sfKey.UP:
            SceneMovies2.handleUp();
			break;
		case $.sfKey.DOWN:
            SceneMovies2.handleDown();
			break;

		case $.sfKey.ENTER:
            SceneMovies2.handleEnter();
			break;
		case $.sfKey.BLUE:
            if  (ScenePlayer.isPlaying == true) {
				$.sfScene.hide('Movies2');
				$.sfScene.show('Player');
				$.sfScene.focus('Player');
            }
            break;
		case $.sfKey.YELLOW:
            try {
                SceneMovies2.handleYellow();
            } catch (error) {
				ErrorHandler.HandleError(error, "Movies2");
            } finally {
				break;
            }
		case $.sfKey.GREEN:
            SceneMovies2.handleGreen(); 
            break;
		case $.sfKey.RED:
            SceneMovies2.handleRed();
            break;
		case $.sfKey.RETURN:
            widgetAPI.blockNavigation(event);
			SceneMovies2.handleReturn();
			break;
		case $.sfKey.EXIT:
			try {
				widgetAPI.blockNavigation(event);
				SceneMovies2.handleExit();
			} catch (error) {
				ErrorHandler.HandleError(error, "Movies2");
			}
			break;
		case $.sfKey.STOP:
            if  (ScenePlayer.isPlaying == true) {
				ScenePlayer.stop();
				SceneMovies2.setHelpBar();
            }
            break;
	}
}
