
var pass_label_password = $L("Password");
var pass_label_signin_button = $L("Sign in");
var pass_label_signingin_button = $L("Signing in...");

var pass_hintText = $L("enter password...");

JoinpasswordAssistant = Class.create({

	passwordAttributes: {
		textFieldName: "passKey",
		hintText: pass_hintText,
		property: 'value',
		label: pass_label_password,
		changeOnKeyPress: true,
		requiresEnterKey: true,
		focus: true
	},
	passwordModel: {
    	'value': ''
	},

    initialize: function(sceneAssistant, profile){
        Mojo.Log.info("joinpass initialize " + NetworkList.printProfile(profile));     
        
        this.sceneAssistant = sceneAssistant;
        this.controller = this.sceneAssistant.controller;
        
        if (profile) {
            this.joinProfile = profile;
        }           
    },

    setup: function(widget) {
        this.widget = widget;
        this.titleElement = this.controller.get('pass_joinTitle');
        this.statusMessage = this.controller.get('pass_statusMessage');
		this.warningIcon = this.controller.get('pass_warningIcon');
		this.warningIcon.hide();
        
        if(this.titleElement)
            this.titleElement.innerHTML = this.titleElement.innerHTML + " " + this.joinProfile.ssid.escapeHTML();
        
		this.joinButtonModel = {buttonLabel: pass_label_signin_button};
		this.joinButton = this.controller.get('pass_joinButton');
        this.controller.setupWidget('pass_joinButton', {type:Mojo.Widget.activityButton}, this.joinButtonModel);
		Mojo.Event.listen(this.joinButton,'mojo-tap', this.joinNetwork.bind(this))
        
        this.hexValue = false;
        
        if (this.joinProfile.security && this.joinProfile.security.simpleSecurity) {
            if (this.joinProfile.security.simpleSecurity.passKey) 
                this.passwordModel.value = this.joinProfile.security.simpleSecurity.passKey;
            
            if (this.joinProfile.security.simpleSecurity.isInHex) 
                this.hexValue = this.joinProfile.security.simpleSecurity.isInHex;
        }
        
        this.controller.setupWidget('pass_password_widget', this.passwordAttributes, this.passwordModel);
		this.controller.get('pass_password_widget').observe(Mojo.Event.propertyChange, this.propertyChanged.bind(this));
		
		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)) {
			Mojo.Log.info("enter key");
			// If the submit button is enabled then create the account
			if (this.joinButtonModel.disabled == false) {
				Mojo.Log.info("simulate button press");
				this.joinNetwork(event);
			} else {
				Mojo.Log.info("disabled button");
				this.controller.get('pass_password_widget').mojo.focus();
			}
		} else {
			Mojo.Log.info("no enter key");
		}

    },
	
    joinNetwork: function(event){
		event.stop();
		this.clearStatusMessage();
		
		this.setButtonState(true);

        var profile = {
            ssid: this.joinProfile.ssid,
            profileId: this.joinProfile.profileId,
            security: {
                securityType: this.joinProfile.security.securityType,
                simpleSecurity: {
                    passKey: this.passwordModel.value,
                    isInHex: this.hexValue
                }
            }
        };
        
        if(this.joinProfile.wasCreatedWithJoinOther)
        {
            profile.wasCreatedWithJoinOther = this.joinProfile.wasCreatedWithJoinOther;
        }
        
        NetworkList.connect(this.controller, profile, this.handleConnect.bind(this, profile), this.handleConnectFailure.bind(this, profile));
    },
        
    bit40Ascii: 5,
    bit40Hex: 10,
    bit104Ascii: 13,
    bit104Hex: 26,
    
    validate: function() {
        var key = this.passwordModel.value;
		//Mojo.Log.info(key);
		var pattern = new RegExp('^[A-Fa-f0-9]*$');
		var asciiPattern = new RegExp('^[\x00-\x7F]*$');
        if(this.joinProfile.security.securityType == "wep") {            
            switch (key.length) {
                case this.bit40Ascii:
					Mojo.Log.info(asciiPattern.test(key) );
                    if (asciiPattern.test(key)) {
						this.joinButtonModel.disabled = false;
						this.hexValue = false;
					} else {
						this.joinButtonModel.disabled = true;
					}
                    break;
                case this.bit40Hex:
                    Mojo.Log.info(pattern.test(key) );
                    if( pattern.test(key) ) {
						this.joinButtonModel.disabled = false;
                        this.hexValue = true;
                    } else {
						this.joinButtonModel.disabled = true;
                        this.hexValue = false;
                    }                   
                    break;
                case this.bit104Ascii:
					Mojo.Log.info(asciiPattern.test(key) );
                    if (asciiPattern.test(key)) {
						this.joinButtonModel.disabled = false;
						this.hexValue = false;
					} else {
						this.joinButtonModel.disabled = true;
					}
                    break;
                case this.bit104Hex:
                    if( pattern.test(key) ) {
						this.joinButtonModel.disabled = false;
                        this.hexValue = true;
                    } else {
						this.joinButtonModel.disabled = true;
                        this.hexValue = false;
                    }
                    break;
                default:
					this.joinButtonModel.disabled = true;
                    this.hexValue = false;
                    break;
            }
        } else if(this.joinProfile.security.securityType == "wpa-personal") {
            this.hexValue = false;
            //Mojo.Log.info(key.length);
            if (key.length >= 8 && key.length <= 63) {
                this.joinButtonModel.disabled = false;
            } else if(key.length == 64 && pattern.test(key)) {
				this.hexValue = true;
				this.joinButtonModel.disabled = false;
			} else {
                //             this.validInfo.innerHTML = "Please enter a WPA password.";					 
				this.joinButtonModel.disabled = true;
			}
        } else {
            this.hexValue = false;
			this.joinButtonModel.disabled = true;
        }
		this.controller.modelChanged(this.joinButtonModel);
    },

	setButtonState: function(state) {
		if (state) {
			this.joinButtonModel.buttonLabel = pass_label_signingin_button;
//			this.joinButtonModel.disabled = true;
			this.controller.modelChanged(this.joinButtonModel);		
//			this.joinButton.mojo.activate();
		}
		else {
			this.joinButtonModel.buttonLabel = pass_label_signin_button;
//			this.joinButtonModel.disabled = false;
			this.controller.modelChanged(this.joinButtonModel);
			this.joinButton.mojo.deactivate();
		}
	},
	
	handleStatusNotification: function(response) {
        Mojo.Log.info("joinpass 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;
                        switch (item.connectState) {
                            case 'associated':
                                if (item.lastConnectError == undefined) {
                                    this.widget.mojo.close();
                                }
                                else {
                                    this.updateStatusMessage(item.lastConnectError);
                                }
								
								this.setButtonState(false);
                                break;
                            case 'associationFailed':
                                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) {
                l = label_status_message_unknown;
            }
        } 
        
        this.statusMessage.innerHTML = l;
		this.warningIcon.show();
    },
	
    clearStatusMessage: function(){
        this.statusMessage.innerHTML = "";
		this.warningIcon.hide();
    },

    getStatusResponseFailed: function(response) {
        Mojo.Log.warn("joinpassword getStatusFailed " + Object.toJSON(response));
    },

    error: function(err){
        var content = Mojo.View.render({
            template: 'error/error',
            object: err
        });
        this.mainElement.update(content);
    },
    
    handleConnect: function(response){
        Mojo.Log.info("joinpass Trying to connect to: ");
    },
    
    handleConnectFailure: function(item, response){
        Mojo.Log.warn("joinpass connect failed: " + Object.toJSON(response));
        this.updateStatusMessage(response.errorText);
        
    },
    
    activate: function(){
        Mojo.Log.info("joinpass activate");
        this.subscribeHandle = NetworkList.subscribe(this.controller, true, this.handleStatusNotification.bind(this), this.getStatusResponseFailed.bind(this));
    },
    
    deactivate: function(){
        Mojo.Log.info("joinpass deactivate");
		this.passwordModel.value = "";
		this.controller.modelChanged(this.passwordModel, this);
		if(this.subscribeHandle) {
	        this.subscribeHandle.cancel();
	    }
    },
});


