
var usrpwd_label_username = $L("Username");
var usrpwd_label_password = $L("Password");

var usrpwd_label_signin_button = $L("Sign in");
var usrpwd_label_signingin_button = $L("Signing in...");

var usrpwd_username_hintText = $L("enter username...");
var usrpwd_password_hintText = $L("enter password...");

JoinuserpasswordAssistant = Class.create({

    userAttributes: {
		textFieldName: "userId",
		hintText: usrpwd_username_hintText,
        property: 'value',
        multi: false,
        label: usrpwd_label_username,
		changeOnKeyPress: true,
		textReplacement: false,
        disabled: false,
    },
    
    userModel: {
        'value': ''
    },    

	passwordAttributes: {
		textFieldName: "password",
		hintText: usrpwd_password_hintText,
        property: 'value',
        multi: false,
        label: usrpwd_label_password,
		changeOnKeyPress: true,
        disabled: false,
		requiresEnterKey: true,
		focusMode: Mojo.Widget.focusSelectMode,
    },
    
    passwordModel: {
        'value': ''
    },
	
    initialize: function(sceneAssistant, profile){
        Mojo.Log.info("Joinu-p initialize " + NetworkList.printProfile(profile));     
        
        this.sceneAssistant = sceneAssistant;
        this.controller = this.sceneAssistant.controller;
        
        if (profile) {
            this.joinProfile = profile;
        }           
    },

    setup: function(widget){
		Mojo.Log.info("Joinu-p setup");
        this.widget = widget;
        this.titleElement = this.controller.get('userpass_joinTitle');
        this.statusMessage = this.controller.get('userpass_statusMessage');
		this.warningIcon = this.controller.get('userpass_warningIcon');
		this.warningIcon.hide();
        
        if(this.titleElement)
            this.titleElement.innerHTML = this.titleElement.innerHTML + " " + this.joinProfile.ssid.escapeHTML();
        
		this.joinButtonModel = {buttonLabel: usrpwd_label_signin_button};
		this.joinButton = this.controller.get('userpass_joinButton');
        this.controller.setupWidget('userpass_joinButton', {type:Mojo.Widget.activityButton}, this.joinButtonModel);
		Mojo.Event.listen(this.joinButton,'mojo-tap', this.joinNetwork.bind(this))
        
        this.controller.setupWidget('userpass_user_widget', this.userAttributes, this.userModel);
		this.controller.get('userpass_user_widget').observe(Mojo.Event.propertyChange, this.propertyChanged.bind(this));
        this.controller.setupWidget('userpass_password_widget', this.passwordAttributes, this.passwordModel);
		this.controller.get('userpass_password_widget').observe(Mojo.Event.propertyChange, this.propertyChanged.bind(this));

        if (this.joinProfile.securty && this.joinProfile.security.enterpriseSecurity) {
            if (this.joinProfile.security.enterpriseSecurity.password) 
                this.passwordElement.value = this.joinProfile.security.enterpriseSecurity.password;
            
            if (this.joinProfile.security.enterpriseSecurity.userId) 
                this.usernameElement.value = this.joinProfile.security.enterpriseSecurity.userId;
        }
		this.validate();
    },    

    propertyChanged: function(event){
        this.validate();
		
		// If the password field has focus and Enter is pressed then simulate tapping on "Sign In"
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			// If the submit button is enabled then create the account
			if (this.joinButtonModel.disabled == false) {
				this.joinNetwork(event);
			} else {
				this.controller.get('userpass_user_widget').mojo.focus();
			}
		}

    },
        
    joinNetwork: function(event){
		event.stop();
		this.clearStatusMessage();
		
		this.setButtonState(true);
		
        var profile = {
            ssid: this.joinProfile.ssid,
            security: {
                securityType: this.joinProfile.security.securityType,
                enterpriseSecurity: {
                    password: this.passwordModel.value,
                    userId: this.userModel.value
                }
            }
        };
		
        if(this.joinProfile.wasCreatedWithJoinOther)
        {
            profile.wasCreatedWithJoinOther = this.joinProfile.wasCreatedWithJoinOther;
        }
        
		this.joinProfile = profile;
        NetworkList.connect(this.controller, profile, this.handleConnect.bind(this), this.handleConnectFailure.bind(this, profile));

    },
    
    validate: function() {
//      Mojo.Log.info("userpass validate");
        
        var key = this.passwordModel.value;
        var name = this.userModel.value;
        
        if(key.length > 0 && name.length > 0) {
            this.joinButtonModel.disabled = false;
        } else {
            this.joinButtonModel.disabled = true;
        }       
		this.controller.modelChanged(this.joinButtonModel);
    },
	
	setButtonState: function(state) {
		if (state) {
			this.joinButtonModel.buttonLabel = usrpwd_label_signingin_button;
			this.joinButtonModel.disabled = true;
			this.controller.modelChanged(this.joinButtonModel);		
			this.joinButton.mojo.activate();
		}
		else {
			this.joinButtonModel.buttonLabel = usrpwd_label_signin_button;
			this.joinButtonModel.disabled = false;
			this.controller.modelChanged(this.joinButtonModel);
			this.joinButton.mojo.deactivate();
		}
	},
	
    handleStatusNotification: function(response) {
        Mojo.Log.info("joinu-p handleStatus " + Object.toJSON(response));
        if (response.status == 'serviceDisabled') {
			this.widget.mojo.close();
		} else if (this.joinProfile && response.networkInfo) {
            if (this.joinProfile.ssid == response.networkInfo.ssid) {
                switch (response.status) {
                    case 'connectionStateChanged':
                        var item = response.networkInfo;
//////////////////////////////////////////////////////
//						item.lastConnectError = 'ClientCertificateRequired';
//						item.connectState = 'associationFailed';
//////////////////////////////////////////////////////						                        
                        switch (item.connectState) {
                            case 'associated':
                                if (item.lastConnectError == undefined) {
                                    this.widget.mojo.close();
                                } else {
                                    this.updateStatusMessage(item.lastConnectError);
                                }
								this.setButtonState(false);
								
                                break;
                            case 'associationFailed':
							     if(item.lastConnectError == 'ClientCertificateRequired') {
							        this.widget.mojo.close();
							        this.sceneAssistant.controller.showDialog({
							            template: 'joincert/joincert-scene',
							            assistant: new JoincertAssistant(this, this.joinProfile)
							        });
								 } else {
								    this.updateStatusMessage(item.lastConnectError);
									this.setButtonState(false);
								 }
                                
                                break;
                        };
                        break;
                };
            }
        }
    },
    
    updateStatusMessage: function(message) {
        
        var l = label_status_message_unknown;
        if (message != undefined) {         
            var label = "label_status_message_" + message.toLowerCase();
            try{
                l = eval(label);
            } catch(err) {
				Mojo.Log.info("unable to eval");
                l = label_status_message_unknown;
            }
        } 
        
        this.statusMessage.innerHTML = l;
		this.warningIcon.show();
		this.controller.get('userpass_password_widget').mojo.focus();
    },

    clearStatusMessage: function(){
        this.statusMessage.innerHTML = "";
		this.warningIcon.hide();
    },

    getStatusResponseFailed: function(response) {
        Mojo.Log.warn("joinu-p getStatusFailed " + Object.toJSON(response));
    },
    
    handleConnect: function(response){
        Mojo.Log.info("joinu-p Trying to connect to: " + this.joinProfile.ssid);
    },
    
    handleConnectFailure: function(item, response){
        Mojo.Log.warn("joinu-p connect failed: " + Object.toJSON(response));
        this.updateStatusMessage(response.errorText);        
    },
    
    activate: function(){
        Mojo.Log.info("joinu-p activate");
        this.subscribeHandle = NetworkList.subscribe(this.controller, true, this.handleStatusNotification.bind(this), this.getStatusResponseFailed.bind(this));
    },
    
    deactivate: function(){
        Mojo.Log.info("joinu-p deactivate");
		this.passwordModel.value = "";
		this.userModel.value = "";
		this.controller.modelChanged(this.passwordModel, this);
		this.controller.modelChanged(this.userModel, this);
		if(this.subscribeHandle) {
	        this.subscribeHandle.cancel();
	    }

    },	
});
