function SceneSearchChannels() {
	

}

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

SceneSearchChannels.initData = function () {
	this.visiblePrograms = 8;
	this.onPage = this.visiblePrograms * 5;
	this.sortBy = null;
	
	this.sortingPanel = new SlidingPanel(120, 80, [], "SearchedChannelsSortBy", this.onSortingOrderChanged, 170, orientations.horizontal, false, 1000, null, 1000); 
    $('#panelChannelsSort').append(this.sortingPanel.panel);
}

SceneSearchChannels.translate = function () {
	if (SceneSearchChannels.currentLang != AppContext.ClientSettings.Language) {
		$('#lblSearchChannelsFor').sfLabel({text : Resources.getResources().ToSearch});
		$('#lblSearchChannels').sfLabel({text : Resources.getResources().SearchResults});
		$("#searchChannelsNoData").html(Resources.getResources().NoData);
		var sortingOrders = [ 
			new PanelElement("movie_date", Resources.getResources().Date), 
			new PanelElement("studio", Resources.getResources().Channel), 
			new PanelElement("_", Resources.getResources().Name), 
			new PanelElement("rating", Resources.getResources().Rating)
		];                  
		this.sortingPanel.loadData(sortingOrders);
		SceneSearchChannels.currentLang = AppContext.ClientSettings.Language;
	}
}

SceneSearchChannels.setHelpbar = function () {
	if (ScenePlayer.isPlaying) {
         $('#keysSearchChannels').sfKeyHelp({
			 'red':Resources.getResources().LabelSettings,
			 '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 {
         $('#keysSearchChannels').sfKeyHelp({
			 'red':Resources.getResources().LabelSettings,
			 'yellow':Resources.getResources().Info,
			 'updown':'', 'leftright':Resources.getResources().MoveCursor,
			 'enter':Resources.getResources().Select,
			 'return':Resources.getResources().BackToMainMenu
         });
     }
}


SceneSearchChannels.onSortingOrderChanged = function (orderId) {
	if (SceneSearchChannels.dataLoaded && SceneSearchChannels.programs && SceneSearchChannels.programs.length > 0) {
		var regex = /^\#divSearchedChannelsSortBy(\w+)/;
		var result = regex.exec(orderId);
		SceneSearchChannels.sortBy = result[1];
		if (SceneSearchChannels.sortBy == "_") {
			SceneSearchChannels.sortBy = null;
		} else {
			if (SceneSearchChannels.sortBy == "studio") {
				SceneSearchChannels.sortBy += " ASC";
			} else {
				SceneSearchChannels.sortBy += " DESC";
			}
		}
		Logger.write("sortBy: " + SceneSearchChannels.sortBy, "SearchChannels", true);
		if (SceneSearchChannels.pager.paging.totalItems == SceneSearchChannels.programs.length) {
			SceneSearchChannels.showLoading();
			var ascending, fieldName, subFieldName;
			if (result[1] == "_") {
				fieldName = "name";
				ascending = true;
			} else if (result[1] == "studio") {
				fieldName = "recentAirTime";
				subFieldName = "channelID";
				ascending = true;
			} else if (result[1] == "movie_date") {
				fieldName = "recentAirTime";
				subFieldName = "startTime";
				ascending = false;
			} else {
				fieldName = "rating";
				ascending = false;
			}
			SceneSearchChannels.programs = Helpers.sortByField(SceneSearchChannels.programs, fieldName, ascending, subFieldName);
			SceneSearchChannels.bindPrograms();
			SceneSearchChannels.hideLoading();
		} else {
			SceneSearchChannels.pager.setPageNumber(1, 0);
		}
	}
}

SceneSearchChannels.onResultsLoaded = function (result) {
	SceneSearchChannels.programs = result.items;
	SceneSearchChannels.pager = new ListPager(result.paging, "#lbSearchChannels", SceneSearchChannels.visiblePrograms, SceneSearchChannels.onPageChanging, SceneSearchChannels.onPagerOutOfBounds);
	
	SceneSearchChannels.bindPrograms();	
	
	if (SceneSearchChannels.programs.length > 0) {
		SceneSearchChannels.focusProgramsPanel();
	} else {
		SceneSearchChannels.focusSortPanel();
	}
	
	SceneSearchChannels.hideLoading();
	
	SceneSearchChannels.dataLoaded = true;
	Logger.write("Total items: " + SceneSearchChannels.pager.paging.totalItems, "SearchChannels", true);
	Logger.write("Programs loaded: " + SceneSearchChannels.programs.length, "SearchChannels", true);
}

SceneSearchChannels.onPageChanging = function (onPage, pageNumber, pageChangedCallback) {
	Logger.write("Changing page, onPage: " + onPage + ", pageNumber: " + pageNumber, "SearchChannels", true);
	SceneSearchChannels.showLoading();
	var completeCallback = function (result) {
		SceneSearchChannels.programs = result.items;
		
		SceneSearchChannels.bindPrograms();
		pageChangedCallback(true);
		Logger.write("New scroll page number: " + SceneSearchChannels.pager.scroll.pageNumber, "SearchChannels", true);
		$('#scrollSearchChannels').sfScroll('move', SceneSearchChannels.pager.scroll.pageNumber);
		SceneSearchChannels.hideLoading();
	};
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "SearchChannels", true, textStatus);
		pageChangedCallback(false);
	};
	
	JsonServices.content.GetClientProgramGuide(
		AppContext.user.sid, SceneSearchChannels.contentType, "SearchByKeywordInChannels", 0, null, null, null, 
		SceneSearchChannels.searchWord, SceneSearchChannels.sortBy, false, onPage, pageNumber,
		AppContext.ClientSettings.shiftTimeZoneName, AppContext.ClientSettings.timeZoneName,
		completeCallback, errCallback
	);
}

SceneSearchChannels.onPagerOutOfBounds = function (num) {
	if (num < 0) {
		SceneSearchChannels.focusSortPanel();
	}
}

SceneSearchChannels.loadResults = function (searchWord, sender) {
	this.dataLoaded = false;
	this.contentType = sender == "ArchPlus" ? "ArcPlus" : "DVR";
	this.sender = sender;
	this.searchWord = searchWord;
	this.offset = AppContext.getNaEstUtcOffset();
	Logger.write("SceneSearchChannels.loadResults("+searchWord+")", "SceneSearchChannels");
	SceneSearchChannels.sortingPanel.setIndex(2);
	SceneSearchChannels.sortingPanel.stopTimer();
	SceneSearchChannels.sortBy = null;
	this.showLoading();
	$("#searchChannelsNoData").hide();
	
	var errorCallback = function (jqXHR, textStatus, error) {
		SceneSearchChannels.hideLoading();
		ErrorHandler.HandleError(error, "SearchChannels", true, textStatus); 
	};
	
	$('#lblSearchChannelsFor').sfLabel({text: Resources.getResources().ToSearch+" '"+searchWord+"'"});
	
	$('#lbSearchChannels').css('visibility', 'hidden');
	$('#scrollSearchChannels').css('visibility', 'hidden');
	
	Logger.write("OnPage: " + SceneSearchChannels.onPage, "SearchChannels", true);
	JsonServices.content.GetClientProgramGuide(
		AppContext.user.sid, this.contentType, "SearchByKeywordInChannels", 0, null, null, null, 
		searchWord, SceneSearchChannels.sortBy, false, SceneSearchChannels.onPage, 1,
		AppContext.ClientSettings.shiftTimeZoneName, AppContext.ClientSettings.timeZoneName,
		SceneSearchChannels.onResultsLoaded, errorCallback
	);
}

SceneSearchChannels.getProgramHtml = function (program) {
	var result = "";
	var isDvr = SceneSearchChannels.contentType == "DVR";
	var realDate = program.recentAirTime.startTime;
	realDate.setHours(realDate.getHours() + SceneSearchChannels.offset - AppContext.deviceOffset/60);
	var date = isDvr 
		? DateHelper.getArchDate(realDate) 
		: DateHelper.getArchPlusDate(realDate);
	var dateClass = "programDate";
	if (!isDvr) {
		dateClass += " arcplus";
	}
	result += "<span class='" + dateClass + "'>" + date + "</span>";
	var url = AppContext.ImageUrlTemplate.replace("{0}", program.recentAirTime.channelID)
		.replace("{1}", isDvr ? 4 : 25)
		.replace("{2}", 1) + "&width=28";
	result += "<div class='logoBack'><img  width='28' height='28' src='" + url + "' /></div>";
	result += "<span class='programTime'>" + realDate.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 > 43 ? program.name.substring(0, 40) + "..." : program.name;
	result += "<span class='" + titleClass + "'>" + name + "</span>";

	return result;
}

SceneSearchChannels.bindPrograms = function () {
	var len = this.programs.length;
	if (len > 0) {
		Logger.write("There's " + len + " programs", "SearchChannels", true);
		$('#lbSearchChannels').css('visibility', 'visible');

		if (SceneSearchChannels.pager.paging.totalItems > this.visiblePrograms) {
			$('#scrollSearchChannels').css('visibility', 'visible');
		} else {
			$('#scrollSearchChannels').css('visibility', 'hidden');
		}
		
		var lbElems = [];
		for (var i = 0; i < len; i++) {
			lbElems.push(this.getProgramHtml(this.programs[i]));
		}
		
		var perPage = len < this.visiblePrograms ? len : this.visiblePrograms;
		$('#lbSearchChannels').sfList({data: lbElems, index: '0', itemsPerPage: perPage});
		$('#lbSearchChannels').sfList('move', 0);
		$('#lbSearchChannels').sfList('blur');
		var pagesNum = SceneSearchChannels.pager.scroll.getTotalPages();
		Logger.write("There's " + pagesNum + " pages", "SearchChannels", true);
		$('#scrollSearchChannels').sfScroll({page: pagesNum});
	} else {
		Logger.write("There's no programs", "SearchChannels", true);
		$('#scrollSearchChannels').css('visibility', 'hidden');
		$('#lbSearchChannels').sfList('clear');
		$('#lbSearchChannels').css('visibility', 'hidden');
		$("#searchChannelsNoData").show();
	}
}

SceneSearchChannels.focusSortPanel = function () {
    $('#lbSearchChannels').sfList('blur');
    this.activePanel = "sortingPanel";
    this[this.activePanel].focusPanel();
}

SceneSearchChannels.focusProgramsPanel = function () {
    this.sortingPanel.blurPanel();
    this.activePanel = "programsPanel";
    $('#lbSearchChannels').sfList('focus');
}

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

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

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

SceneSearchChannels.show = function () {
    $.sfScene.show('SearchChannels');
    $.sfScene.focus('SearchChannels');
    SceneSearchChannels.setHelpbar();
}

SceneSearchChannels.showLoading = function () {
    SceneSearchChannels.isLoading = true;
	if (AppContext.CurrentScene == "SearchChannels") {
		Helpers.showLoading();
	}
}

SceneSearchChannels.hideLoading = function () {
    SceneSearchChannels.isLoading = false;
	if (AppContext.CurrentScene == "SearchChannels") {
		Helpers.hideLoading();
	}
}

SceneSearchChannels.handleLeft = function () {
	if (SceneSearchChannels.isLoading) {
		return;
	}
    try {
		if (this.activePanel.indexOf("sortingPanel") != -1) {
			this.sortingPanel.focusPrev();
		}
     } catch (error) {
		ErrorHandler.HandleError(error, "SearchChannels");  
    }  
}

SceneSearchChannels.handleRight = function () {
	if (SceneSearchChannels.isLoading) {
		return;
	}
    try {
		if (this.activePanel.indexOf("sortingPanel") != -1) {
			this.sortingPanel.focusNext();
		}
    } catch (error) {
		ErrorHandler.HandleError(error, "SearchChannels");  
    }  
}

SceneSearchChannels.handleUp = function () {
	if (SceneSearchChannels.isLoading) {
		return;
	}
    try {
		if (this.activePanel.indexOf("programsPanel") != -1) {
			var idx = this.pager.paging.index;
			this.pager.prev();
			$('#scrollSearchChannels').sfScroll('move', this.pager.scroll.pageNumber);
		}
    } catch (error) {
          ErrorHandler.HandleError(error, "SearchChannels");  
    }  
}

SceneSearchChannels.handleDown = function () {
	if (SceneSearchChannels.isLoading) {
		return;
	}
    try {
		if (this.activePanel.indexOf("programsPanel") != -1) {
			var idx = this.pager.paging.index;
			this.pager.next();
			$('#scrollSearchChannels').sfScroll('move', this.pager.scroll.pageNumber);
		} else if (this.programs && this.programs.length > 0) {
			this.focusProgramsPanel();
		}
    } catch (error) {
		ErrorHandler.HandleError(error, "SearchChannels");
    }  
}

SceneSearchChannels.handleEnter = function () {
	var idx = $('#lbSearchChannels').sfList('getIndex');
	var program = SceneSearchChannels.programs[idx];
	var hasSeries = program.isContainer && program.episodeNum === 1 || program.episodeNum > 1;
	if (hasSeries) {
		$.sfScene.hide('SearchChannels');
		SceneSearchResult.show();
		SceneSearchResult.loadResults(program, SceneSearchChannels.searchWord, SceneSearchChannels.contentType);
	} else {
		SceneSearchChannels.openPlayer();
	}
}

SceneSearchChannels.handleYellow = function () {
	if (SceneSearchChannels.isLoading) {
		return;
	}
	if (this.activePanel == "programsPanel") {
		var itemIndex = $('#lbSearchChannels').sfList('getIndex');
		var item = SceneSearchChannels.programs[itemIndex];
		
		ScenePopUp.setWindow("SearchChannels", item);
		$.sfScene.show('PopUp');
		$.sfScene.focus('PopUp');
	}
}

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

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

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

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

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