function SceneLogin(options) {
	this.options = options;
	
    var ime_txtLogin = null;
	var ime_txtPassword = null;
}

SceneLogin.prototype.initialize = function () {
	Logger.write("SceneLogin.initialize()", "Login");
	// 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
            this.isLoading = false;
            $('#limgLoggin').sfLoading();
            SceneLogin.translate();
            ime_txtLogin = new IMEShell("txtLogin", callback_txtLogin);
            ime_txtPassword = new IMEShell("txtPassword", callback_txtPassword);
            SceneLogin.isBtnLoginFocused=false;
            SceneLogin.loadLanguages();
            SceneLogin.hideLanguages();
            SceneLogin.setDisplayLanguage();
}

function callback_txtLogin(cb) {
    cb.setKeypadPos(660, 80, 9);
    SceneLogin.focusLogin();
    cb.setKeyFunc($.sfKey.RETURN, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.btnIndex = 0;
            $("#btnLogin").sfButton("focus");
			SceneLogin.isBtnLoginFocused = true;
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.btnIndex = 0;
            $("#btnLogin").sfButton("focus");
			SceneLogin.isBtnLoginFocused = true;
			SceneLogin.handleExit();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
    cb.setKeyFunc($.sfKey.ENTER, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.focusPassword();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
    cb.setKeyFunc($.sfKey.DOWN, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.focusPassword();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.UP, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.focusLanguages();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.BLUE, function(){
		try {
			SceneLogin.handleBlue();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			AppEvents.Exit();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
    if (!SceneMainMenu.showed)
    {
        SceneLogin.focusLogin();        
     }
     else
     {
         $.sfScene.focus(AppContext.CurrentScene);
     }
}

function callback_txtPassword(cb) {
    cb.setKeypadPos(660, 80, 9);
    cb.setKeyFunc($.sfKey.RETURN, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.btnIndex = 0;
            $("#btnLogin").sfButton("focus");
			SceneLogin.isBtnLoginFocused = true;
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.btnIndex = 0;
            $("#btnLogin").sfButton("focus");
			SceneLogin.isBtnLoginFocused = true;
			SceneLogin.handleExit();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
    cb.setKeyFunc($.sfKey.ENTER, function(){
        try {
            $.sf.returnFocus();
            SceneLogin.btnIndex = 0;
            $("#btnLogin").sfButton("focus");
			SceneLogin.isBtnLoginFocused = true;
        } catch (error) {
            $("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
        }  
    });
    cb.setKeyFunc($.sfKey.UP, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.focusLogin();
		} catch (error) {
			ErrorHandler.HandleError(error,"Login");
		}
    });
    cb.setKeyFunc($.sfKey.DOWN, function(){
		try {
			$.sf.returnFocus();
			$("#btnLogin").sfButton("focus");
			SceneLogin.btnIndex = 0;
			SceneLogin.isBtnLoginFocused = true;
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.BLUE, function(){
		try {
			$.sf.returnFocus();
			SceneLogin.handleBlue();
			SceneLogin.focusPassword();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
	cb.setKeyFunc($.sfKey.EXIT, function(){
		try {
			AppEvents.Exit();
		} catch (error) {
			$("#lblError").sfLabel({text:ErrorHandler.HandleError(error,"Login")});
		}  
    });
}

SceneLogin.showLanguages = function(){
    $("#lbLoginLanguages").show();
    $("#panelLanguage").hide();
    $("#lbLoginLanguages").sfList("focus");
    SceneLogin.showedLanguages = true;
}
SceneLogin.hideLanguages = function(){
    $("#lbLoginLanguages").hide();    
    $("#panelLanguage").show();
    SceneLogin.showedLanguages = false;
    SceneLogin.setDisplayLanguage();
}

SceneLogin.setDisplayLanguage = function(){
    $("#panelLanguage").html(AppContext.ClientSettings.Language.name);
}

SceneLogin.focusLanguages = function(){   
    SceneLogin.btnIndex = 2;
    SceneLogin.isBtnLoginFocused = true;
    $("#panelLanguage").removeClass("sf-ui-list-blured");
    $("#panelLanguage").addClass("sf-ui-list-focused");
}

SceneLogin.blurLanguages = function(){
    $("#panelLanguage").addClass("sf-ui-list-blured");
    $("#panelLanguage").removeClass("sf-ui-list-focused");
}
SceneLogin.loadLanguages = function(){  
	Logger.write("Loading languages", "Login", true);
    var languageElements = new Array;
    var selectedIndex = 0;
    for (var i = 0; i < AppContext.Languages.length; i++) {
		languageElements[i] = AppContext.Languages[i].name;
		if (AppContext.Languages[i].name == AppContext.ClientSettings.Language.name)  {
			selectedIndex = i;
		}
    }
	
    var perPage = languageElements.length;
	$("#lbLoginLanguages").sfList({data: languageElements, index: '0', itemsPerPage: perPage });
	$("#lbLoginLanguages").sfList("move", selectedIndex);
}

SceneLogin.setHelpBar = function () {
	var passwordType = $("#txtPassword").attr("type");
	var blue = passwordType === "password" ? Resources.getResources().ShowPassword : Resources.getResources().HidePassword;
	$('#hbKeyHelp').sfKeyHelp({
		'blue': blue,
		'Enter': Resources.getResources().Select, 
		'updown': Resources.getResources().MoveCursor
	});
}

SceneLogin.translate = function(){
	SceneLogin.setHelpBar();
    $('#lblLogin').sfLabel({text:Resources.getResources().Login, width:'80px'});
    $('#loginTitle').sfLabel({text:Resources.getResources().Login, width:'80px'});
    $('#lblPassword').sfLabel({text:Resources.getResources().Password, width:'80px'});
    $('#btnLogin').sfButton({text:Resources.getResources().Login, width:'140px'});
    $("#lblError").sfLabel({text:Resources.getResources().SceneLoginWrongLoginError});
	$("#titlePopUp h2").html(Resources.getResources().ApplicationName);
	SceneLogin.loadLanguages();
	SceneLogin.setDisplayLanguage();
	Helpers.setImeLanguage('en');
}
 /*
 * Set current language
 */
SceneLogin.setCurrentLanguage = function() {    
    var lang = AppContext.Languages[$("#lbLoginLanguages").sfList('getIndex')];
    SceneLogin.setLangToContext(lang);
}

/*
* Sets language to app context
*/
SceneLogin.setLangToContext = function(language) {
    if(language.name!="None")
    {
		AppContext.ClientSettings.Language = language;           
		Resources.getResources(AppContext.ClientSettings.Language.cultureInfo);
		SceneLogin.translate();
    }           
}


SceneLogin.successLogin = function(){
    SceneLogin.endLoading();
    $.sf.returnFocus();
    $.sfScene.hide('Login');
    SceneMainMenu.show();           
}
/*
Updates language settings
*/
SceneLogin.updateLanguageSettings = function(callback, errCallback){
	var language = AppContext.ClientSettings.Language;
    try {
		JsonServices.client.SetSettings(AppContext.user.sid, language.id, null, null, null, callback, errCallback);
    } catch (error) {
		ErrorHandler.HandleError(error, "Login");
    }
}

/*
    Checks input data and begin login
*/
/*
Gets clients settings from web service
*/
SceneLogin.getClientSettings = function () {
    SceneLogin.startLoading();
    
    var errCallback = function (error) {
		$("#lblError").sfLabel({text: error});
    }
    
    var callbackSuccess = function () {
		SceneLogin.successLogin();   
    }
    
    var callback = function (result) {
        try {
			Login.getClientSettings(callbackSuccess, errCallback);
        } catch (error) {
			$("#lblError").empty();
			$("#lblError").append(ErrorHandler.HandleError(error, "Login"));  
        }
    }
    
	SceneLogin.updateLanguageSettings(callback, callback);
}

/*
      Clers values in inputs
*/
SceneLogin.clear = function() {
	document.getElementById('txtPassword').value = "";
	document.getElementById('txtLogin').value = "";
	if ($("#txtPassword").attr("type") === "text") {
		SceneLogin.handleBlue();
	}
}

/*
    Try to login with selected login and password
    
    *login - user login
    *passwd - user password
    *DUID - device unique id
*/
SceneLogin.login = function (DUID, login, passwd) {
    Logger.write("=========1===========Login: "+login+"  Password: "+passwd, "Login");
    var successCb = function(result) { 
        try {
			SceneLogin.endLoading();
			SceneLogin.getClientSettings();
        } catch (error) {
			SceneLogin.endLoading();
			ErrorHandler.HandleError(error,"Login");
        }
    }
    
    var errCb = function (error) {
         SceneLogin.endLoading();
         $("#lblError").sfLabel({text:error});
    }
	
    Login.login(DUID, login, passwd, successCb, errCb);
}

/*
    Shows "Loading" element and hides others
*/
SceneLogin.startLoading = function(){
    this.isLoading = true;
    $('#divLogin').css('visibility', 'hidden');
    $('#limgLoggin').sfLoading('show');
	$("#inputsDiv").hide();
    //$('#hbKeyHelp').sfKeyHelp('hide');
}

/*
    Hides "Loading" element and shows others
*/
SceneLogin.endLoading = function(){
    this.isLoading = false;
    $('#divLogin').css('visibility', 'visible');
    $('#limgLoggin').sfLoading('hide');
	$("#inputsDiv").show();
    //$('#hbKeyHelp').sfKeyHelp('show');
}

/*
    Focused "Password" textbox
*/
SceneLogin.focusPassword = function(){
    $('#txtPassword').focus();
    $("#btnLogin").sfButton("blur");
}

/*
    Focuses "Login" textbox
*/
SceneLogin.focusLogin = function(){
      $('#txtLogin').focus();      
      ime_txtLogin._inputModeChange();   
}

SceneLogin.prototype.handleShow = function () {
	Logger.write("SceneLogin.handleShow()", "Login");
	// this function will be called when the scene manager show this scene 
	Logger.write("Login button outer html: " + $($("#btnLogin").parent().clone()).html(), "Login", true);
    SceneLogin.translate();
    SceneLogin.clear();
}

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

SceneLogin.prototype.handleFocus = function () {
	Logger.write("SceneLogin.handleFocus()", "Login");
	// this function will be called when the scene manager focus this scene    
    if (!SceneMainMenu.showed)
    {
        if(AppContext.CurrentScene!="")
        {
			SceneLogin.sender=AppContext.CurrentScene;
        }
        AppContext.CurrentScene="Login";     
        SceneLogin.focusLogin();   
        $("#btnLogin").sfButton("blur");
     }
     else
     {
         $.sfScene.focus(AppContext.CurrentScene);
     }
}

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

SceneLogin.handleUp = function(){
    try
    {
		if (SceneLogin.showedLanguages)
		{
			$("#lbLoginLanguages").sfList("prev");
			return;
		}

		if(SceneLogin.isBtnLoginFocused!=true)
		{
			SceneLogin.focusLogin();                
		}        
		else  if (SceneLogin.btnIndex == 2)
		{            
			$("#btnLogin").sfButton("focus");
			SceneLogin.btnIndex = 0;
			SceneLogin.blurLanguages();
		}
		else
		{
			SceneLogin.focusPassword();
			SceneLogin.isBtnLoginFocused = false;
		}
    }
    catch(error)
    {
		ErrorHandler.HandleError(error,"Login");  
    }
}

SceneLogin.handleDown=function(){
    try
    {
		if (SceneLogin.showedLanguages)
		{
			$("#lbLoginLanguages").sfList("next");
			return;
		}

		if(SceneLogin.isBtnLoginFocused != true)
		{
			SceneLogin.focusPassword();
		}
		else
		{
		
			if (SceneLogin.btnIndex > 1)
			{
				SceneLogin.focusLogin();         
				SceneLogin.blurLanguages();
			}
			else
			{
				 SceneLogin.focusLanguages();  
				 $("#btnLogin").sfButton("blur");
			}
		}
    }
    catch(error)
    {
          ErrorHandler.HandleError(error,"Login");  
    }
}

SceneLogin.handleEnter = function () {
    try {
        if (this.isLoading)
            return;
            
        if (SceneLogin.isBtnLoginFocused == true) {
			if (SceneLogin.btnIndex == 0) {
				SceneLogin.startLoading();
				//Logger.write("Login text html: " + $("#inputsDiv").html(), "Login", true);
				var DUID = Helpers.getDUID();
				SceneLogin.login(DUID, document.getElementById('txtLogin').value, document.getElementById('txtPassword').value);
			} else if (SceneLogin.btnIndex == 2) {
				if (!SceneLogin.showedLanguages) {
					SceneLogin.showLanguages();
				} else {
					SceneLogin.setCurrentLanguage();
					SceneLogin.hideLanguages();
				}
			} else {
				$.sfScene.hide('Login');
				$.sfScene.show("DescribeApp");
				$.sfScene.focus("DescribeApp");
			}
        }            
    } catch (error) {
		SceneLogin.endLoading();
		ErrorHandler.HandleError(error,"Login");  
    }
}

SceneLogin.handleBlue = function () {
	var passParent = $("#txtPassword").parent();
	var type = $("#txtPassword").attr("type");
	var size = $("#txtPassword").attr("size");
	var maxlength = $("#txtPassword").attr("maxlength");
	var value = $("#txtPassword").val();
	
	$("#txtPassword").remove();
	var newType = type === "password" ? "text" : "password";
	var passHtml = "<input type='" + newType + "' id='txtPassword' size='" + size + "' maxlength='" + maxlength + "' />";
	passParent.append(passHtml);
	$("#txtPassword").val(value);
	ime_txtPassword = null;
	ime_txtPassword = new IMEShell("txtPassword", callback_txtPassword);
	ime_txtPassword.setKeypadPos(660, 80, 9);
	SceneLogin.setHelpBar();
}

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

SceneLogin.prototype.handleKeyDown = function (keyCode) {
	Logger.write("SceneLogin.handleKeyDown(" + keyCode + ")", "Login");
	// TODO : write an key event handler when this scene get focued
    if (!SceneLogin.isLoading) {
        switch (keyCode) {        
            case $.sfKey.LEFT:
                break;
            case $.sfKey.RIGHT:
                break;
            case $.sfKey.UP:
                SceneLogin.handleUp();
                break;
            case $.sfKey.DOWN:
                SceneLogin.handleDown();
                break;
            case $.sfKey.ENTER:
               SceneLogin.handleEnter();
                break;
			case $.sfKey.BLUE:
				SceneLogin.handleBlue();
				break;
            case $.sfKey.RETURN:
                widgetAPI.sendReturnEvent();
                break;
            case $.sfKey.EXIT:
                try
                {
                    widgetAPI.blockNavigation(event);
					SceneLogin.handleExit();
                }
                catch(error)
                {
					ErrorHandler.HandleError(error,"Login");  
                }     
                break;
            default:         
                widgetAPI.blockNavigation(event);
                break;
        }
    }
}