var other_label_ssid = $L("Network name");

var other_label_connect_button = $L("Connect");
var other_label_connecting_button = $L("Connecting...");

var other_label_security_open = $L("Open");
var other_label_security_wpa = $L("WPA-personal");
var other_label_security_wep = $L("WEP");
var other_label_security_eap = $L("Enterprise");

var other_hintText = $L("enter network name...");

//var other_label_security = $L("Security");

JoinotherAssistant = Class.create({
    security: [{
        label: other_label_security_open,
        value: "open"
    }, {
        label: other_label_security_wpa,
        value: "wpa-personal"
    }, {
        label: other_label_security_wep,
        value: "wep"
    }, {
        label: other_label_security_eap,
        value: "enterprise"
    }],
    
    selectedSecurity: "open",
    
    ssidAttributes: {
		textFieldName: "ssid",
		hintText: other_hintText,
        property: 'value',
        multi: false,
        label: other_label_ssid,
		changeOnKeyPress: true,
		textReplacement: false,
		requiresEnterKey: true,
        focus: true
    },
    
    ssidModel: {
        'value': ''
    },

    initialize: function(sceneAssistant, profile){
        Mojo.Log.info("Joinother initialize");     
        
        this.sceneAssistant = sceneAssistant;
        this.controller = this.sceneAssistant.controller;
        
        if (profile) {
            this.joinProfile = profile;
        }           
    },
    
    setup: function(widget){
		Mojo.Log.info("Joinother setup");
        this.widget = widget;
        this.titleElement = this.controller.get('other_joinTitle');
        this.statusMessage = this.controller.get('other_statusMessage');
		this.warningIcon = this.controller.get('other_warningIcon');
		this.warningIcon.hide();
        
        if(this.titleElement)
            this.titleElement.innerHTML = this.titleElement.innerHTML + " " + this.joinProfile.ssid;
        
		this.joinButtonModel = {buttonLabel: other_label_connect_button};
		this.joinButton = this.controller.get('other_joinButton');
        this.controller.setupWidget('other_joinButton', {type:Mojo.Widget.activityButton}, this.joinButtonModel);
		Mojo.Event.listen(this.joinButton,'mojo-tap', this.joinNetwork.bind(this))

        this.controller.setupWidget('other_ssid_widget', this.ssidAttributes, this.ssidModel);
		$('other_ssid_widget').observe(Mojo.Event.propertyChange, this.propertyChanged.bind(this));

        this.securitySelector = this.controller.get('securitySelector');        
        this.securitySelector.observe('mojo-property-change', this.selectorChanged.bindAsEventListener(this));
        
        this.controller.setupWidget('securitySelector', {
            choices: this.security
        }, {
            value: this.selectedSecurity
        });
        
        this.subscribeHandle = NetworkList.subscribe(this.controller, true, this.handleStatusNotification.bind(this), this.getStatusResponseFailed.bind(this));
		this.validate();
    },
    
    propertyChanged: function(event){
        Mojo.Log.info("propertyChanged ", event.value);
		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);
			}
		}
    },

    selectorChanged: function(event){
        this.selectedSecurity = event.value;
        Mojo.Log.info("selectorChanged " + this.selectedSecurity);
    },
	
	setButtonState: function(state) {
		if (state) {
			this.joinButtonModel.buttonLabel = other_label_connecting_button;
//			this.joinButtonModel.disabled = true;
			this.controller.modelChanged(this.joinButtonModel);		
//			this.joinButton.mojo.activate();
		}
		else {
			this.joinButtonModel.buttonLabel = other_label_connect_button;
//			this.joinButtonModel.disabled = false;
			this.controller.modelChanged(this.joinButtonModel);
			this.joinButton.mojo.deactivate();
		}
	},

    
    joinNetwork: function(event){
		event.stop();
        this.clearStatusMessage();

		this.setButtonState(true);
		
		Mojo.Log.info("joinNetwork ", this.ssidModel.value);
//        var ssidPattern = /[a-zA-Z0-9]+/;
        if (true) {
            var profile = {
                ssid: this.ssidModel.value,
                wasCreatedWithJoinOther:true
            };

            this.joinProfile = profile;
            if (this.selectedSecurity == "open") {
                NetworkList.connect(this.controller, profile, this.handleConnect, this.handleConnectFailure.bind(this, profile));
            }
            else if (this.selectedSecurity == "enterprise"){
				profile.security = {
                    securityType: this.selectedSecurity
                }
                
                this.widget.mojo.close();
                this.sceneAssistant.controller.showDialog({
                    template: 'joinuserpassword/joinuserpassword-scene',
                    assistant: new JoinuserpasswordAssistant(this, profile)
                });
			} else {
                profile.security = {
                    securityType: this.selectedSecurity
                }
                
                this.widget.mojo.close();
                this.sceneAssistant.controller.showDialog({
                    template: 'joinpassword/joinpassword-scene',
                    assistant: new JoinpasswordAssistant(this, profile)
                });
            }
        }
        else {
        }
    },
    
    countBytes: function(string) {
        var count = 0;
        var i = 0;
        for(i = 0; i < string.length; i++) {
            if(string.charCodeAt(i) <= 128) {
                count += 1;
            } else {
                count =+ 2;
            }
        }
        return count;
    },
    
	validate: function() {		
        var ssid = this.ssidModel.value;
		Mojo.Log.info("validate ", this.ssidModel.value);
        
        if((ssid.length > 0) && (this.countBytes(ssid) <= 32)) {
            this.joinButtonModel.disabled = false;
        } else {
            this.joinButtonModel.disabled = true;
        }       
		this.controller.modelChanged(this.joinButtonModel);
    },
	
	handleStatusNotification: function(response) {		
        Mojo.Log.info("joinother 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("joinother getStatusFailed " + Object.toJSON(response));
    },

    handleConnect: function(response){
        Mojo.Log.info("joinother Trying to connect to: " + Object.toJSON(response));
    },
    
    handleConnectFailure: function(item, response){
        Mojo.Log.warn("joinother connect failed: " + Object.toJSON(response));
        this.updateStatusMessage(response.errorText);        
    },
    
    activate: function(){
        Mojo.Log.info("joinother activate");
    },
    
    deactivate: function(){
        Mojo.Log.info("joinother deactivate");
		this.ssidModel.value = "";
		if(this.subscribeHandle) {
	        this.subscribeHandle.cancel();
	    }

    },
});
