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

}

SceneArchPlus.displayOptions = {
	showDate: 1,
	showTime: 2,
	showChannelIcon: 4
}

SceneArchPlus.prototype.initialize = function () {
	Logger.write("SceneArchPlus.initialize()", "ArchPlus");
	// 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
	
	//SceneArchPlus.currentLang = AppContext.ClientSettings.Language;
	
	SceneArchPlus.initData();
	SceneArchPlus.loadData();
}

SceneArchPlus.initData = function () {
	//this.channels = null;
	this.currentChannelId = null;
	//this.genres = null;
	this.firstYear = 2007;
	
	this.activeCategoryIndex = null;
	
	this.pager = null;
	
	this.visiblePrograms = 9;
	
	this.onPage = this.visiblePrograms * 4;
	
	this.categoryNameLength = 17;
	
	$("#panelSections").empty();
	$("#panelArchPlusCategories").empty();
	
	this.popularCategoriesPanel = new SlidingPanel(0, 0, [], "popularCategory", this.onPopularCategorieSelectionChanged, 40, orientations.vertical, false, 320, "categoriesElement", 1500);
    $('#panelArchPlusCategories').append(this.popularCategoriesPanel.panel);
	this.popularCategoriesPanel.hide();
	
	this.channelsCategoriesPanel = new SlidingPanel(0, 0, [], "channelCategory", this.onChannelsCategorieSelectionChanged, 40, orientations.vertical, false, 320, "categoriesElement", 1500);
    $('#panelArchPlusCategories').append(this.channelsCategoriesPanel.panel);
	this.channelsCategoriesPanel.hide();
	
	this.genresCategoriesPanel = new SlidingPanel(0, 0, [], "genreCategory", this.onGenresCategorieSelectionChanged, 40, orientations.vertical, false, 320, "categoriesElement", 1500);
    $('#panelArchPlusCategories').append(this.genresCategoriesPanel.panel);
	this.genresCategoriesPanel.hide();
	
	this.sectionsPanel = new SlidingPanel(80, 300, [], "section", this.onActiveSectionChanged, 140, orientations.horizontal, false, 1000);
	$('#panelSections').append(this.sectionsPanel.panel);
	
	this.channels = {
		root: null,
		active: null,
		panel: this.channelsCategoriesPanel,
		history: []
	};
	
	this.genres = {
		root: null,
		active: null,
		panel: this.genresCategoriesPanel,
		history: []
	};
}

SceneArchPlus.translate = function () {
    if (SceneArchPlus.currentLang != AppContext.ClientSettings.Language)
    {
		$('#lblArchPlusTitle').sfLabel({text: Resources.getResources().ArchPlusTitle.toLowerCase()});
		$("#archPlusNoData").html(Resources.getResources().NoData);
		SceneArchPlus.loadSections();
		SceneArchPlus.bindPopularCategories();
		if (SceneArchPlus.channels && SceneArchPlus.channels.root && SceneArchPlus.channels.root.length) {
			SceneArchPlus.updateChannelsSubCategories();
			SceneArchPlus.bindChannelsCategories(SceneArchPlus.channels.root);
			
			if (SceneArchPlus.activePanel == "channelsCategoriesPanel") {
				SceneArchPlus[SceneArchPlus.activePanel].invokeSelectedChangedCallback();
			}
		}
		
        SceneArchPlus.currentLang = AppContext.ClientSettings.Language;
        SceneArchPlus.setHelpBar();
    }
}

SceneArchPlus.setHelpBar = function () {
	if (ScenePlayer.isPlaying) {
		$('#keysArchPlus').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 {
		$('#keysArchPlus').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
		});
	}
}

SceneArchPlus.onPopularCategorieSelectionChanged = function (element, index) {
	var requestType = null;
	Logger.write("New popular element: " + element, "ArchPlus", true);
	
	var id = element.replace("#divpopularCategory", "");
	
	var category = null;
	for (var i = 0; i < SceneArchPlus.popular.length; i++) {
		if (SceneArchPlus.popular[i].id == id) {
			category = SceneArchPlus.popular[i];
			break;
		}
	}
	
	if (category) {
		SceneArchPlus.currentDisplayOptions = category.displayOptions;
		SceneArchPlus.loadPrograms(category.tag, null, null, null, null);
		SceneArchPlus.activeCategoryIndex = index;
	}
}

SceneArchPlus.onChannelsCategorieSelectionChanged = function (element, index) {
	Logger.write("New channels element: " + element, "ArchPlus", true);
	if (!element) {
		return;
	}
	
	var id = element.replace("#divchannelCategory", "");
	var categories = SceneArchPlus.channels.active;
	var isChannels = categories[0].isChannel;
	if (isChannels && isChannels === true) {
		SceneArchPlus.currentChannelId = id;
	}
	if (isChannels) {
		SceneArchPlus.currentDisplayOptions = SceneArchPlus.displayOptions.showTime | SceneArchPlus.displayOptions.showDate | SceneArchPlus.displayOptions.showChannelIcon;
		var tag = categories[0].subCategories[0].tag;
		id = parseInt(id);
		SceneArchPlus.loadPrograms("SearchByDateRangExpanded", id, tag.dateFrom, tag.dateTill, null);
		SceneArchPlus.activeCategoryIndex = index;
	} else if (SceneArchPlus.currentChannelId) {
		var item = SceneArchPlus.getItem(categories, id);
		if (item && item.tag) {
			var dateFrom = item.tag.dateFrom;
			var dateTill = item.tag.dateTill;
			var displayOptions = item.displayOptions ? item.displayOptions : 7;
			SceneArchPlus.currentDisplayOptions = displayOptions;
			SceneArchPlus.loadPrograms("SearchByDateRangExpanded", SceneArchPlus.currentChannelId, dateFrom, dateTill, null);
			SceneArchPlus.activeCategoryIndex = index;
		}
	}
}

SceneArchPlus.onGenresCategorieSelectionChanged = function (element, index) {
	Logger.write("New genres element: " + element, "ArchPlus", true);
	
	var genreId = element.replace("#divgenreCategory", "");
	if (genreId) {
		SceneArchPlus.currentDisplayOptions = SceneArchPlus.displayOptions.showDate | SceneArchPlus.displayOptions.showTime | SceneArchPlus.displayOptions.showChannelIcon;
		SceneArchPlus.loadPrograms(null, null, null, null, genreId, null, "name ASC");
		SceneArchPlus.activeCategoryIndex = index;
	}
}

SceneArchPlus.onActiveSectionChanged = function (element) {
	SceneArchPlus.popularCategoriesPanel.stopTimer();
	SceneArchPlus.channelsCategoriesPanel.stopTimer();
	SceneArchPlus.genresCategoriesPanel.stopTimer();
	
	SceneArchPlus.popularCategoriesPanel.hide();
	SceneArchPlus.channelsCategoriesPanel.hide();
	SceneArchPlus.genresCategoriesPanel.hide();
	
	Logger.write("Focusing element: " + element, "ArchPlus");
	
	if (element.indexOf("popular") > -1) {
		SceneArchPlus.popularCategoriesPanel.show();
		SceneArchPlus.popularCategoriesPanel.invokeSelectedChangedCallback();
	} else if (element.indexOf("channels") > -1) {
		SceneArchPlus.channelsCategoriesPanel.show();
		SceneArchPlus.channelsCategoriesPanel.invokeSelectedChangedCallback();
	} else if (element.indexOf("genres") > -1) {
		SceneArchPlus.genresCategoriesPanel.show();
		SceneArchPlus.genresCategoriesPanel.invokeSelectedChangedCallback();
	}
}

SceneArchPlus.loadSections = function () {
	var sections = [];
	sections.push(new PanelElement("channels", Resources.getResources().ArchPlusChannels));
	sections.push(new PanelElement("genres", Resources.getResources().ArchPlusGenres));
	sections.push(new PanelElement("popular", Resources.getResources().ArchPlusPopular));
	SceneArchPlus.sectionsPanel.loadData(sections, true);
}

SceneArchPlus.loadData = function () {
	this.showLoading();
	this.offset = AppContext.getNaEstUtcOffset();
	setTimeout(function () {
		SceneArchPlus.loadGenres();
		SceneArchPlus.loadChannels();
	}, 1);
}

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

SceneArchPlus.loadChannels = function () {
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "ArchPlus", true, textStatus, jqXHR);
	};
	JsonServices.content.GetClientChannels(
		AppContext.user.sid, "ArcPlus", null, null,
		SceneArchPlus.onChannelsLoaded, errCallback
	);
}

SceneArchPlus.loadPrograms = function (requestType, channelId, dateFrom, dateTill, genreId, keyWord, orderBy) {
	var request = new Models.ArchPlusRequest(requestType, channelId, dateFrom, dateTill, genreId, keyWord, orderBy);
	
	if (!request.equals(this.request)) {
		this.showLoading();
		var errCallback = function (jqXHR, textStatus, error) {
			ErrorHandler.HandleError(error, "ArchPlus", true, textStatus, jqXHR);
		};
		var from = null;
		var till = null;
		if (dateFrom && dateTill) {
			from = new Date(dateFrom);
			till = new Date(dateTill);
			from.setHours(from.getHours() - SceneArchPlus.offset + AppContext.deviceOffset/60);
			till.setHours(till.getHours() - SceneArchPlus.offset + AppContext.deviceOffset/60);
		}
		JsonServices.content.GetClientProgramGuide(
			AppContext.user.sid, "ArcPlus", requestType, channelId, genreId,
			from, till, keyWord, null, false, this.onPage, 1,
			AppContext.ClientSettings.shiftTimeZoneName, AppContext.ClientSettings.shiftTimeZoneName,
			SceneArchPlus.onProgramsLoaded, errCallback
		);
		
		this.request = request;
	}
}

SceneArchPlus.checkDataLoaded = function () {
	if (SceneArchPlus.channels.root && SceneArchPlus.genres.root) {
		SceneArchPlus.onDataLoaded();
	}
}

SceneArchPlus.onDataLoaded = function () {
	if (this.channels.root.length > 0 && this.genres.root.length > 0) {
	//Logger.write("data loaded from: " + (new Error()).stack, "ArchPlus", true);
		$("#archPlusNoData").hide();
		this.bindChannelsCategories(this.channels.root);
		this.bindGenresCategories(this.genres.root);
		
		this.focusActiveCategories();
		this.sectionsPanel.invokeSelectedChangedCallback();
	} else {
		SceneArchPlus.popularCategoriesPanel.stopTimer();
		SceneArchPlus.channelsCategoriesPanel.stopTimer();
		SceneArchPlus.genresCategoriesPanel.stopTimer();
		$("#archPlusNoData").show();
		$("#panelSections").hide();
		SceneArchPlus.hideLoading();
	}
}

SceneArchPlus.onGenresLoaded = function (result) {
	var genres = Models.ContentGenresTree(result.genres);
	SceneArchPlus.genres.root = genres;
	
	SceneArchPlus.checkDataLoaded();
}

SceneArchPlus.onChannelsLoaded = function (result) {
	var channels = Models.CategoriesFromChannelsCollection(result.items);
	SceneArchPlus.channels.root = channels;
	SceneArchPlus.updateChannelsSubCategories(SceneArchPlus.checkDataLoaded);
	
	//SceneArchPlus.checkDataLoaded();
}

SceneArchPlus.updateChannelsSubCategories = function (callback) {
	var getTimeCallback = function (result) {
		var tmpDate = result;
		var shift = 0;
		for (var i = 0; i < AppContext.TimeZones.length; i++) {
			if (AppContext.ClientSettings.timeZoneName == AppContext.TimeZones[i].id) {
				shift = parseInt(AppContext.TimeZones[i].utcOffset);
				break;
			}
		}
		tmpDate.setMinutes(tmpDate.getMinutes() + shift);
		var time = Helpers.getUtcTime(tmpDate);
		
		var channelSubCategories = SceneArchPlus.createChannelSubCategories(time);
		for (var i = 0; i < SceneArchPlus.channels.root.length; i++) {
			SceneArchPlus.channels.root[i].subCategories = channelSubCategories;
		}

		if (!!callback) {
			callback();
		}
	};

	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "LiveTv", true, textStatus, jqXHR);
	};
	
	JsonServices.media.GetCurrentUtcTime(getTimeCallback, errCallback);
}

SceneArchPlus.onProgramsLoaded = function (result) {
	var isChannels = SceneArchPlus.activePanel == "channelsCategoriesPanel";
	var paging = result.paging;
	Logger.write("Total items: " + paging.totalItems, "ArchPlus", true);
	SceneArchPlus.pager = new ListPager(paging, "#lbArchPlusPrograms", SceneArchPlus.visiblePrograms, SceneArchPlus.onPageChanging, SceneArchPlus.onPagerOutOfBounds);
	SceneArchPlus.programs = result.items;
	
	SceneArchPlus.bindPrograms();
	if (SceneArchPlus.activePanel == "programs") {
		if (SceneArchPlus.programs.length > 0) {
			SceneArchPlus.focusPrograms();
		} else {
			SceneArchPlus.focusActiveCategories();
		}
	}
	SceneArchPlus.hideLoading();
}

SceneArchPlus.onPageChanging = function (onPage, pageNumber, pageChangedCallback) {
	Logger.write("Page changed callback: " + pageChangedCallback ? pageChangedCallback.toSource() : pageChangedCallback, "ArchPlus", true);
	SceneArchPlus.showLoading();
	var completeCallback = function (result) {
		var isChannels = SceneArchPlus.activePanel == "channelsCategoriesPanel";
		SceneArchPlus.programs = result.items;
		
		SceneArchPlus.bindPrograms();
		pageChangedCallback(true);
		Logger.write("New scroll page number: " + SceneArchPlus.pager.scroll.pageNumber, "ArchPlus", true);
		$('#scrollArchPlusPrograms').sfScroll('move', SceneArchPlus.pager.scroll.pageNumber);
		SceneArchPlus.hideLoading();
	};
	
	JsonServices.content.GetClientProgramGuide(
		AppContext.user.sid, "ArcPlus", SceneArchPlus.request.requestType, SceneArchPlus.request.channelId, 
		SceneArchPlus.request.genreId, SceneArchPlus.request.dateFrom, SceneArchPlus.request.dateTill, 
		SceneArchPlus.request.keyWord, SceneArchPlus.request.orderBy, false, onPage, pageNumber,
		AppContext.ClientSettings.shiftTimeZoneName, AppContext.ClientSettings.timeZoneName,
		completeCallback,
		function (jqXHR, textStatus, error) {
			ErrorHandler.HandleError(error, "ArchPlus", true, textStatus, jqXHR);
			pageChangedCallback(false);
		}
	);

}

SceneArchPlus.onPagerOutOfBounds = function (num) {
	if (num < 0) {
		$('#lbArchPlusPrograms').sfList('blur');
		SceneArchPlus.focusSectionsPanel();
	}
}

SceneArchPlus.getProgramHtml = function (program) {
	var result = "";
	var isChannels = !!SceneArchPlus.request.channelId;
	var date = new Date(program.recentAirTime.startTime);
	date.setHours(date.getHours() + SceneArchPlus.offset - AppContext.deviceOffset/60);
	if (SceneArchPlus.currentDisplayOptions & SceneArchPlus.displayOptions.showDate) {
		result += "<span class='programDate'>" + DateHelper.getArchPlusDate(date) + "</span>";
	}
	if (SceneArchPlus.currentDisplayOptions & SceneArchPlus.displayOptions.showChannelIcon) {
		var channelId = isChannels ? SceneArchPlus.currentChannelId : program.recentAirTime.channelID;
		var url = AppContext.ImageUrlTemplate.replace("{0}", channelId).replace("{1}", 25).replace("{2}", 1) + "&width=28";
		result += "<div class='logoBack'><img  width='28' height='28' src='" + url + "' /></div>";
	}
	if (SceneArchPlus.currentDisplayOptions & SceneArchPlus.displayOptions.showTime) {
		result += "<span class='programTime'>" + date.toLocaleFormat("%H:%M") + "</span>";
	}
	var titleClass = "programTitle";
	var hasSeries = program.isContainer && program.episodeNum === 1 || program.episodeNum > 1;
	if (hasSeries && !isChannels) {
		titleClass += " series";
	}
	result += "<span class='" + titleClass + "'>" + program.name + "</span>";

	return result;
}

SceneArchPlus.bindPopularCategories = function () {
	var popular = [];
	var displayOptions = SceneArchPlus.displayOptions.showDate | SceneArchPlus.displayOptions.showTime | SceneArchPlus.displayOptions.showChannelIcon;
	popular.push(new Models.Category("thisWeek", Resources.getResources().ArchPlusWeek, false, null, "TopHundredWatchedWeek", displayOptions));
	popular.push(new Models.Category("thisMonth", Resources.getResources().ArchPlusMonth, false, null, "TopHundredWatchedMonth", displayOptions));
	popular.push(new Models.Category("allTime", Resources.getResources().ArchPlusAllTime, false, null, "TopHundredWatched", displayOptions));
	this.popular = popular;

	var elements = [];
	for (var i = 0; i < this.popular.length; i++) {
		elements[i] = new PanelElement(this.popular[i].id, this.popular[i].name);
	}
	
	this.popularCategoriesPanel.loadData(elements, true);
}

SceneArchPlus.bindCategories = function (section, categories, idToFocus) {
	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;
		}
	}
	
	section.active = categories;
	Logger.write("Binding categories, elements length: " + elements.length, "ArchPlus", true);
	section.panel.loadData(elements);
	if (idToFocus) {
		section.panel.setIndex(index);
	}
}

SceneArchPlus.bindChannelsCategories = function (categories, idToFocus) {
	this.bindCategories(this.channels, categories, idToFocus);
}

SceneArchPlus.bindGenresCategories = function (categories, idToFocus) {
	this.bindCategories(this.genres, categories, idToFocus);
}

SceneArchPlus.bindPrograms = function () {
	var len = this.programs.length;
	if (len > 0) {
		$('#lbArchPlusPrograms').css('visibility', 'visible');

		if (len > this.visiblePrograms)
		{
			$('#scrollArchPlusPrograms').css('visibility', 'visible');
		}
		
		var lbElems = [];
		for (var i = 0; i < len; i++) {
			lbElems.push(this.getProgramHtml(this.programs[i]));
		}
		var perPage = len > this.visiblePrograms ? this.visiblePrograms : len;
		$('#lbArchPlusPrograms').sfList({data: lbElems, index: '0', itemsPerPage: perPage});
		$('#lbArchPlusPrograms').sfList('blur');
		var pagesNum = SceneArchPlus.pager.scroll.getTotalPages();
		Logger.write("Total items: " + SceneArchPlus.pager.paging.totalItems + "; total pages: " + pagesNum, "ArchPlus", true);
		$('#scrollArchPlusPrograms').sfScroll({page: pagesNum});
		$("#panelArchPlusPrograms").show();
		$("#scrollArchPlusPrograms").show();
		$("#pagerInfo").html(this.pager.paging.getPagerInfo());
	} else {
		$('#scrollArchPlusPrograms').css('visibility', 'hidden');
		$('#lbArchPlusPrograms').sfList('clear');
		$('#lbArchPlusPrograms').css('visibility', 'hidden');
		$("#pagerInfo").html("");
	}
	Logger.write("Programs binded", "ArchPlus", true);
}

SceneArchPlus.createChannelSubCategories = function (time) {
	var defaultDisplayOptions = SceneArchPlus.displayOptions.showTime | SceneArchPlus.displayOptions.showDate | SceneArchPlus.displayOptions.showChannelIcon;

	var now = new Date(time);
	var subCategories = [];
	var dateTill = new Date(time);
	var dateFrom = new Date(dateTill.getTime());
	dateFrom.setHours(dateFrom.getHours() - 24);
	var lastDayTag = {
		dateFrom: dateFrom,
		dateTill: dateTill
	};
	subCategories.push(new Models.Category("lastDay", Resources.getResources().LastDay, false, null, lastDayTag, defaultDisplayOptions));
	
	var weekDay = now.getDay();
	weekDay = weekDay == 0 ? 7 : weekDay;
	if (weekDay > 1) {
		var lastWeekFrom = new Date(now.getFullYear(), now.getMonth(), now.getDate() - weekDay, 0, 0, 0);
		var lastWeekTag = new DateHelper.DateRange(lastWeekFrom, now);
		var lastWeek = new Models.Category("lastWeek", Resources.getResources().ArchPlusWeek, true, null, lastWeekTag, defaultDisplayOptions);
		for (var i = 1; i < weekDay; i++) {
			var tmpDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i, now.getHours(), now.getMinutes(), now.getSeconds());
			var tag = new DateHelper.DateRange(tmpDate);
			lastWeek.subCategories.push(new Models.Category("lastWeekDay"+i, Resources.getResources()["ArchPlusDay"+i], false, lastWeek, tag, defaultDisplayOptions));
		}
		subCategories.push(lastWeek);
	}
	
	var lastMonthFrom = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
	var lastMonthTag = new DateHelper.DateRange(lastMonthFrom, now);
	var lastMonth = new Models.Category("lastMonth", Resources.getResources().ArchPlusMonth, true, null, lastMonthTag, defaultDisplayOptions);
	var day = now.getDate();
	for (var i = day; i > 0; i--) {
		now.setDate(i);
		var tag = new DateHelper.DateRange(now);
		lastMonth.subCategories.push(new Models.Category("lastMonthDay"+i, i.toString(), false, lastMonth, tag, defaultDisplayOptions));
	}
	subCategories.push(lastMonth);
	
	var date = new Date(time);
	var yearsToShow = date.getFullYear() - this.firstYear + 1;
	for (var i = 0; i < yearsToShow; i++) {
		var yearStr = date.getFullYear().toString();
		var dateFrom = new Date(date.getFullYear(), 0, 1, 0, 0, 0);
		var yearTag = new DateHelper.DateRange(dateFrom, date);
		var year = new Models.Category("year" + yearStr, yearStr, true, null, yearTag, defaultDisplayOptions);
		
		var months = date.getMonth() + 1;
		for (var j = 0; j < months; j++) {
			var monthStr = date.getMonth().toString();
			dateFrom = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0);
			var monthTag = new DateHelper.DateRange(dateFrom, date);
			var month = new Models.Category("year"+yearStr+"month"+monthStr, Resources.getResources()["ArchPlusMonth"+monthStr], true, year, monthTag, defaultDisplayOptions);
			var daysInMonth = date.getDate();
			for (var k = 0; k < daysInMonth; k++) {
				var dayStr = date.getDate().toString();
				var dayTag = new DateHelper.DateRange(date);
				var monthDay = new Models.Category("year"+yearStr+"month"+monthStr+"day"+dayStr, dayStr, false, month, dayTag, defaultDisplayOptions);
				
				month.subCategories.push(monthDay);
				date.setDate(date.getDate() - 1);
			}
			
			year.subCategories.push(month);
		}
		
		subCategories.push(year);
	}
	
	return subCategories;
}

SceneArchPlus.showLoading = function () {
	Logger.write("SceneArchPlus.showLoading()", "ArchPlus");
    SceneArchPlus.isLoading = true;
	if (AppContext.CurrentScene == "ArchPlus") {
		Helpers.showLoading();
	}
    SceneArchPlus.dataLoaded = false;
}

SceneArchPlus.hideLoading = function () {
	Logger.write("SceneArchPlus.hideLoading()", "ArchPlus");
	SceneArchPlus.isLoading = false;
	if (AppContext.CurrentScene == "ArchPlus") {
		Helpers.hideLoading();
	}
    SceneArchPlus.dataLoaded = true;
}

SceneArchPlus.focusSectionsPanel = function () {
	SceneArchPlus.sectionsPanel.focusPanel();
	SceneArchPlus.activePanel = "sectionsPanel";
}

SceneArchPlus.focusPopular = function () {
	SceneArchPlus.popularCategoriesPanel.focusPanel();
	SceneArchPlus.activePanel = "popularCategoriesPanel";
}

SceneArchPlus.focusChannels = function () {
	SceneArchPlus.channelsCategoriesPanel.focusPanel();
	SceneArchPlus.activePanel = "channelsCategoriesPanel";
}

SceneArchPlus.focusGenres = function () {
	SceneArchPlus.genresCategoriesPanel.focusPanel();
	SceneArchPlus.activePanel = "genresCategoriesPanel";
}

SceneArchPlus.focusActiveCategories = function () {
	var focusedId = this.sectionsPanel.getFocusedId();
	if (focusedId.indexOf("popular") > -1) {
		this.focusPopular();
	} else if (focusedId.indexOf("channels") > -1) {
		this.focusChannels();
	} else if (focusedId.indexOf("genres") > -1) {
		this.focusGenres();
	}
}

SceneArchPlus.focusPrograms = function () {
	$("#lbArchPlusPrograms").sfList('focus');
	SceneArchPlus.activePanel = "programs";
	$("#pagerInfo").html(this.pager.paging.getPagerInfo());
}

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

SceneArchPlus.getItem = function (items, id) {
	for (var i = 0; i < items.length; i++) {
		if (items[i].id == id) {
			return items[i];
		}
	}
	
	return null;
}

SceneArchPlus.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;
}

SceneArchPlus.getChannelAr = function (channelId) {
	if (!SceneArchPlus.channels || !SceneArchPlus.channels.root) {
		if (channelId == 23) {
			return {
				x: 16,
				y: 9
			};
		}
		return null;
	}
	
	for (var i = 0; i < SceneArchPlus.channels.root.length; i++) {
		var channel = SceneArchPlus.channels.root[i];
		if (channel.id == channelId) {
			return channel.ar;
		}
	}
	
	if (channelId == 23) {
		return {
			x: 16,
			y: 9
		};
	}
	return null;
}

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

SceneArchPlus.openPlayer = function () {
	var itemIndex = $('#lbArchPlusPrograms').sfList('getIndex');
	var item = SceneArchPlus.programs[itemIndex];
	
	var callback = function (response) {
		try {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('Player');
			var video = item;
			Logger.write("channel ID: " + item.recentAirTime.channelID, "ArchPlus", true);
			var ar = SceneArchPlus.getChannelAr(item.recentAirTime.channelID);
			if (ar) {
				Logger.write("AR gotten: " + ar.x + ":" + ar.y, "ArchPlus", true);
				video.ar = ar;
			}
			video.currentTime = 0;
			video.url = response.URL;
			video.playlist = response.Playlist;
			video.contentType = "ArcPlus";
			ScenePlayer.setContent(video, "ArchPlus");
			$.sfScene.focus('Player');
		} catch (error) {
			ErrorHandler.HandleError(error, "ArchPlus");
		}
    };
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "ArchPlus", 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, "ArchPlus");  
	}
}

SceneArchPlus.moveToPrevCategories = function (section) {
	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", "ArchPlus", true);
		Logger.write("categories: " + categories, "ArchPlus", true);
		this.bindCategories(section, categories, id);
		section.panel.slide(section.history.pop(), true);
		section.panel.focusPanel();
		return true;
	}
}

SceneArchPlus.handleLeft = function () {
	if (this.activePanel == "sectionsPanel") {
		this.sectionsPanel.focusPrev();
	} else if (this.activePanel == "genresCategoriesPanel") {
		return this.moveToPrevCategories(this.genres);
	} else if (this.activePanel == "channelsCategoriesPanel") {
		return this.moveToPrevCategories(this.channels);
	} else if (this.activePanel == "programs") {
		$('#lbArchPlusPrograms').sfList('blur');
		this.focusActiveCategories();
		return true;
	}
}

SceneArchPlus.handleRight = function () {
	if (this.activePanel == "sectionsPanel") {
		this.sectionsPanel.focusNext();
	} else if (this.activePanel == "popularCategoriesPanel" || this.activePanel == "channelsCategoriesPanel" || this.activePanel == "genresCategoriesPanel") {
		if (this.programs.length > 0) {
			this[this.activePanel].blurPanel();
			this.focusPrograms();
		}
	}
}

SceneArchPlus.handleUp = function () {
	if (this.activePanel == "popularCategoriesPanel" || this.activePanel == "channelsCategoriesPanel" || this.activePanel == "genresCategoriesPanel") {
		if (this[this.activePanel].index > 0) {
			this[this.activePanel].focusPrev();
		} else {
			this[this.activePanel].setIndex(this.activeCategoryIndex);
			this[this.activePanel].blurPanel();
			this[this.activePanel].stopTimer();
			this.focusSectionsPanel();
		}
	} else if (this.activePanel == "programs") {
		var index = this.pager.paging.index
		this.pager.prev();
		if (index > 0) {
			$("#pagerInfo").html(this.pager.paging.getPagerInfo());
		}
		$('#scrollArchPlusPrograms').sfScroll('move', this.pager.scroll.pageNumber);
	}
}

SceneArchPlus.handleDown = function () {
	if (this.activePanel == "sectionsPanel") {
		this.sectionsPanel.blurPanel();
		if (this.programs.length > 0) {
			this.focusPrograms();
		} else {
			this.focusActiveCategories();
		}
	} else if (this.activePanel == "popularCategoriesPanel" || this.activePanel == "channelsCategoriesPanel" || this.activePanel == "genresCategoriesPanel") {
		this[this.activePanel].focusNext();
	} else if (this.activePanel == "programs") {
		this.pager.next();
		$("#pagerInfo").html(this.pager.paging.getPagerInfo());
		$('#scrollArchPlusPrograms').sfScroll('move', this.pager.scroll.pageNumber);
	}
}

SceneArchPlus.handleEnter = function () {
	if (this.activePanel == "genresCategoriesPanel") {
		Logger.write("Current element: " + this.genres.panel.getFocusedId(), "ArchPlus", true);
		var id = parseInt(this.genres.panel.getFocusedId().replace("#divgenreCategory", ""));
		var genres = this.getChildren(this.genres.active, id);
		if (genres) {
			this.bindCategories(this.genres, genres);
			this.genres.history.push(this.genres.panel.getCurrentPosition());
			this.genres.panel.focusPanel();
			this.genres.panel.invokeSelectedChangedCallback();
		}
	} else if (this.activePanel == "channelsCategoriesPanel") {
		var id = this.channels.panel.getFocusedId().replace("#divchannelCategory", "");
		Logger.write("Current element: " + this.channels.panel.getFocusedId() + ", id: " + id, "ArchPlus", true);
		var item = this.getItem(this.channels.active, id);
		if (!item) {
			return;
		}
		
		var categories = item.subCategories;
		if (item.isChannel) {
			SceneArchPlus.currentChannelId = item.id;
			item.updateSubCategoriesParent();
		}
		
		this.bindCategories(this.channels, categories);
		this.channels.history.push(this.channels.panel.getCurrentPosition());
		this.channels.panel.focusPanel();
	} else if (this.activePanel == "programs") {
		var idx = $('#lbArchPlusPrograms').sfList('getIndex');
		var program = SceneArchPlus.programs[idx];
		var hasSeries = program.isContainer && program.episodeNum === 1 || program.episodeNum > 1;
		if (hasSeries && !SceneArchPlus.request.channelId) {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('ProgramEpisodes');
			$.sfScene.focus('ProgramEpisodes');
			SceneProgramEpisodes.loadEpisodes(program.id, "ArchPlus");
		} else {
			SceneArchPlus.openPlayer();
		}
	}
}

SceneArchPlus.handleYellow = function () {
	if (this.activePanel == "programs") {
		var itemIndex = $('#lbArchPlusPrograms').sfList('getIndex');
		var item = SceneArchPlus.programs[itemIndex];
		ScenePopUp.setWindow("ArchPlus", item);
		$.sfScene.show('PopUp');
		$.sfScene.focus('PopUp');
	}
}

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

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

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

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

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

SceneArchPlus.prototype.handleFocus = function () {
	alert("SceneArchPlus.handleFocus()");
	// this function will be called when the scene manager focus this scene
	AppContext.CurrentScene = "ArchPlus";
	if (ScenePlayer.isPlaying == true) {
	    Helpers.setBackgroundOpacity();
	}
	SceneArchPlus.setHelpBar();
	if (ErrorHandler.NeedToRefresh[AppContext.CurrentScene]) {
		SceneArchPlus.refresh();
		ErrorHandler.NeedToRefresh[AppContext.CurrentScene] = false;
    } else {
		var focusedSection = SceneArchPlus.sectionsPanel.getFocusedId();
		if (focusedSection.indexOf("popular") > -1) {
			SceneArchPlus.popularCategoriesPanel.invokeSelectedChangedCallback();
		} else if (focusedSection.indexOf("channels") > -1) {
			SceneArchPlus.channelsCategoriesPanel.invokeSelectedChangedCallback();
		} else if (focusedSection.indexOf("genres") > -1) {
			SceneArchPlus.genresCategoriesPanel.invokeSelectedChangedCallback();
		}
	}
	
	if (SceneArchPlus.isLoading) {
		Logger.write("Showing loading indicator [handleFocus]", "ArchPlus");
		Helpers.showLoading();
	}
}

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

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

		case $.sfKey.ENTER:
            SceneArchPlus.handleEnter();
			break;
		case $.sfKey.BLUE:
            if  (ScenePlayer.isPlaying == true) {
				$.sfScene.hide('ArchPlus');
				$.sfScene.show('Player');
				$.sfScene.focus('Player');
            }
            break;
		case $.sfKey.YELLOW:
            try {
                SceneArchPlus.handleYellow();
            } catch (error) {
				ErrorHandler.HandleError(error, "ArchPlus");
            } finally {
				break;
            }
		case $.sfKey.GREEN:
            try {
				Logger.write("Showing search window", "ArchPlus");
				var okFunc = function (result)
				{
					$.sfScene.hide('ArchPlus');
					SceneSearchChannels.show();
                    SceneSearchChannels.loadResults(result, "ArchPlus");
				}
				SceneTextboxPopUp.setCallbacks(okFunc, "ArchPlus");
				SceneTextboxPopUp.show();
            } catch (error) {
				ErrorHandler.HandleError(error, "ArchPlus");
            }    
            break;
		case $.sfKey.RED:
            try {
                $.sfScene.hide('ArchPlus');
                $.sfScene.show('Settings');
                $.sfScene.focus('Settings');
                SceneSettings.selectAccount();
            } catch (error) {
                ErrorHandler.HandleError(error, "ArchPlus");  
            }  
            break;
		case $.sfKey.RETURN:
            widgetAPI.blockNavigation(event);
			SceneArchPlus.handleReturn();
			break;
		case $.sfKey.EXIT:
			try {
				widgetAPI.blockNavigation(event);
				SceneArchPlus.handleExit();
			} catch (error) {
				ErrorHandler.HandleError(error, "ArchPlus");
			}
			break;
		case $.sfKey.STOP:
            if  (ScenePlayer.isPlaying == true) {
				ScenePlayer.stop();
				SceneArchPlus.setHelpBar();
            }
            break;
	}
}
