/**
 * @author Samsung
 */
function SceneRadio(options) {
	this.options = options;
}

SceneRadio.currentLang=null;

SceneRadio.prototype.initialize = function () {
	Logger.write("SceneRadio.initialize()", "Radio");
	// 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
		SceneRadio.initData();
        SceneRadio.currentLang = AppContext.ClientSettings.Language;
        SceneRadio.loadRadioPanel();
		
		SceneRadio.setHelpBar();
		$("#lblRadioTitle").empty();
		$("#lblRadioTitle").append(Resources.getResources().LabelRadio.toLowerCase());
}

SceneRadio.initData = function () {
	SceneRadio.visibleStations = 12;
}

/*
Sets helpbar
*/
SceneRadio.setHelpBar = function(){
    if (ScenePlayer.isPlaying)
    {
		$('#keysRadio').sfKeyHelp({
			'red':Resources.getResources().LabelSettings,
			'green':Resources.getResources().Refresh,
			'blue':Resources.getResources().Player,
			'return':Resources.getResources().BackToMainMenu,
			'updown':'', 'leftright':Resources.getResources().MoveCursor,
			'enter':Resources.getResources().ListenRadio,
			'stop':Resources.getResources().Stop
		});                
    }
    else
    {
		$('#keysRadio').sfKeyHelp({
			'red':Resources.getResources().LabelSettings,
			'green':Resources.getResources().Refresh,
			'return':Resources.getResources().BackToMainMenu,
			'updown':'', 'leftright':Resources.getResources().MoveCursor,
			'enter':Resources.getResources().ListenRadio
		});                
    }
}

/*
Translates language-dependent parts of scene
*/
SceneRadio.translate = function () {
     if (SceneRadio.currentLang != AppContext.ClientSettings.Language)
     {
		$("#radioNoData").html(Resources.getResources().NoData);
		$("#lblRadioTitle").empty();
		$("#lblRadioTitle").append(Resources.getResources().LabelRadio.toLowerCase());
		SceneRadio.currentLang = AppContext.ClientSettings.Language;
		SceneRadio.focusRadio();
		SceneRadio.setHelpBar();
	}
}

/*
Active panel index
*/
SceneRadio.activePanel="radio";

/*
Hides image loading and makes visible panels
*/
SceneRadio.onLoadDataCompleted = function(){
	if (SceneRadio.stations.length > 0) {
		Logger.write("Showing stations", "Radio");
		$('#radioStations').css('visibility', 'visible');
		$('#radioStations').show();
		$('#panelRadioSort').css('visibility', 'visible'); 
		SceneRadio.focusRadio();
	} else {
		$('#radioStations').css('visibility', 'hidden');
		$('#panelRadioSort').css('visibility', 'hidden'); 
		$("#radioNoData").show();
	}
    SceneRadio.hideLoading();
    SceneRadio.dataLoaded = true;
}

/*
Shows loading image and  hides panels
*/
SceneRadio.showLoading = function () {
    SceneRadio.isLoading = true;
	if (AppContext.CurrentScene == "Radio") {
		Helpers.showLoading();
	}
    /*$('#radioStations').css('visibility', 'hidden');
    $('#panelRadioSort').css('visibility', 'hidden');  */
}

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

/*
Loads radio panel
*/
SceneRadio.loadRadioPanel = function(){    
    SceneRadio.dataLoaded = true;
	
    SceneRadio.showLoading();          
    SceneRadio.loadListRadio(); 
}

 /*
 Loads list of  radiostations by user
 */
SceneRadio.loadListRadio = function () {
	var errCallBack = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Radio", true, textStatus, jqXHR);     
	}
	var callBack = function (result) {
		try {
			$("#radioStations").ImageView("clear");
			SceneRadio.stations = result.items;
			SceneRadio.stations = Helpers.sortByField(SceneRadio.stations, "name", true);
			SceneRadio.channelPicker = new ArchProgramPicker(SceneRadio.stations, SceneRadio.channelSetCallback);
			$('#scrollRadioStations').css({'visibility': 'hidden'});
			if (result) {
				SceneRadio.bindRadio();
			}
			SceneRadio.onLoadDataCompleted();
		} catch (error) {
			ErrorHandler.HandleError(error, "Radio");  
		}
	}

	JsonServices.content.GetClientChannels(AppContext.user.sid, "Radio", null, null, callBack, errCallBack);
 }
 
 SceneRadio.bindRadio = function () {
	var pattern = AppContext.ImageUrlTemplate.replace("{1}", "10").replace("{2}", "1") + "&width=110";
	$("#radioStations").ImageView({
		elements: SceneRadio.stations,
		pageChangedCallback: SceneRadio.radioPageChanged,
		imageUrlPattern: pattern,
		patternFields: ["id"]
	});
	if (SceneRadio.visibleStations < SceneRadio.stations.length) {
		var pages = Math.ceil(SceneRadio.stations.length / SceneRadio.visibleStations);
		$('#scrollRadioStations').sfScroll({page: pages});
		$('#scrollRadioStations').css({'visibility': 'visible'});
	}
 }
 
  SceneRadio.channelSetCallback = function (index, successCallback) {
	$("#radioStations").ImageView("move", index);
	var radio = SceneRadio.stations[index];
	SceneRadio.playRadio(radio);
	successCallback();
 }
 
 SceneRadio.radioPageChanged = function (newPage) {
	$('#scrollRadioStations').sfScroll("move", newPage - 1);
 }

SceneRadio.focusRadio = function () {
	SceneRadio.activePanel = "radio";
	$("#radioStations").ImageView("focus");
}

/*
Handles move up
*/
SceneRadio.handleUp = function () {
	try {
		if (SceneRadio.activePanel == "radio") {
			$("#radioStations").ImageView("moveUp");
			SceneRadio.channelPicker.count = $("#radioStations").ImageView("getIndex");
		}
	} catch (error) {
		ErrorHandler.HandleError(error,"Radio");  
	}  
}
/*
Handles move down
makes radio panel active and blurs sort panel if it was active
*/
SceneRadio.handleDown = function () {
	try {
		if (SceneRadio.activePanel == "radio") {
			$("#radioStations").ImageView("moveDown");
			SceneRadio.channelPicker.count = $("#radioStations").ImageView("getIndex");
		}
	} catch (error) {
		ErrorHandler.HandleError(error, "Radio");  
	}         
}

SceneRadio.handleLeft = function () {
	try {
		if (SceneRadio.activePanel == "radio") {
			$("#radioStations").ImageView("moveLeft");
			SceneRadio.channelPicker.count = $("#radioStations").ImageView("getIndex");
		}
	} catch (error) {
		ErrorHandler.HandleError(error,"Radio");  
	}
}

SceneRadio.handleRight = function () {
	try {
		if (SceneRadio.activePanel == "radio") {
			$("#radioStations").ImageView("moveRight");
			SceneRadio.channelPicker.count = $("#radioStations").ImageView("getIndex");
		}
	} catch (error) {
		ErrorHandler.HandleError(error,"Radio");
	}
}

SceneRadio.playRadio = function (station) {
	var callback = function (result) {
		try {
			$.sfScene.hide(AppContext.CurrentScene);
			$.sfScene.show('Player');
			var radio = {
				url: result.URL,
				playlist: result.Playlist,
				contentType: "Radio"
			};
			radio.name = station.name;
			radio.imageUrl = AppContext.ImageUrlTemplate.replace("{0}", station.id).replace("{1}", "10").replace("{2}", "1") + "&width=132";
			ScenePlayer.setContent(radio, "Radio");
			SceneRadio.channelPicker.count = $("#radioStations").ImageView("getIndex");
			$.sfScene.focus('Player');
		} catch (error) {
			ErrorHandler.HandleError(error, "Radio");  
		}
	 }
	var errCallback = function (jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Radio", true, textStatus, jqXHR);
	}
	
	JsonServices.media.GetClientStreamUri(
		AppContext.user.sid, "Radio", station.id,
		AppContext.ClientSettings.bAId, AppContext.ClientSettings.cdnId,
		AppContext.ClientSettings.qualityPreset, AppContext.ClientSettings.shiftTimeZoneName,
		callback, errCallback
	);
}

/*
Handles pressing enter 
*/
SceneRadio.handleEnter = function () {
    try {
        if (SceneRadio.activePanel === "radio") {
			var station = SceneRadio.stations[$("#radioStations").ImageView("getIndex")];
			
			SceneRadio.playRadio(station);
        }
     } catch (error) {
        ErrorHandler.HandleError(error, "Radio");  
     }   
}
/*
Returns to main menu
*/
SceneRadio.backToMainMenu = function(){
	try {
		$.sfScene.hide('Radio');
		SceneMainMenu.show();
	} catch (error) {
		ErrorHandler.HandleError(error,"Radio");
	}
}

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

SceneRadio.refresh = function () {      
    try {
		SceneRadio.loadRadioPanel();
    } catch (error) {
		ErrorHandler.HandleError(error, "Radio");
    }    
}


SceneRadio.prototype.handleShow = function () {
	Logger.write("SceneRadio.handleShow()", "Radio");
	// this function will be called when the scene manager show this scene 
    SceneRadio.translate();
}

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

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

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

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