/**
 * @author EvgeniyV
 */
function SceneSettings(options) {
	this.options = options;
}
    SceneSettings.perPage = 7;
    SceneSettings.listBoxes = [];
    SceneSettings.scrolls = [];
    SceneSettings.currentListBoxId = 0;
	
	var ime_txtTotalBuffer = null;
	var ime_txtInitialBuffer = null;
	var ime_txtPendingBuffer = null;
    
/*
Function that runs when client data loading complited
*/
SceneSettings.onLoadDataCompleted = function() {
    $('#settingsPanel').css('visibility', 'visible');
	$('#loadingObject').sfLoading('hide');
    SceneSettings.showSettings();
 }
 
 /*
 Shows loading image
 */
 SceneSettings.showLoading = function() {
    SceneSettings.hideSettings();
    $('#loadingObject').sfLoading();
	$('#loadingObject').sfLoading('show');
    $('#settingsPanel').css('visibility', 'hidden');
    $('.setting').css('visibility', 'hidden');
}

/*
    Translates scene to setted language
 */
 SceneSettings.translate = function(){
    if (SceneSettings.currentLang != AppContext.ClientSettings.Language)
    {
        SceneSettings.currentLang = AppContext.ClientSettings.Language;
        SceneSettings.setArray();
        SceneSettings.loadPanelData();
        SceneSettings.loadSetBtns();
        SceneSettings.loadDescriptions();
        SceneSettings.showSettings();
        SceneSettings.setHelpBar();
		$("#updates .button").sfButton({text: Resources.getResources().SettingsManual});
		$("#messager #noMessages").html(Resources.getResources().SettingsMessagesNoMessages);
        
		if (SceneSettings.focusedPanel != "settingsNames")
		{
			$("#btnLogout").sfButton("focus");
		}
    }
 }
 
 SceneSettings.refresh = function () {
	SceneSettings.focusedPanel = "settingsNames";
	SceneSettings.setArray();
	SceneSettings.loadPanelData();
	SceneSettings.loadSetBtns();
	SceneSettings.loadDescriptions();
	SceneSettings.showSettings();
	SceneSettings.settingsPanel.focusPanel();
 }

/* 
Stores index of focused button
*/
SceneSettings.focusedBtnIndex=0;
SceneSettings.loadPanelData = function(){
    SceneSettings.tSorting = [Resources.getResources().Account+">", Resources.getResources().Language+">", Resources.getResources().TimeZone+">", Resources.getResources().StreamZone+">", Resources.getResources().SettingsStream+">", Resources.getResources().SettingsBuffers + ">", Resources.getResources().SettingsMessager+">", Resources.getResources().About+">"];
    SceneSettings.sorting = ["account", "language", "timeZone", "streamZone", "stream", "buffers", "messager", "about"];
	if (Updater.updateAvailable) {
		SceneSettings.tSorting.push(Resources.getResources().SettingsUpdates+">");
		SceneSettings.sorting.push("updates");
	}
    var elements = [];
    for (var i=0; i<SceneSettings.sorting.length; i++)
    {
		elements[i] = new PanelElement(SceneSettings.sorting[i], SceneSettings.tSorting[i]);
    }
    SceneSettings.settingsPanel.loadData(elements);
    SceneSettings.settingsPanel.index =  SceneSettings.currentListBoxId;
}
/*
Loads settings listbox 
*/
SceneSettings.loadSettingsPanel = function() {
    SceneSettings.settingsPanel = new SlidingPanel(0, 0, [], "settingItem", function(){}, 40, orientations.vertical, false, 400, "categoriesElement");
    $('#settingsSlidingPanel').append(SceneSettings.settingsPanel.panel);
    SceneSettings.loadPanelData(); 
    //$("#settingsPanel").sfList('blur');
}
/*
Gets clients settings from web service
*/       
SceneSettings.getClientSettings = function () {
	Resources.getResources(AppContext.ClientSettings.Language.cultureInfo);

	SceneSettings.setArray();
	SceneSettings.loadPanelData();
	SceneSettings.loadSetBtns();
	SceneSettings.loadDescriptions();
	SceneSettings.setHelpBar();
 }
/*
Sets arrays of buttons, pop up windows and pop up window buttons
*/
SceneSettings.setArray = function () { 
    var timeZoneElements=[];
    for (var i = 0; i < AppContext.TimeZones.length; i++) {
		timeZoneElements[i] = AppContext.TimeZones[i].fullName
    }
    
    var streamZoneElements=[];
    for (var i = 0; i < AppContext.StreamZones.length; i++) {
		streamZoneElements[i] = AppContext.StreamZones[i].userName;
    }
    
    var languageElements = [];
    for (var i = 0; i < AppContext.Languages.length; i++) {
		languageElements[i] = AppContext.Languages[i].displayName;
    }
    
    var langBtns = new Array(new Setting(languageElements));
    var timeZoneBtns = new Array(new Setting(timeZoneElements));
    var StreamZoneBtns = new Array(new Setting(streamZoneElements));
	var streamQualityBtns = [new Setting([Resources.getResources().SQ, Resources.getResources().HQ], ["SQ", "HQ"])];
    
    SceneSettings.settingArray = new Array(
		new SettingItem('account', [], SceneSettings.loadAccount),
		new SettingItem('language', langBtns, SceneSettings.loadLanguage, SceneSettings.getCurrentLanguage),
		new SettingItem('timeZone',timeZoneBtns, SceneSettings.loadTimeZone, SceneSettings.getCurrentTimeZone),
		new SettingItem('streamZone', StreamZoneBtns, SceneSettings.loadStreamZone, SceneSettings.getCurrentStreamZone),
		new SettingItem('stream', streamQualityBtns, SceneSettings.loadStream, SceneSettings.getCurrentStreamQuality),
		new SettingItem('buffers', [], SceneSettings.loadBuffers),
		new SettingItem('messager', [], SceneSettings.loadMessages),
		new SettingItem('about', [], SceneSettings.loadAbout)
	);
	
	if (Updater.updateAvailable) {
		SceneSettings.settingArray.push(new SettingItem('updates', [], SceneSettings.loadUpdates));
	}
}

/*
Loads setting's descriptions
*/
SceneSettings.loadDescriptions = function() {
    $("#lblSettingsTitle").empty();
    $("#lblSettingsTitle").append(Resources.getResources().LabelSettings.toLowerCase());
    for(var i = 0; i < SceneSettings.settingArray.length; i++)
    {
		if(SceneSettings.settingArray[i].cbLoad != null)
		{
			SceneSettings.settingArray[i].cbLoad();
		}
    }    
}

/*
Load settings buttons
*/
SceneSettings.loadSetBtns = function () {
	for (var i = 0; i < SceneSettings.settingArray.length; i++) {
		$("#"+SceneSettings.settingArray[i].name+"> .btns").empty();
		if (SceneSettings.settingArray[i].btnArray.length > 0) {
			var length = SceneSettings.settingArray[i].btnArray[0].lbArray.length;
			var perPage = length < SceneSettings.perPage ? length : SceneSettings.perPage;
			$("#"+SceneSettings.settingArray[i].name+"> .btns").sfList({data: SceneSettings.settingArray[i].btnArray[0].lbArray, index: '0', itemsPerPage: perPage });    
			SceneSettings.listBoxes[i]="#"+SceneSettings.settingArray[i].name+" > .btns";
			$(SceneSettings.listBoxes[i]).sfList('blur');
			SceneSettings.scrolls[i] = "#"+SceneSettings.settingArray[i].name+" > .scroll";
			var pagesNum = Math.ceil(length / perPage);
			if (pagesNum > 1) {
				$(SceneSettings.scrolls[i]).sfScroll({page: pagesNum});
				$(SceneSettings.scrolls[i]).css({'height':(40*perPage).toString()+"px"});
			} else {
				$(SceneSettings.scrolls[i]).css({'visibility':'hidden'});
			}
		}
	}
}

/*
Gets current time zone
*/
SceneSettings.getCurrentTimeZone = function () {
	Logger.write("SceneSettings.getCurrentTimeZone()", "Settings");
	for (var i = 0; i < AppContext.TimeZones.length; i++) {
		if (AppContext.TimeZones[i].id == AppContext.ClientSettings.timeZoneName) {
			return  i;//AppContext.TimeZones[i].name;
		}
	}
}

/*
Gets time zone
*/
SceneSettings.getTimeZone = function(zone) {
	for(var i = 0; i < AppContext.TimeZones.length;i++)
	{
		if(AppContext.TimeZones[i].id.toString() == zone)
		{
			return  AppContext.TimeZones[i];
		}
	}
}

/*
Gets stream zone
*/
SceneSettings.getStreamZone = function(zone) {
	for(var i=0;i<AppContext.StreamZones.length;i++)
	{
		if(AppContext.StreamZones[i].id.toString() == zone)
		{
			return  AppContext.StreamZones[i];
		}
	}
}

/*
Gets current stream zone
*/
SceneSettings.getCurrentStreamZone = function () {
	Logger.write("SceneSettings.getCurrentStreamZone()", "Settings");
    for (var i = 0; i < AppContext.StreamZones.length; i++) {
		if (AppContext.StreamZones[i].id == AppContext.ClientSettings.shiftTimeZoneName) {
			return i;
		}
    }
}

/*
Gets current language
*/
SceneSettings.getCurrentLanguage = function () {
	Logger.write("Current language: " + AppContext.ClientSettings.Language.toSource(), "Settings", true);
    for (var i = 0; i < AppContext.Languages.length; i++) {
		if (AppContext.Languages[i].id == AppContext.ClientSettings.Language.id) {
			return i;//AppContext.Languages[i].name;
		}
    }
}

SceneSettings.getCurrentStreamQuality = function () {
	for (var i = 0; i < AppContext.StreamQualityPresets.length; i++) {
		if (AppContext.StreamQualityPresets[i] === AppContext.ClientSettings.qualityPreset) {
			return i;
		}
	}
}

/*
Clears user data
*/
SceneSettings.logout = function () {
	var callback = function () {
		if (ScenePlayer.isPlaying == true) {
			ScenePlayer.stop();
			SceneSettings.setHelpBar();
		}
		AppContext.user.login = "";
		AppContext.user.password = "";
		for (scene in ErrorHandler.NeedToRefresh) {
			ErrorHandler.NeedToRefresh[scene] = true;
		}
		$.sfScene.hide('Settings');
		$.sfScene.show('Login');
		$.sfScene.focus('Login');
	};
	
	var errCallback = function(jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error, "Settings", true, textStatus, jqXHR);
	};
	
	var duid = Helpers.getDUID();
	JsonServices.client.ClientLogout(AppContext.user.sid, AppContext.appName, duid, callback, errCallback);
}

SceneSettings.setToContext = function (language, userTz, userStreamTz, streamQuality) {
	try {
		SceneSettings.updateSettings(language ? language.id : null, userTz, userStreamTz, streamQuality);
		if (language) {
			AppContext.ClientSettings.Language = language;
			SceneSettings.getClientSettings();
		}
		if (userTz) {
			AppContext.ClientSettings.timeZoneName = userTz;
		}
		if (userStreamTz) {
			AppContext.ClientSettings.shiftTimeZoneName = userStreamTz;
		}
		if (streamQuality) {
			AppContext.ClientSettings.qualityPreset = streamQuality;
		}
	} catch (error) {
		ErrorHandler.HandleError(error, "Settings");  
	}
}
/*
Updates client settings
*/
SceneSettings.updateSettings = function(language, userTz, userStreamTz, streamQuality) {
    var errCallback = function(jqXHR, textStatus, error) {
		ErrorHandler.HandleError(error,"Settings",true, textStatus, jqXHR);
	};

    var callback = function (result) {
		SceneSettings.onLoadDataCompleted(); 
		if (userTz || userStreamTz) {
			ErrorHandler.NeedToRefresh["LiveTv"] = true;
			ErrorHandler.NeedToRefresh["ArchTv"] = true;
		}
    };

    SceneSettings.showLoading();
    try {
		JsonServices.client.SetSettings(AppContext.user.sid, language, userTz, userStreamTz, 
			streamQuality, callback, errCallback);
    } catch (error) {
		ErrorHandler.HandleError(error, "Settings");
    }  
}

/*
Loads description of account setting
*/
SceneSettings.loadAccount = function() {
    $("#account > .settingsDescription").empty();
	var text = "<h2>"+Resources.getResources().Account+".</h2>";
	text += "<p>"+Resources.getResources().YouLoggedInAs+" <span class='textHilight'>"+AppContext.user.email+"</span></p>";
	if (!Helpers.checkAllServices()) {
		text += "<p><b>" + Resources.getResources().SettingsSubscriptionExpired + "</b></p>";
	}
	text += "<p>"+Resources.getResources().DoYouWantToChangeAccount+"</p>";
	text += "<div id='btnLogout'></div>";
	$("#account > .settingsDescription").append(text);
    $("#btnLogout").sfButton({text : Resources.getResources().Logout});
}
/*
Loads description of language setting
*/
SceneSettings.loadLanguage = function() {
    $("#language > .settingsDescription").empty();
    $("#language > .settingsDescription").append("<h2>"+Resources.getResources().Language+".</h2><p>"+Resources.getResources().YouCanChoseLanguage + "</p>");
}
/*
Loads description of time zone setting
*/
SceneSettings.loadTimeZone = function() {
    $("#timeZone > .settingsDescription").empty();
    $("#timeZone > .settingsDescription").append("<h2>"+Resources.getResources().TimeZone+".</h2><p>"+Resources.getResources().YouCanChoseTimeZone + "</p>");
}
/*
Loads description of stream zone setting
*/
SceneSettings.loadStreamZone = function() {
    $("#streamZone> .settingsDescription").empty();
    $("#streamZone> .settingsDescription").append("<h2>"+Resources.getResources().StreamZone+".</h2><p>"+Resources.getResources().YouCanChoseStreamZone+"</p>");
}

SceneSettings.loadStream = function () {
	$("#stream> .settingsDescription").empty();
	$("#stream> .settingsDescription").append("<h2>"+Resources.getResources().SettingsStream+".</h2><p>"+Resources.getResources().SettingsChooseStreamQuality+"</p>");
}

SceneSettings.loadBuffers = function () {
	$("#buffers .settingsDescription").empty();
	$("#buffers .settingsDescription").append("<h2>"+Resources.getResources().SettingsBuffers+".</h2><p>"+Resources.getResources().SettingsBuffersDescription+"</p>");
	$("#buffers #lblTotalBuffer").sfLabel({text: Resources.getResources().SettingsTotalBuffer});
	$("#buffers #lblInitialBuffer").sfLabel({text: Resources.getResources().SettingsInitialBuffer});
	$("#buffers #lblPendingBuffer").sfLabel({text: Resources.getResources().SettingsPendingBuffer});
	$("#buffers .bufferKbLabel").sfLabel({text: Resources.getResources().SettingsKb});
	SceneSettings.settings = Helpers.loadBuffers();
	SceneSettings.resetBuffers();
	$("#btnSave").sfButton({text: Resources.getResources().SettingsSave});
	$("#btnReset").sfButton({text: Resources.getResources().SettingsReset});
}

SceneSettings.loadMessages = function () {
	$("#messager .settingsDescription").empty();
	$("#messager .settingsDescription").append("<h2>"+Resources.getResources().SettingsMessager+".</h2>");
	$("#messager #noMessages").html(Resources.getResources().SettingsMessagesNoMessages);
	SceneSettings.messagesMode = "many";
	
	var callback = function (messages) {
		SceneSettings.messages = [];
		SceneSettings.messages = messages.filter(
			function (message) { 
				return !message.isRead && message.expires > (new Date());
			}
		);
		SceneSettings.bindMessages();
	};
	
	JsonServices.client.GetMessages(AppContext.user.sid, callback, function () {});
}

SceneSettings.bindMessages = function () {
	if (SceneSettings.messages.length > 0) {
		Logger.write("There is a couple of messages", "Settings", true);
		var lbElems = [];
		for (var i = 0; i < SceneSettings.messages.length; i++) {
			lbElems.push(SceneSettings.getMessageHtml(SceneSettings.messages[i]));
		}
		Logger.write("Messages: " + lbElems.toSource(), "Settings", true);
		var perPage = SceneSettings.messages.length > SceneSettings.perPage ? SceneSettings.perPage : SceneSettings.messages.length;
		$('#lbMessages').sfList({data: lbElems, index: '0', itemsPerPage: perPage});
		$('#lbMessages').sfList('blur');
		$('#lbMessages').show();
		$("#noMessages").hide();
	} else {
		Logger.write("There is no messages", "Settings", true);
		$('#lbMessages').hide();
		SceneSettings.hideMessagesPager();
		$("#noMessages").show();
	}
}

SceneSettings.getMessageHtml = function (message) {
	var result = "";
	result += "<div class='message'>";
	result += "<div class='date'>" + DateHelper.getMessageDateTime(message.sent) + "</div>";
	var subject = message.subject.length > 35 ? message.subject.substring(0, 32) + "..." : message.subject;
	result += "<div class='subject'>" + subject + "</div>";
	result += "</div>";
	return result;
}

/*
Loads description of about
*/
SceneSettings.loadAbout = function () {
	var logo = Resources.getResources().SettingsAboutLogoUrl;
	var title = Resources.getResources().SettingsAboutTitle;
	var text = Resources.getResources().SettingsAboutText;
	var html = "<div><img src='"+logo+"'/><h2>" + title + "</h2><p>" + text + "</p></div>";
	$("#about> .settingsDescription").html(html);
}

SceneSettings.loadUpdates = function () {
	$("#updates .settingsDescription").empty();
	$("#updates .settingsDescription").append("<h2>"+Resources.getResources().SettingsUpdates+".</h2>");
	if (Updater.updateAvailable) {
		var loadChangesComplete = function (changes) {
			Logger.write("changes loaded: " + changes, "Settings", true);
			SceneSettings.updateChanges = changes;
			SceneSettings.bindChanges();
		};
		
		var loadManualComplete = function (manual) {
			Logger.write("manual loaded: " + manual, "Settings", true);
			SceneSettings.updateManual = manual;
		};
	
		Updater.loadChangesList(loadChangesComplete);
		Updater.loadManual(loadManualComplete);
	}
	$("#updates .button").sfButton({text: Resources.getResources().SettingsManual});
}

SceneSettings.bindChanges = function () {
	if (SceneSettings.updateChanges && SceneSettings.updateChanges[AppContext.ClientSettings.Language.cultureInfo]) {
		$("#updates .changes p").html(SceneSettings.updateChanges[AppContext.ClientSettings.Language.cultureInfo]);
	}
}

/*
Construnctor of one client setting

*name - setting's name
*btnArray - array of client setting's buttons 
*cbLoad - callback that loads description of client setting

*/
SettingItem = function (name, btnArray, cbLoad, cbGetCurrent) {
        this.name = name;
        this.btnArray = btnArray;
        this.cbLoad = cbLoad;
        this.cbGetCurrent = cbGetCurrent;
}
/*
Construnctor of one client setting's button

*name - button's name
*title - button's title
*callback - callback that runs when button is pressed
*btns - array of pop up window's items to choose setting from it

*/
Setting = function(lbArray,  idsArray) {
	this.lbArray = lbArray;
	this.idsArray = idsArray;
}
/*
Stores name of focused panel: settings or settingsNames
*/
SceneSettings.focusedPanel = "settingsNames";
SceneSettings.prototype.initialize = function () {
	Logger.write("SceneSettings.initialize()", "Settings");
	// 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    
    SceneSettings.currentLang = AppContext.ClientSettings.Language;
    SceneSettings.setArray();
	SceneSettings.loadSettingsPanel();
    SceneSettings.loadSetBtns();
    SceneSettings.loadDescriptions(); 
    SceneSettings.showSettings();
    SceneSettings.settingsPanel.focusPanel();
    //SceneSettings.getClientSettings();
     SceneSettings.setHelpBar();
	 
	ime_txtTotalBuffer = new IMEShell("txtTotalBuffer", callback_txtTotalBuffer);
	ime_txtInitialBuffer = new IMEShell("txtInitialBuffer", callback_txtInitialBuffer);
	ime_txtPendingBuffer = new IMEShell("txtPendingBuffer", callback_txtPendingBuffer);
}

function callback_txtTotalBuffer (cb) {
	cb.setKeypadPos(650, 100, 9);
	cb.setKeyFunc($.sfKey.ENTER, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusInitialBuffer();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.DOWN, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusInitialBuffer();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.RETURN, function () {
		try {
			widgetAPI.blockNavigation(event);
			$.sf.returnFocus();
			SceneSettings.settingsPanel.focusPanel();
			SceneSettings.focusedPanel = "settingsNames";
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			AppEvents.Exit();
		} catch (error) {
			ErrorHandler.HandleError(error,"Settings");
		}  
    });
}

function callback_txtInitialBuffer (cb) {
	cb.setKeypadPos(650, 100, 9);
	cb.setKeyFunc($.sfKey.ENTER, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusPendingBuffer();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.UP, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusTotalBuffer();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.DOWN, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusPendingBuffer();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.RETURN, function () {
		try {
			widgetAPI.blockNavigation(event);
			$.sf.returnFocus();
			SceneSettings.settingsPanel.focusPanel();
			SceneSettings.focusedPanel = "settingsNames";
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			AppEvents.Exit();
		} catch (error) {
			ErrorHandler.HandleError(error,"Settings");
		}  
    });
}

function callback_txtPendingBuffer (cb) {
	cb.setKeypadPos(650, 100, 9);
	cb.setKeyFunc($.sfKey.ENTER, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusSaveButton();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.UP, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusInitialBuffer();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.DOWN, function () {
		try {
			$.sf.returnFocus();
			SceneSettings.focusSaveButton();
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.RETURN, function () {
		try {
			widgetAPI.blockNavigation(event);
			$.sf.returnFocus();
			SceneSettings.settingsPanel.focusPanel();
			SceneSettings.focusedPanel = "settingsNames";
		} catch (error) {
			ErrorHandler.HandleError(error, "Settings");
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			AppEvents.Exit();
		} catch (error) {
			ErrorHandler.HandleError(error,"Settings");
		}  
    });
}
 
 SceneSettings.setHelpBar = function() {
	if (ScenePlayer.isPlaying) {
		$('#keysSettings').sfKeyHelp({
			'blue':Resources.getResources().Player, 
			'stop' : Resources.getResources().Stop,
			'updown':'', 'leftright':Resources.getResources().MoveCursor, 
			'enter':Resources.getResources().Select,
			'return':Resources.getResources().BackToMainMenu
		});
     } else {
		$('#keysSettings').sfKeyHelp({
			'updown':'', 'leftright':Resources.getResources().MoveCursor, 
			'enter':Resources.getResources().Select,
			'return':Resources.getResources().BackToMainMenu
		});
     }
 }
 
SceneSettings.prototype.handleShow = function () {
	Logger.write("SceneSettings.handleShow()", "Settings");
	// this function will be called when the scene manager show this scene 
}

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

SceneSettings.prototype.handleFocus = function () {
	Logger.write("SceneSettings.handleFocus()", "Settings");
	// this function will be called when the scene manager focus this scene
    AppContext.CurrentScene="Settings";
    if  (ScenePlayer.isPlaying == true)
    {
		Helpers.setBackgroundOpacity();
    }
	
	if (ErrorHandler.NeedToRefresh && ErrorHandler.NeedToRefresh["Settings"]) {
		SceneSettings.refresh();
		ErrorHandler.NeedToRefresh["Settings"] = false;
	} else {
		SceneSettings.translate();
	}
	SceneSettings.setHelpBar();
	SceneSettings.hideSettings(); 
	SceneSettings.settingsPanel.blurElement(SceneSettings.settingsPanel.index);
	SceneSettings.settingsPanel.focusElement(0);
	SceneSettings.showSettings();
	SceneSettings.handleLeft();
}

SceneSettings.prototype.handleBlur = function () {
	Logger.write("SceneSettings.handleBlur()", "Settings");
	// this function will be called when the scene manager move focus to another scene from this scene
	var settingId = SceneSettings.settingsPanel.getFocusedId();
	if (settingId.indexOf("account") > -1) {
		$("#btnLogout").sfButton("blur");
	} else if (settingId.indexOf("buffers") > -1) {
		$("#btnReset").sfButton("blur");
		$("#btnSave").sfButton("blur");
	} else if (settingId.indexOf("update") > -1) {
		$("#updates .button").sfButton("blur");
	} else if (settingId.indexOf("messager") > -1 && SceneSettings.messagesMode === "one") {
		$("#btnBackToMessages").sfButton("blur");
		$("#btnDeleteMessage").sfButton("blur");
	}
}
/*
Hides current client setting
*/
SceneSettings.hideSettings = function() {
	var idx = SceneSettings.settingsPanel.index;
	$("#"+SceneSettings.settingArray[idx].name).css({'visibility':'hidden'});
}
/*
Show current client setting
*/
SceneSettings.showSettings = function() {
    var idx = SceneSettings.settingsPanel.index;
    $("#"+SceneSettings.settingArray[idx].name).css({'visibility':'visible'});
	if (SceneSettings.settingArray[idx].name.indexOf("buffers") > -1) {
		SceneSettings.resetBuffers();
	}
}

SceneSettings.focusSaveButton = function () {
	$("#btnSave").sfButton("focus");
	SceneSettings.focusedBtnIndex = 1;
}

SceneSettings.focusResetButton = function () {
	$("#btnReset").sfButton("focus");
	SceneSettings.focusedBtnIndex = 0;
}

SceneSettings.focusTotalBuffer = function () {
	$("#txtTotalBuffer").focus();
	ime_txtTotalBuffer._inputModeChange();
	ime_txtTotalBuffer._inputModeChange();
	ime_txtTotalBuffer._inputModeChange();
}

SceneSettings.focusInitialBuffer = function () {
	$("#txtInitialBuffer").focus();
	ime_txtInitialBuffer._inputModeChange();
	ime_txtInitialBuffer._inputModeChange();
	ime_txtInitialBuffer._inputModeChange();
}

SceneSettings.focusPendingBuffer = function () {
	$("#txtPendingBuffer").focus();
	ime_txtPendingBuffer._inputModeChange();
	ime_txtPendingBuffer._inputModeChange();
	ime_txtPendingBuffer._inputModeChange();
}

SceneSettings.focusBackToMessagesButton = function () {
	$("#btnBackToMessages").sfButton("focus");
	SceneSettings.focusedBtnIndex = 0;
}

SceneSettings.focusDeleteMessageButton = function () {
	$("#btnDeleteMessage").sfButton("focus");
	SceneSettings.focusedBtnIndex = 1;
}

SceneSettings.resetBuffers = function () {
	document.getElementById("txtTotalBuffer").value = SceneSettings.settings.totalBuffer;
	document.getElementById("txtInitialBuffer").value = SceneSettings.settings.initialBuffer;
	document.getElementById("txtPendingBuffer").value = SceneSettings.settings.pendingBuffer;
}

SceneSettings.saveBuffers = function () {
	SceneSettings.showLoading();
	var toFunc = function () {
		var buffers = {
			totalBuffer: document.getElementById("txtTotalBuffer").value,
			initialBuffer: document.getElementById("txtInitialBuffer").value,
			pendingBuffer: document.getElementById("txtPendingBuffer").value
		};
		
		if (Helpers.saveBuffers(buffers)) {
			SceneSettings.settings = buffers;
		}
		
		$('#settingsPanel').css('visibility', 'visible');
		$('#loadingObject').sfLoading('hide');
		SceneSettings.showSettings();
	}
	
	setTimeout(toFunc, 0);
}

SceneSettings.showMessage = function (index) {
	var title = SceneSettings.messages[index].subject;
	var message = SceneSettings.messages[index].body;
	title = title.length > 50 ? title.substring(0, 47) + "..." : title;
	$("#messager .messageContent .messageTitle").html("<h2>" + Resources.getResources().SettingsMessagesSubject + ": " + title + "</h2>");
	$("#messager .messageContent .messageBody p").html(message);
	$("#btnBackToMessages").sfButton({text: Resources.getResources().SettingsMessagesBack});
	$("#btnDeleteMessage").sfButton({text: Resources.getResources().SettingsMessagesDelete});
	$("#messager .messages").hide();
	$("#messager .messageContent").show();
	SceneSettings.messagesMode = "one";
	SceneSettings.focusBackToMessagesButton();
}

SceneSettings.showMessagesPager = function () {
	var index = parseInt($("#lbMessages").sfList("getIndex")) + 1;
	var total = SceneSettings.messages.length;
	$("#messagesPagerInfo").html(index + " | " + total);
	$("#messagesPagerInfo").show();
}

SceneSettings.hideMessagesPager = function () {
	Logger.write("Hiding messages pager.", "Settings", true);
	$("#messagesPagerInfo").empty();
	$("#messagesPagerInfo").hide()
}

SceneSettings.backToMessages = function () {
	$("#messager .messageContent .messageTitle").empty();
	$("#messager .messageContent .messageBody p").empty();
	$("#messager .messageContent").hide();
	$("#messager .messages").show();
	$("#btnBackToMessages").sfButton("blur");
	$("#btnDeleteMessage").sfButton("blur");
	if (SceneSettings.messages && SceneSettings.messages.length > 0) {
		$("#lbMessages").sfList("focus");
		SceneSettings.showMessagesPager();
	} else {
		SceneSettings.settingsPanel.focusPanel();
		SceneSettings.focusedPanel = "settingsNames";
	}
	SceneSettings.messagesMode = "many";
}

SceneSettings.deleteMessage = function () {
	var msgIdx = $("#lbMessages").sfList("getIndex");
	var msgId = SceneSettings.messages[msgIdx].id;
	
	var tmpCallback = function (result) {
		if (result) {
			SceneSettings.messages.splice(msgIdx, 1);
			SceneSettings.bindMessages();
			SceneSettings.backToMessages();
		}
	};
	
	JsonServices.client.SetMessagesRead(AppContext.user.sid, [msgId], tmpCallback, function () {});
}

/*
Handles key right pressing
*/
SceneSettings.handleRight = function() {
	try
	{
		var idx = SceneSettings.settingsPanel.index;
		SceneSettings.currentListBoxId = idx;
		var settingId = SceneSettings.settingsPanel.getFocusedId();
		if (settingId.indexOf("account") > -1) {
			SceneSettings.focusedBtnIndex = 0;
			$("#btnLogout").sfButton("focus");
		} else if (settingId.indexOf("buffers") > -1) {
			Logger.write("Is panel focused: " + SceneSettings.settingsPanel.isFocused, "Settings", true);
			if (SceneSettings.settingsPanel.isFocused) {
				SceneSettings.focusTotalBuffer();
			} else if (SceneSettings.focusedBtnIndex == 0) {
				$("#btnReset").sfButton("blur");
				SceneSettings.focusSaveButton();
			}
		} else if (settingId.indexOf("update") > -1) {
			$("#updates .button").sfButton("focus");
		} else if (settingId.indexOf("messager") > -1 && SceneSettings.messages && SceneSettings.messages.length > 0) {
			if (SceneSettings.messagesMode === "many") {
				$("#lbMessages").sfList("focus");
				SceneSettings.showMessagesPager();
			} else {
				if (SceneSettings.focusedPanel === "settingsNames") {
					SceneSettings.focusBackToMessagesButton();
				} else {
					$("#btnBackToMessages").sfButton("blur");
					SceneSettings.focusDeleteMessageButton();
				}
			}
		} else {
			if (SceneSettings.settingArray[idx].btnArray.length > 0) {
				$(SceneSettings.listBoxes[idx]).sfList('focus');
			}
		}
		
		var messagesUnavailable = settingId.indexOf("messager") > -1 && (!SceneSettings.messages || SceneSettings.messages.length == 0);
		if (settingId.indexOf("about") < 0 && !messagesUnavailable) {
			SceneSettings.focusedPanel = "settings";
			SceneSettings.settingsPanel.blurPanel();
		}
	}
	catch(error)
	{
		ErrorHandler.HandleError(error,"Settings");
	}
}
/*
Handles key left pressing
*/
SceneSettings.handleLeft = function() {
    try
    {
		if (SceneSettings.focusedPanel != "settingsNames")
		{
			var settingId = SceneSettings.settingsPanel.getFocusedId();
			if (settingId.indexOf("buffers") > -1) {
				if (SceneSettings.focusedBtnIndex == 1) {
					$("#btnSave").sfButton("blur");
					SceneSettings.focusResetButton();
				} else {
					$("#btnReset").sfButton("blur");
					SceneSettings.settingsPanel.focusPanel();
					SceneSettings.focusedPanel = "settingsNames";
				}
			} else if (settingId.indexOf("update") > -1) {
				$("#updates .button").sfButton("blur");
				SceneSettings.settingsPanel.focusPanel();
				SceneSettings.focusedPanel = "settingsNames";
			} else if (settingId.indexOf("account") > -1) {
				$("#btnLogout").sfButton("blur");
				SceneSettings.focusedPanel = "settingsNames";
				SceneSettings.settingsPanel.focusPanel();
			} else if (settingId.indexOf("messager") > -1) {
				if (SceneSettings.messagesMode === "many" || (SceneSettings.messagesMode === "one" && SceneSettings.focusedBtnIndex == 0)) {
					if (SceneSettings.messagesMode === "one") {
						SceneSettings.backToMessages();
					}
					$("#lbMessages").sfList("blur");
					SceneSettings.settingsPanel.focusPanel();
					SceneSettings.focusedPanel = "settingsNames";
				} else {
					$("#btnDeleteMessage").sfButton("blur");
					SceneSettings.focusBackToMessagesButton();
				}
			} else {
				var idx = SceneSettings.settingsPanel.index;
				SceneSettings.focusedPanel = "settingsNames";
				$(SceneSettings.listBoxes[idx]).sfList('blur');
				SceneSettings.settingsPanel.focusPanel();
			}
		}
    }
    catch(error)
    {
		ErrorHandler.HandleError(error,"Settings");
    }  
}
/*
Handles key up pressing
*/
SceneSettings.handleUp = function() {
	try
	{
		if(SceneSettings.focusedPanel == "settingsNames")
		{
			SceneSettings.hideSettings();
			SceneSettings.settingsPanel.focusPrev(); 
			
			SceneSettings.showSettings();
			SceneSettings.setCurrentValue();
		}
		else
		{
			var settingId = SceneSettings.settingsPanel.getFocusedId();
			if (settingId.indexOf("buffers") > -1) {
				$("#btnReset").sfButton("blur");
				$("#btnSave").sfButton("blur");
				SceneSettings.focusPendingBuffer();
			} else if (settingId.indexOf("messager") > -1 && SceneSettings.messagesMode === "many") {
				$("#lbMessages").sfList("prev");
				SceneSettings.showMessagesPager();
			} else if (settingId.indexOf("update") < 0) {
				var idx = SceneSettings.settingsPanel.index;
				var index = $(SceneSettings.listBoxes[idx]).sfList('getIndex');
				if (((index+1) % SceneSettings.perPage) == 1)
				{
					var moveTo = Math.ceil((index - SceneSettings.perPage)/SceneSettings.perPage);
					$(SceneSettings.scrolls[idx]).sfScroll('move', moveTo);
				}
				if (index == 0)
				{
					var currentCount = SceneSettings.settingArray[idx].btnArray[0].lbArray.length; 
					var moveTo = Math.ceil(currentCount / SceneSettings.perPage)-1;
					$(SceneSettings.scrolls[idx]).sfScroll('move', moveTo);
				}
				$(SceneSettings.listBoxes[idx]).sfList('prev');
				SceneSettings.selectItem();
			}
		}
	}
	catch(error)
	{
		ErrorHandler.HandleError(error,"Settings");
	}  
}

/*
Sets current value in current listbox
*/
SceneSettings.setCurrentValue = function() {
    var idx = SceneSettings.settingsPanel.index;
    var getCurrentCallback = SceneSettings.settingArray[idx].cbGetCurrent;
    if (getCurrentCallback != null)
    {
		var index = getCurrentCallback();
		$(SceneSettings.listBoxes[idx]).sfList({'index':index});
		if(SceneSettings.focusedPanel=="settingsNames")
		{
			$(SceneSettings.listBoxes[idx]).sfList('blur');
		}
		var moveTo = Math.ceil((index+1)/ SceneSettings.perPage-1);
		$(SceneSettings.scrolls[idx]).sfScroll('move', moveTo);
		$(".setting .sf-ui-list-selected").addClass("selectedSetting");
		$(".setting .sf-ui-list-focused").addClass("selectedSetting");
		if (idx == 2)
		{
			SceneSettings.selectedPage = moveTo;
		}
    }
}

/*
* Selects account item
*/
SceneSettings.selectAccount = function() {
    try
    {
		SceneSettings.hideSettings(); 
		SceneSettings.settingsPanel.blurElement(SceneSettings.settingsPanel.index);
		SceneSettings.settingsPanel.focusElement(0);
		SceneSettings.showSettings();
		SceneSettings.handleLeft();
		if  (ScenePlayer.isPlaying == true)
		{
			ScenePlayer.stop();
			SceneSettings.setHelpBar();
		}
    }
    catch(error)
    {
		ErrorHandler.HandleError(error,"Settings");
    }
}

SceneSettings.showUpdates = function () {
	try {
		SceneSettings.hideSettings(); 
		SceneSettings.settingsPanel.blurElement(SceneSettings.settingsPanel.index);
		var idx = 0;
		for (var i = 0; i < SceneSettings.settingArray.length; i++) {
			if (SceneSettings.settingArray[i].name.indexOf("updates") > -1) {
				idx = i;
				break;
			}
		}
		SceneSettings.settingsPanel.focusElement(idx);
		SceneSettings.showSettings();
		SceneSettings.handleLeft();
		if (ScenePlayer.isPlaying == true) {
			ScenePlayer.stop();
			SceneSettings.setHelpBar();
		}
    } catch (error) {
		ErrorHandler.HandleError(error, "Settings");
    }
}

/*
Handles key down pressing
*/
SceneSettings.handleDown = function() {
	try
	{
		if (SceneSettings.focusedPanel == "settingsNames")
		{
			SceneSettings.hideSettings();
			SceneSettings.settingsPanel.focusNext();
			
			SceneSettings.showSettings();
			SceneSettings.setCurrentValue();

		}
		else
		{
			var settingId = SceneSettings.settingsPanel.getFocusedId();
			if (settingId.indexOf("messager") > -1) {
				if (SceneSettings.messagesMode === "many") {
					$("#lbMessages").sfList("next");
					SceneSettings.showMessagesPager();
				}
			} else if (settingId.indexOf("account") < 0 && settingId.indexOf("buffers") < 0 && settingId.indexOf("update") < 0) {
				var idx = SceneSettings.settingsPanel.index;
				var index = $(SceneSettings.listBoxes[idx]).sfList('getIndex');
				if (((index+1) % SceneSettings.perPage) == 0)
				{
					var moveTo = Math.ceil((index+2)/SceneSettings.perPage-1);
					$(SceneSettings.scrolls[idx]).sfScroll('move', moveTo);
				}
				if (index == SceneSettings.settingArray[idx].btnArray[0].lbArray.length -1)
				{
					var moveTo = 0;
					$(SceneSettings.scrolls[idx]).sfScroll('move', moveTo);
				}
				$(SceneSettings.listBoxes[idx]).sfList('next');  
				SceneSettings.selectItem();
			}
		}
	}
	catch(error)
	{
		ErrorHandler.HandleError(error,"Settings");  
	}
}

/*
Adds style to selected item
*/
SceneSettings.selectItem = function() {
	var settingId = SceneSettings.settingsPanel.getFocusedId();
	if (settingId.indexOf("timeZone") > -1)
	{
		var idx = SceneSettings.settingsPanel.index;
		var index = $(SceneSettings.listBoxes[idx]).sfList('getIndex');        
		var page = Math.ceil((index+1)/SceneSettings.perPage-1); 
		if (SceneSettings.selectedPage == page)
		{
			$(".selectedSetting").css({'color':'#fff'});
			$(".selectedSetting").css({'font-size':'16pt'});
		}
		else
		{
			$(".selectedSetting").css({'color':'#72c6f8'});
			$(".selectedSetting").css({'font-size':'16pt'});
		}
	}
}

/*
Handles key Enter pressing
*/
SceneSettings.handleEnter = function() {
	try {
		if (SceneSettings.focusedPanel == "settings") {
			var settingId = SceneSettings.settingsPanel.getFocusedId();
			Logger.write("Handling enter for '" + settingId + "'", "Settings", true);
			if (settingId.indexOf("account") > -1) {
				SceneSettings.logout();
			} else if (settingId.indexOf("buffers") > -1) {
				if (SceneSettings.focusedBtnIndex == 0) {
					SceneSettings.resetBuffers();
				} else {
					SceneSettings.saveBuffers();
				}
			} else if (settingId.indexOf("update") > -1) {
				$("#updates .button").sfButton("blur");
				SceneUpdateManual.show(SceneSettings.updateManual, "Settings");
			} else if (settingId.indexOf("messager") > -1) {
				if (SceneSettings.messagesMode === "many") {
					var msgIndex = $("#lbMessages").sfList("getIndex");
					SceneSettings.showMessage(msgIndex);
				} else {
					if (SceneSettings.focusedBtnIndex == 0) {
						SceneSettings.backToMessages();
					} else {
						SceneSettings.deleteMessage();
					}
				}
			} else {
				var idx = SceneSettings.settingsPanel.index;
				if (settingId.indexOf("language") > -1) {
					var lang = AppContext.Languages[$(SceneSettings.listBoxes[idx]).sfList('getIndex')];
					SceneSettings.setToContext(lang, null, null);
					SceneSettings.handleRight();
					SceneSettings.settingsPanel.blurElement(0);
				} else if (settingId.indexOf("timeZone") > -1) {
					var timeZone = AppContext.TimeZones[$(SceneSettings.listBoxes[idx]).sfList('getIndex')].id;
					SceneSettings.setToContext(null, timeZone, null);
				} else if (settingId.indexOf("streamZone") > -1) {
					var streamZone = AppContext.StreamZones[$(SceneSettings.listBoxes[idx]).sfList('getIndex')].id;
					SceneSettings.setToContext(null, null, streamZone);
				} else if (settingId.indexOf("stream") > -1) {
					var streamQuality = AppContext.StreamQualityPresets[$(SceneSettings.listBoxes[idx]).sfList('getIndex')];
					SceneSettings.setToContext(null, null, null, streamQuality);
				}
				SceneSettings.setCurrentValue();
			}
		}
	} catch (error) {
		ErrorHandler.HandleError(error,"Settings");
	}
}
SceneSettings.backToMainMenu = function() {
	try {
		var settingId = SceneSettings.settingsPanel.getFocusedId();
		if (settingId.indexOf("messager") > -1 && SceneSettings.messagesMode === "one" && SceneSettings.focusedPanel != "settingsNames") {
			SceneSettings.backToMessages();
		} else if (SceneSettings.focusedPanel == "settings") {
			if (settingId.indexOf("buffers") > -1) {
				SceneSettings.focusedBtnIndex = 0
				$("#btnSave").sfButton("blur");
				$("#btnReset").sfButton("blur");
				SceneSettings.settingsPanel.focusPanel();
				SceneSettings.focusedPanel = "settingsNames";
			} else {
				SceneSettings.handleLeft();
			}
		} else {
			$.sfScene.hide('Settings');
			SceneMainMenu.show();
		}
    } catch (error) {
		ErrorHandler.HandleError(error,"Settings");  
    }  
}

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

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