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

}

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

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

SceneSearchResult.translate = function () {
	if (SceneSearchResult.currentLang != AppContext.ClientSettings.Language) {
		$('#lblSearchFor').sfLabel({text : Resources.getResources().ToSearch});
		$('#lblSearchResult').sfLabel({text : Resources.getResources().SearchResults});
		$("#searchResultNoData").html(Resources.getResources().NoData);
		var sortingOrders = [ new PanelElement("movie_date", Resources.getResources().Date), new PanelElement("name", Resources.getResources().Name)];
		this.sortingPanel.loadData(sortingOrders);
		//this.sortingPanel.invokeSelectedChangedCallback();
		SceneSearchResult.currentLang = AppContext.ClientSettings.Language;
	}
}

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

SceneSearchResult.onSortingOrderChanged = function (orderId) {
	if (SceneSearchResult.programs && SceneSearchResult.programs.length > 0) {
		var regex = /^\#divSearchedSortBy(\w+)/;
		var result = regex.exec(orderId);
		SceneSearchResult.sortBy = result[1];
		if (SceneSearchResult.sortBy == "_") {
			SceneSearchResult.sortBy = null;
		} else {
			SceneSearchResult.sortBy += " DESC";
		}
		
		if (SceneSearchResult.pager.paging.totalItems == SceneSearchResult.programs.length) {
			SceneSearchResult.showLoading();
			var ascending, fieldName, subFieldName;
			if (result[1] == "name") {
				fieldName = "name";
				ascending = true;
			} else {
				fieldName = "recentAirTime";
				subFieldName = "startTime";
				ascending = false;
			}
			SceneSearchResult.programs = Helpers.sortByField(SceneSearchResult.programs, fieldName, ascending, subFieldName);
			SceneSearchResult.bindPrograms();
			SceneSearchResult.hideLoading();
		} else {
			SceneSearchResult.pager.setPageNumber(1, 0);
		}
	}
}

SceneSearchResult.onResultsLoaded = function (result) {
	SceneSearchResult.programs = result.items;
	if (!result.paging.totalItems) {
		result.paging.totalItems = result.items.length;
		result.paging.totalPages = 1;
	}
	SceneSearchResult.pager = new ListPager(result.paging, "#lbSearch", SceneSearchResult.visiblePrograms, SceneSearchResult.onPageChanging, SceneSearchResult.onPagerOutOfBounds);
	
	SceneSearchResult.bindPrograms();
	
	if (SceneSearchResult.programs.length > 0) {
		SceneSearchResult.focusProgramsPanel();
	} else {
		SceneSearchResult.focusSortPanel();
	}
	
	SceneSearchResult.hideLoading();
}

SceneSearchResult.onPageChanging = function (onPage, pageNumber, pageChangedCallback) {
	Logger.write("Changing page, onPage: " + onPage + ", pageNumber: " + pageNumber, "SearchResult", true);
	SceneSearchResult.showLoading();
	var completeCallback = function (result) {
		SceneSearchResult.programs = result.items;
		
		SceneSearchResult.bindPrograms();
		pageChangedCallback(true);
		Logger.write("New scroll page number: " + SceneSearchResult.pager.scroll.pageNumber, "SearchResult", true);
		$('#scrollSearch').sfScroll('move', SceneSearchResult.pager.scroll.pageNumber);
		SceneSearchResult.showDescription(SceneSearchResult.programs[SceneSearchResult.pager.paging.index]);
		SceneSearchResult.hideLoading();
	};
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "SearchResult", true, textStatus);
		pageChangedCallback(false);
	};
	
	JsonServices.content.GetClientRelatedProgramGuide(
		AppContext.user.sid, SceneSearchResult.contentType, "children", 
		SceneSearchResult.item.id, SceneSearchResult.sortBy, onPage, pageNumber, 
		completeCallback, errCallback
	);
}

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

SceneSearchResult.loadResults = function (item, searchWord, contentType) {
	this.contentType = contentType;
	this.sender = "SearchChannels";
	this.item = item;
	this.searchWord = searchWord;
	Logger.write("SceneSearchResult.loadResults("+searchWord+")", "SceneSearchResult");
	this.dataLoaded = false;
	this.offset = AppContext.getNaEstUtcOffset();
	SceneSearchResult.sortingPanel.setIndex(1);
	SceneSearchResult.sortBy = null;
	this.showLoading();
	$("#searchResultNoData").hide();
	
	var errorCallback = function (jqXHR, textStatus, error) {
		SceneSearchResult.hideLoading();
		ErrorHandler.HandleError(error, "SearchResult", true, textStatus); 
	};
	
	$('#lblSearchFor').sfLabel({text: Resources.getResources().ToSearch+" '"+searchWord+"'"});
	
	this.hideDescription();
	$('#lbSearch').css('visibility', 'hidden');
	$('#scrollSearch').css('visibility', 'hidden');
	
	JsonServices.content.GetClientRelatedProgramGuide(
		AppContext.user.sid, SceneSearchResult.contentType, "children", 
		SceneSearchResult.item.id, this.sortBy, SceneSearchResult.onPage, 1, 
		SceneSearchResult.onResultsLoaded, errorCallback
	);
}

SceneSearchResult.getProgramHtml = function (program) {
	var result = "";
	var isDvr = SceneSearchChannels.contentType == "DVR";
	var realDate = program.recentAirTime.startTime;
	realDate.setHours(realDate.getHours() + SceneSearchResult.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 name = program.name.length > 43 ? program.name.substring(0, 40) + "..." : program.name;
	result += "<span class='" + titleClass + "'>" + name + "</span>";

	return result;
}

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

		if (len > this.visiblePrograms) {
			$('#scrollSearch').css('visibility', 'visible');
		} else {
			$('#scrollSearch').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;
		$('#lbSearch').sfList({data: lbElems, index: '0', itemsPerPage: perPage});
		$('#lbSearch').sfList('move', 0);
		$('#lbSearch').sfList('blur');
		var pagesNum = SceneSearchResult.pager.scroll.getTotalPages();
		Logger.write("There's " + pagesNum + " pages", "SearchResult", true);
		$('#scrollSearch').sfScroll({page: pagesNum});
	} else {
		Logger.write("There's no programs", "SearchResult", true);
		$('#scrollSearch').css('visibility', 'hidden');
		$('#lbSearch').sfList('clear');
		$('#lbSearch').css('visibility', 'hidden');
		$("#searchResultNoData").show();
	}
}

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

SceneSearchResult.focusProgramsPanel = function () {
    this.sortingPanel.blurPanel();
    this.activePanel = "programsPanel";
    $('#lbSearch').sfList('focus');
	
	this.showDescription(this.programs[$('#lbSearch').sfList('getIndex')]);
}

SceneSearchResult.showDescription = function (program) {
	setTimeout(function () {
		if (program) {
			var description = "";
			if (program.description && program.description.length > 0) {
				description = program.description.length > 160 
					? program.description.substring(0, 160) + "..." 
					: program.description;
			} else if (SceneSearchResult.item.description) {
				description = SceneSearchResult.item.description.length > 160 
					? SceneSearchResult.item.description.substring(0, 160) + "..." 
					: SceneSearchResult.item.description;
			}
			$('#lblSearchDescription').sfLabel({text: description});
			if (program.imageCount > 0) {
				var isDvr = program.contentType == JsonServices.ContentType.DVR;
				var imageUrl = AppContext.ImageUrlTemplate.replace("{0}", program.id).replace("{1}", isDvr ? 28 : 16).replace("{2}", 1) + "&width=152";
				Logger.write("Image: " + imageUrl, "SearchResult", true);
				$("#SceneSearchResult #lblSearchDescription").removeClass("noImage");
				$("#imgSearch").sfImage({src: imageUrl});
				$("#SceneSearchResult .programImage").show();
				$("#imgSearch").css({'visibility': 'visible'});
			} else {
				$("#SceneSearchResult .programImage").hide();
				$("#imgSearch").css({'visibility': 'hidden'});
				$("#SceneSearchResult #lblSearchDescription").addClass("noImage");
			}
		}
	}, 1);
}

SceneSearchResult.hideDescription = function () {
	$('#lblSearchDescription').sfLabel({text: ''});                    
	$("#imgSearch").css({'visibility':'hidden'});
	$("#imgSearch").sfImage({src:""});
}

SceneSearchResult.openPlayer = function () {
	var itemIndex = $('#lbSearch').sfList('getIndex');
	var item = SceneSearchResult.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 = SceneSearchResult.contentType;
			Logger.write("Channel ID: " + item.recentAirTime.channelID, "SearchResult", true);
			var ar = video.contentType == "ArcPlus"
				? SceneArchPlus.getChannelAr(item.recentAirTime.channelID)
				: SceneArchTv.getChannelAr(item.recentAirTime.channelID);
			if (ar) {
				video.ar = ar;
			}
			ScenePlayer.setContent(video, "SearchResult");
			$.sfScene.focus('Player');
		} catch (error) {
			ErrorHandler.HandleError(error, "SearchResult");
		}
    }
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "SearchResult", true, textStatus);
	}
	
    try {
		JsonServices.media.GetClientStreamUri(
			AppContext.user.sid, SceneSearchResult.contentType, item.id,
			AppContext.ClientSettings.bAId, AppContext.ClientSettings.cdnId,
			AppContext.ClientSettings.qualityPreset, AppContext.ClientSettings.shiftTimeZoneName,
			callback, errCallback
		);
	} catch (error) {
        ErrorHandler.HandleError(error, "SearchResult");  
	}
}

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

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

SceneSearchResult.show = function () {
    $.sfScene.show('SearchResult');
    $.sfScene.focus('SearchResult');
    SceneSearchResult.setHelpbar();
}

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

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

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

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

SceneSearchResult.handleUp = function () {
	if (SceneSearchResult.isLoading) {
		return;
	}
    try {
		if (this.activePanel.indexOf("programsPanel") != -1) {
			var idx = this.pager.paging.index;
			this.pager.prev();
			if (idx > 0) {
				this.showDescription(this.programs[this.pager.paging.index]);
			}
			$('#scrollSearch').sfScroll('move', this.pager.scroll.pageNumber);
		}
    } catch (error) {
          ErrorHandler.HandleError(error, "SearchResult");  
    }  
}

SceneSearchResult.handleDown = function () {
	if (SceneSearchResult.isLoading) {
		return;
	}
    try {
		if (this.activePanel.indexOf("programsPanel") != -1) {
			var idx = this.pager.paging.index;
			this.pager.next();
			if (idx < (this.onPage - 1)) {
				this.showDescription(this.programs[this.pager.paging.index]);
			} else {
				this.hideDescription();
			}
			$('#scrollSearch').sfScroll('move', this.pager.scroll.pageNumber);
		} else if (this.programs && this.programs.length > 0) {
			this.focusProgramsPanel();
		}
    } catch (error) {
		ErrorHandler.HandleError(error, "SearchResult");
    }  
}

SceneSearchResult.handleEnter = function () {
	var idx = $('#lbSearch').sfList('getIndex');
	var program = SceneSearchResult.programs[idx];
	var hasSeries = program.isContainer && program.episodeNum === 1 || program.episodeNum > 1;
	/*if (hasSeries) {
		$.sfScene.hide(AppContext.CurrentScene);
		$.sfScene.show('ProgramEpisodes');
		$.sfScene.focus('ProgramEpisodes');
		SceneProgramEpisodes.loadEpisodes(program.id, "SearchResult");
	} else {*/
		SceneSearchResult.openPlayer();
	//}
}

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

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

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

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

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

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