
//var config_label_ip_static = $L("Manual");
//var config_label_ip_dynamic = $L("Automatic");

var config_label_done_button = $L("Done");
var config_label_discard_button = $L("Forget network");
var config_label_connecting_button = $L("Connecting...");

//var config_label_ip_address = $L("IP address");
//var config_label_subnet = $L("Subnet address");
//var config_label_gateway = $L("Gateway");
//var config_label_dns1 = $L("DNS server #1");
//var config_label_dns2 = $L("DNS server #2");

ConfigAssistant = Class.create({

    ipAddressAttributes: {
		textFieldName: "ip",
        property: 'value',
        multi: false,
//        label: config_label_ip_address,
        focus: true,
		changeOnKeyPress: true,
		textReplacement: false,
		modifierState: Mojo.Widget.numLock
    },
    
    ipAddressModel: {
        'value': '',
		valid: false,
//        disabled: true
    },
    
    subnetAttributes: {
		textFieldName: "subnet",
        property: 'value',
        multi: false,
//       label: config_label_subnet,
		changeOnKeyPress: true,
		textReplacement: false,
		modifierState: Mojo.Widget.numLock
    },
    
    subnetModel: {
        'value': '',
		validValue: false,
//        disabled: true
    },
    
    gatewayAttributes: {
		textFieldName: "gateway",
        property: 'value',
        multi: false,
 //       label: config_label_gateway,
		changeOnKeyPress: true,
		textReplacement: false,
		modifierState: Mojo.Widget.numLock
    },
    
    gatewayModel: {
        'value': '',
		validValue: false,
//        disabled: true
    },
    
    dns1Attributes: {
		textFieldName: "dns1",
        property: 'value',
        multi: false,
//        label: config_label_dns1,
		changeOnKeyPress: true,
		textReplacement: false,
		modifierState: Mojo.Widget.numLock
    },
    
    dns1Model: {
        'value': '',
		validValue: false,
//        disabled: true
    },

    dns2Attributes: {
		textFieldName: "dns2",
        property: 'value',
        multi: false,
//        label: config_label_dns2,
		changeOnKeyPress: true,
		textReplacement: false,
		modifierState: Mojo.Widget.numLock
    },
    
    dns2Model: {
        'value': '',
		validValue: false,
//        disabled: true
    },

	keyFilter: function(c) {
		if (Mojo.Widget.numericValidation(c) || (c == 46))	{
			return true;
		}			
		return false;
	},
	
    initialize: function(profile){
        Mojo.Log.info("config initialize " + NetworkList.printProfile(profile));     
        
        if (profile) {			
            this.joinProfile = profile;
        }
    },

    setup: function(){
        Mojo.Log.info("config setup");
		
        this.ipAddressAttributes.charsAllow = this.keyFilter.bind(this);
        var ipwidget = this.controller.setupWidget('ip_widget', this.ipAddressAttributes, this.ipAddressModel);
        this.controller.get('ip_widget').observe(Mojo.Event.propertyChange, this.ipChanged.bind(this));
        
		this.subnetAttributes.charsAllow = this.keyFilter.bind(this);
        this.controller.setupWidget('subnet_widget', this.subnetAttributes, this.subnetModel);
        this.controller.get('subnet_widget').observe(Mojo.Event.propertyChange, this.subnetChanged.bind(this));

		this.gatewayAttributes.charsAllow = this.keyFilter.bind(this);
        this.controller.setupWidget('gateway_widget', this.gatewayAttributes, this.gatewayModel);
        this.controller.get('gateway_widget').observe(Mojo.Event.propertyChange, this.gatewayChanged.bind(this));

		this.dns1Attributes.charsAllow = this.keyFilter.bind(this);
        this.controller.setupWidget('dns1_widget', this.dns1Attributes, this.dns1Model);
        this.controller.get('dns1_widget').observe(Mojo.Event.propertyChange, this.dns1Changed.bind(this));

		this.dns2Attributes.charsAllow = this.keyFilter.bind(this);
        this.controller.setupWidget('dns2_widget', this.dns2Attributes, this.dns2Model);
        this.controller.get('dns2_widget').observe(Mojo.Event.propertyChange, this.dns2Changed.bind(this));

        this.titleElement = this.controller.get('joinTitle');		       
        this.titleElement.innerHTML = $L("Connected to #{networkName}").interpolate({ networkName: this.joinProfile.ssid.escapeHTML() });;
        
        this.discardButton = this.controller.get('discardButton');
		this.controller.setupWidget('discardButton', {}, {buttonLabel: config_label_discard_button, buttonClass: "negative"});
        Mojo.Event.listen(this.discardButton,'mojo-tap', this.discardProfile.bind(this));

        this.ipInformation = this.controller.get('ipInformation');        
		
		this.toggleOpt = {};
    	this.toggleModel = { value: true };
        this.firstToggleValue = true;
        if(this.joinProfile.useStaticIp) { 
            if(this.joinProfile.useStaticIp == false) {
                this.disableFields();   
            } else {
                this.firstToggleValue = this.toggleModel.value = false;
				this.enableFields();
            }
        } else {
            this.disableFields();
        }
		  
        this.controller.setupWidget('ipSelection', this.toggleOpt, this.toggleModel);		
        this.controller.get('ipSelection').observe(Mojo.Event.propertyChange, this.selectorChanged.bind(this));
		
		this.joinButtonModel = {buttonLabel: config_label_done_button};		
        this.controller.setupWidget('joinButton', {type:Mojo.Widget.activityButton}, this.joinButtonModel);
		this.joinButton = this.controller.get('joinButton');
		Mojo.Event.listen(this.joinButton,'mojo-tap', this.joinNetwork.bind(this))
		
        var appMenuModel = {
            visible: true,
            items: [Mojo.Menu.editItem, Mojo.Menu.helpItem]
        };
        this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);

		this.setFields(true);
		this.staticIpChanges = false;

		this.subscribeHandle = NetworkList.subscribe(this.controller, true, this.handleStatusNotification.bind(this), this.getStatusResponseFailed.bind(this));
    },
	
	setButtonState: function(state) {
		if (state) {
			this.joinButtonModel.buttonLabel = config_label_connecting_button;
//			this.joinButtonModel.disabled = true;
			this.controller.modelChanged(this.joinButtonModel);		
			this.joinButton.mojo.activate();
		}
		else {
			this.joinButtonModel.buttonLabel = config_label_done_button;
//			this.joinButtonModel.disabled = false;
			this.controller.modelChanged(this.joinButtonModel);
			this.joinButton.mojo.deactivate();
		}
	},

    handleStatusNotification: function(response) {
        Mojo.Log.info("config handleStatus " + Object.toJSON(response));
		
		if (response.status == 'serviceDisabled') {
			Mojo.Controller.stageController.popScenesTo('networklist');
		} 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.connecting) {                                    
                                    Mojo.Controller.stageController.popScenesTo('networklist');
                                }
                                else {
//                                    this.updateStatusMessage(item.lastConnectError);
                                }
								
								this.setButtonState(false);
                                break;
							case 'ipConfigured':
								this.joinProfile.ipInfo = response.ipInfo;
								this.setFields(false);
								this.staticIpChanges = false;
								break;	
                            case 'associationFailed':
//                               this.updateStatusMessage(item.lastConnectError);
								this.setButtonState(false);
                                break;
							case 'notAssociated':
								if(this.discard == true) {
									delete this.joinProfile.profileId;
									Mojo.Controller.stageController.popScenesTo('networklist');
								}
								break;
                        };
                        break;
                };
            }
        }
    },
	  
    handleConnect: function(response){

    },
    
    handleConnectFailure: function(item, response){
        Mojo.Log.warn("config connect failed: " + Object.toJSON(response));
    },
	    
    propertyChanged: function(event){
		this.staticIpChanges = true;
		// regular expression for a valid ip address.
		var pattern = new RegExp('^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$');
        return (pattern.test(event.value));
    },

    discardProfile: function() {
		if (!this.discard) {
			this.discard = true;
			NetworkList.discardProfile(this.controller, this.joinProfile, this.discardSuccess.bind(this, this.joinProfile), this.discardFail.bind(this, this.joinProfile));
		}  
    },
    	
	ip4Class: function(ipAddress) {
		if (ipAddress) {
			var patternA = new RegExp('^(0?[0-9]?[0-9]|1[0-1][0-9]|12[0-7])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$');
			var patternB = new RegExp('^(12[8-9]|1[3-8][0-9]|19[0-1])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$');
			var patternC = new RegExp('^(19[2-9]|2[0-1][0-9]|22[0-3])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$');
			if (patternA.test(ipAddress)) {
				return 'A';
			}
			if (patternB.test(ipAddress)) {
				return 'B';
			}
			if (patternC.test(ipAddress)) {
				return 'C';
			}
		}
		return 'F';
	},
	
	ipChanged: function(event){
		this.ipAddressModel.validValue = "" ? false : this.propertyChanged(event);
		this.validate();
		if(this.ipAddressModel.validValue == true && 
			(this.subnetModel.value == "0.0.0.0" || this.subnetModel.value == "")) {
			var ipClass = this.ip4Class(this.ipAddressModel.value);
			Mojo.Log.warn("ipChanged: " + ipClass);
			if(ipClass == 'A') {
				this.subnetModel.value = "255.0.0.0";	
				this.subnetModel.validValue = true;
			} else if(ipClass == 'B') {
				this.subnetModel.value = "255.255.0.0";
				this.subnetModel.validValue = true;
			} else if(ipClass == 'C') {
				this.subnetModel.value = "255.255.255.0";
				this.subnetModel.validValue = true;
			}
			this.controller.modelChanged(this.subnetModel);
		}
	},
    subnetChanged: function(event){
        this.subnetModel.validValue = event.value == "" ? true : this.propertyChanged(event);
		this.validate();
    },
    gatewayChanged: function(event){
        this.gatewayModel.validValue = event.value == "" ? true : this.propertyChanged(event);
		this.validate();
    },
    dns1Changed: function(event){
        this.dns1Model.validValue = event.value == "" ? true : this.propertyChanged(event);
		this.validate();
    },
    dns2Changed: function(event){
        this.dns2Model.validValue = event.value == "" ? true : this.propertyChanged(event);
		this.validate();
    },
		
	validate: function() {
		Mojo.Log.info("validate ", this.toggleModel.value, this.ipAddressModel.validValue, this.subnetModel.validValue, this.gatewayModel.validValue, this.dns1Model.validValue, this.dns2Model.validValue);
		if (this.toggleModel.value == false) {
			if (this.ipAddressModel.validValue && this.subnetModel.validValue &&
					this.gatewayModel.validValue && this.dns1Model.validValue &&
					this.dns2Model.validValue) {
				this.joinButtonModel.disabled = false;
			}
			else {
				this.joinButtonModel.disabled = true;
			}
		} else {
			this.joinButtonModel.disabled = false;
		}
		
		this.controller.modelChanged(this.joinButtonModel);
	},
		
    getFields: function(){		
	    if (!this.joinProfile.ipInfo) {
	        this.joinProfile.ipInfo = {};
	    }		
        this.joinProfile.ipInfo.ip = this.ipAddressModel.value;
        this.joinProfile.ipInfo.subnet = this.subnetModel.value;
        this.joinProfile.ipInfo.gateway = this.gatewayModel.value;
        this.joinProfile.ipInfo.dns1 = this.dns1Model.value;
        this.joinProfile.ipInfo.dns2 = this.dns2Model.value;
        
        Mojo.Log.info("getFields " + Object.toJSON(this.joinProfile.ipInfo));
    },
    
    setFields: function(firstTime){
		Mojo.Log.info("setFields " + Object.toJSON(this.joinProfile.ipInfo));
		if (this.joinProfile.ipInfo) {
            if (this.joinProfile.ipInfo.ip) 
                this.ipAddressModel.value = this.joinProfile.ipInfo.ip;
            if (this.joinProfile.ipInfo.subnet) 
                this.subnetModel.value = this.joinProfile.ipInfo.subnet;
            if (this.joinProfile.ipInfo.gateway) 
                this.gatewayModel.value = this.joinProfile.ipInfo.gateway;
            if (this.joinProfile.ipInfo.dns1) 
                this.dns1Model.value = this.joinProfile.ipInfo.dns1;
            if (this.joinProfile.ipInfo.dns2) 
                this.dns2Model.value = this.joinProfile.ipInfo.dns2;
        }

		this.ipChanged(this.ipAddressModel);
		this.subnetChanged(this.subnetModel);
		this.gatewayChanged(this.gatewayModel);
		this.dns1Changed(this.dns1Model);
		this.dns2Changed(this.dns2Model);

//		if (!firstTime) {
			this.updateFieldModels();
//		}
		
    },
    
    enableFields: function(){
       this.ipAddressModel.disabled = false;
       this.subnetModel.disabled = false;
       this.gatewayModel.disabled = false;
       this.dns1Model.disabled = false;
       this.dns2Model.disabled = false;
		
		this.updateFieldModels();
		//this.ipInformation.show();
    },
    
    disableFields: function(){
		//this.ipInformation.hide();
		
       this.ipAddressModel.disabled = true;
       this.subnetModel.disabled = true;
       this.gatewayModel.disabled = true;
       this.dns1Model.disabled = true;
       this.dns2Model.disabled = true;
		
		this.updateFieldModels();
    },

    updateFieldModels: function() {
        this.controller.modelChanged(this.ipAddressModel);
        this.controller.modelChanged(this.subnetModel);
        this.controller.modelChanged(this.gatewayModel);
        this.controller.modelChanged(this.dns1Model);
        this.controller.modelChanged(this.dns2Model);
	},
	
    selectorChanged : function(e) {		
		Mojo.Log.info("selectorChanged ", e.value, this.toggleModel.value);
//        this.toggleModel.value = e.value;
        if(this.toggleModel.value == true) {
            this.disableFields();
            if (this.joinProfile.ipInfo && this.joinProfile.ipInfo.ip) {
				this.ipAddressModel.value = this.joinProfile.ipInfo.ip;
				this.subnetModel.value = this.joinProfile.ipInfo.subnet;
			}
			
        } else {
            this.enableFields();
            // clear the ip address.
            this.ipAddressModel.value = "";
			this.subnetModel.value = "";    
        }	
		
        this.controller.modelChanged(this.subnetModel);
        this.controller.modelChanged(this.ipAddressModel);
		this.ipChanged(this.ipAddressModel);
		this.subnetChanged(this.subnetModel);
		this.validate();
    },

    discardSuccess: function(item, response) {
        Mojo.Log.info("discard success " + Object.toJSON(response));
    },

    discardFail: function(item, response) {
        Mojo.Log.warn("discard fail " + Object.toJSON(response));
        Mojo.Controller.stageController.popScenesTo('networklist');
    },

	cancelDialog: function() {
        Mojo.Log.info("cancel changes ");
        Mojo.Controller.stageController.popScenesTo('networklist');
	},

    joinNetwork: function(event){
        this.getFields();       
		
		if ((this.firstToggleValue == true && this.toggleModel.value == true) || this.staticIpChanges == false) {
		 	this.cancelDialog();
		} else {

			this.setButtonState(true);
			this.joinProfile.useStaticIp = !this.toggleModel.value;
			
			NetworkList.connect(this.controller, this.joinProfile, this.handleConnect.bind(this, this.joinProfile), this.handleConnectFailure.bind(this, this.joinProfile));
			this.connecting = true;
		}
    },
	
    getStatusResponseFailed: function(response) {
        Mojo.Log.warn("joinconfig getStatusFailed " + Object.toJSON(response));
    },

	handleCommand: function(event) {
		if(event.type == Mojo.Event.command) {
			if (event.command == Mojo.Menu.helpCmd) {
				Event.stop(event);
				var openParams = {
					target: 'http://help.palm.com/wifi/index.html'
				};
				this.controller.serviceRequest('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {
						id: 'com.palm.app.help',
						params: openParams
					}
				});
			}
		} else if (event.type == Mojo.Event.commandEnable && 
		         (event.command == Mojo.Menu.helpCmd)) {
			event.stopPropagation();
		}
	},

    
    activate: function(){
        Mojo.Log.info("joinconfig activate");        
    },
    
    deactivate: function(){
        Mojo.Log.info("joinconfig deactivate");
        this.ipAddressModel.value = "";
        this.subnetModel.value = "";
        this.gatewayModel.value = "";
        this.dns1Model.value = "";
        this.dns2Model.value = "";
		if(this.subscribeHandle) {
	        this.subscribeHandle.cancel();
	    }

    },

//    toggleAttrs : {
//        choices : [
//            {label : config_label_ip_dynamic, value : 1},
//            {label : config_label_ip_static, value : 2},
//        ]
//    },
//    
//    toggleModel : {
//        value : 2,
//    }
	

});
