
var list_label_toggle_on = $L("On");
var list_label_toggle_off = $L("Off");
var list_label_list_other_network = $L("Join other network");
var list_label_list_network = $L("Join network");

var list_label_status_connecting = $L("Connecting...");
var list_label_status_association_failed = $L("Association failed.");
var list_label_status_ip_failed = $L("IP configuration failed.");
var list_label_status_server_cert_required = $L("Server certificate required.");

var list_label_status_connection_failed = $L("Unable to connect. Try again.");
var list_label_status_connection_lost = $L("You were disconnected from the Wi-Fi network.");
var list_label_error_username_password = $L("Username or password is invalid.");
var list_label_error_certificate = $L("You need a security certificate to join this network. Contact your network administrator.");
var list_label_error_not_found = $L("No network of that name with that security setting was found.");


////////////////////////////  lastConnectError //////////////////////
var label_status_message_unknown = list_label_status_connection_failed;                    	/*< Connection failed/disconnected reason unknown */
var label_status_message_internal = list_label_status_connection_failed;                   	/*< Supplicant/dhclient got terminated while connecting */
var label_status_message_connectiontimeout = list_label_status_connection_failed;          	/*< Did not get connected before timeout */
var label_status_message_linkloss = list_label_status_connection_lost;                     	/*< Lost connection to the access point */
var label_status_message_apnotfound = list_label_error_not_found;                   		/*< Cannot find specified access point to connect to */
//var label_status_message_disconnectrequest = no error            			/*< User requested disconnect */
var label_status_message_dhcpfailure = list_label_status_connection_failed;         		/*< Failed to receive DHCP OFFER */
var label_status_message_ipconflict = list_label_status_connection_failed;          		/*< Static IP causes conflict */
var label_status_message_incorrectpasskey = list_label_error_username_password;             /*< Incorrect passphrase/key provided */
var label_status_message_invalidcertificate = list_label_error_certificate;            		/*< Enterprise: Bad/expired certificate */
var label_status_message_identityrequired = list_label_error_username_password;             /*< Enterprise: need a userId to connect */
var label_status_message_passwordrequired = list_label_error_username_password;            	/*< Enterprise: need password to connect */
var label_status_message_servercertificaterequired = list_label_error_certificate;     		/*< Enterprise: need server cert to connect */
var label_status_message_clientcertificaterequired = list_label_error_certificate;    		/*< Enterprise: need client cert to connect */
var label_status_message_incorrectpassword = list_label_error_username_password;            /*< Enterprise: incorrect password provided */

////////////////////////////  errorText //////////////////////
//var label_status_message_badargument = $L("BadArgument");              /**< Argument(s) contain invalid value */
//var label_status_message_badpasskey = $L("BadPassKey");               /**< Passkey too short/long */
//var label_status_message_badjsonstring = $L("BadJsonString");            /**< Failed to parse JSON string */
//var label_status_message_notpermitted = $L("NotPermitted");             /**< Operation not allowed (disabled) */
//var label_status_message_batterytoolow = $L("BatteryTooLow");            /**< Operation not allowed (low battery) */
//var label_status_message_alreadyenabled = $L("AlreadyEnabled");           /**< service already enabled */
//var label_status_message_alreadydisabled = $L("AlreadyDisabled");          /**< service already disabled */
//var label_status_message_profilenotfound = $L("ProfileNotFound");          /**< profile not found based on ID */
//var label_status_message_profilealreadyexists = $L("ProfileAlreadyExists");     /**< profile already exists */
//var label_status_message_drivererror = $L("DriverError");              /**< WiFi driver returned error */
//var label_status_message_noapfound = $L("NoApFound");                /**< No AP within range (during scan) */ 

var NetworklistAssistant = Class.create({
//    ipInfo: {},
    emptyListItem: {emptylist:true, spinning:true},
	
    initialize: function(params){
		console.log("THIS IS THE FIRST TIME INITIALIZE IS GETTING CALLED *******************************************************");
		var timing = Mojo.Timing;
		timing.resume('scene#networklist#initialize');
        this.wifiNetworkInfoList = new Array();
		this.wifiNetworkInfoList.push(this.emptyListItem);
		Mojo.Log.info("initialized " + Object.toJSON(params));
		if (params.target) {
            this.params = params;
        }
		this.findNetworksHandle = undefined;
		this.displayOn = true;
		this.appFocus = true;
		timing.pause('scene#networklist#initialize');
    },
    
    subscribeWifiCallback: function(result){
		var timing = Mojo.Timing;
		timing.resume('scene#networklist#subscribewifi');

        Mojo.Log.info("Mojo Service Wifi state " + result.connected);
        if (result.connected == true) {
    			Mojo.Event.listen(this.controller.document, Mojo.Event.deactivate, this.onBlur.bind(this), false);
    			Mojo.Event.listen(this.controller.document, Mojo.Event.activate, this.onFocus.bind(this), false);

            // Subscribe to network status
          this.subscription = NetworkList.subscribe(this.controller, true, this.handleStatusNotification.bind(this), this.getStatusResponseFailed.bind(this));
            this.startWifiSubscription();
        }
        else {
            this.stateDisabled();
			if (this.subscription) {
            	this.subscription.cancel();
			}

			this.cancelWifiSubscription();
        }
		timing.pause('scene#networklist#subscribewifi');
    },
    

    setup: function(){
		console.log("THIS IS THE FIRST TIME SETUP IS GETTING CALLED *******************************************************");
		var timing = Mojo.Timing;
		timing.resume('scene#networklist#setup');
        Mojo.Log.info("setup");
		
        this.networkInfoListElement = this.controller.get('wifiNetworkInfoList');        
        this.networkInfoModel = {
            items: this.wifiNetworkInfoList,
			addItemLabel: list_label_list_network
        };
        
        this.template = {
            itemTemplate: 'networklist/networklist-item',
            listTemplate: 'networklist/networklist-container',
            addItemLabel: list_label_list_network,
        };
        		
        this.controller.setupWidget('wifiNetworkInfoList', this.template, this.networkInfoModel);
        this.wifiNetworkInfoListWidget = this.controller.get('wifiNetworkInfoList');
        this.networkInfoListElement.observe(Mojo.Event.listAdd, this.listAddHandler.bindAsEventListener(this));
        this.networkInfoListElement.observe(Mojo.Event.listTap, this.listSelectionHandler.bindAsEventListener(this));

        
		this.onOffToggleOpt = {};
    	this.toggleModel = { value: false };
        this.controller.setupWidget('onOffToggle', this.onOffToggleOpt, this.toggleModel);		
        this.controller.get('onOffToggle').observe(Mojo.Event.propertyChange, this.selectorChangedHandler.bind(this));

        this.sleepConfigCommand = 'sleepconfig';
        var sleepConfigMenuItem = {label:$L('Sleep Settings'), command:this.sleepConfigCommand};

        var appMenuModel = {
            visible: true,
            items: [Mojo.Menu.editItem, sleepConfigMenuItem, Mojo.Menu.helpItem]
        };
        this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);
		
		//Mojo.Event.listen(this.controller.document, Mojo.Event.deactivate, this.onBlur.bind(this), false);
		//Mojo.Event.listen(this.controller.document, Mojo.Event.activate, this.onFocus.bind(this), false);
		
		var request = this.controller.serviceRequest('palm://com.palm.bus/signal', {
            method: 'registerServerStatus',
            parameters: {
                'serviceName': 'com.palm.wifi', 
				subscribe:true
            },
            onSuccess: this.subscribeWifiCallback.bind(this),
            onFailure: function(){
                Mojo.Log.info("failed to subscribe for bus signal");
            }
        });
		
		var displayRequest = this.controller.serviceRequest('palm://com.palm.display/control', {
            method: 'status',
            parameters: {subscribe:true},
            onSuccess: this.displayCallback.bind(this),
            onFailure: function(){
                Mojo.Log.info("failed to subscribe for display signal");
            }
        });

		timing.pause('scene#networklist#setup');
    },
    
	displayCallback: function(response) {
		Mojo.Log.info("displayCallback ", Object.toJSON(response));
		
		if ("event" in response) {
			if (response.event == "displayOff") {
				this.displayOn = false;
				Mojo.Log.info("wifi displayoff")
				this.cancelWifiSubscription();
				return;
			} else if (response.event == "displayOn") {
				Mojo.Log.info("wifi displayon");
				this.displayOn = true;
				this.startWifiSubscription();
			}
		}
	},
	
	cancelWifiSubscription: function() {
		if(this.findNetworksHandle && (!this.displayOn || !this.appFocus)){
			this.findNetworksHandle.cancel();
			this.findNetworksHandle = undefined;
		}
	},
	
	startWifiSubscription: function() {
		if(this.findNetworksHandle == undefined && (this.displayOn && this.appFocus)) {
			this.findNetworksHandle = NetworkList.subscribeFindNetworks(this.controller, this.findNetworksResponseSuccess.bind(this), this.findNetworksResponseFailed.bind(this));
		}
	},
	
	onBlur: function(event) {
		Mojo.Log.info("network list blur ");		
		this.appFocus = false;
		
		this.cancelWifiSubscription();
		
		if (this.wifiNetworkInfoList.first().emptylist == true) {
			this.wifiNetworkInfoList.splice(0, 1);
			this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(0, 1);
		} else if (this.wifiNetworkInfoList.last().emptylist == true) {
			this.wifiNetworkInfoList.splice(length+1, 1);
			this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(length+1, 1);
		}
	},
	
	onFocus: function(event) {
		this.appFocus = true;
		this.controller.getSceneScroller().mojo.scrollTo(undefined, 0, true);
		if (this.wifiNetworkInfoList.length > 0) {
			Mojo.Log.info("network list focus ", this.wifiNetworkInfoList.first().connectState, this.wifiNetworkInfoList.length);
			
			if (this.wifiNetworkInfoList.first().emptylist == true) {
				
			} else if (this.wifiNetworkInfoList.first().connectState == "ipConfigured") {
				var length = this.wifiNetworkInfoList.length;
				this.wifiNetworkInfoList.splice(1, length - 1);
				this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(1, length-1);
				this.wifiNetworkInfoList.push(this.emptyListItem);
				this.wifiNetworkInfoListWidget.mojo.noticeAddedItems(1, [this.emptyListItem]);
			}
			else {
				var length = this.wifiNetworkInfoList.length;
				this.wifiNetworkInfoList.clear();
				this.wifiNetworkInfoList.push(this.emptyListItem);
				this.updateModelList();
			}
		} else {
			this.wifiNetworkInfoList.push(this.emptyListItem);
			this.updateModelList();
		}
//        this.updateModelList();
//this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(1, length-1);
//this.wifiNetworkInfoListWidget.mojo.noticeAddedItems(0, [modelItem]);
 
		this.startWifiSubscription();

	},

	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.command == this.sleepConfigCommand) {
                            Mojo.Log.error("Launching sleepconfig");
                            Event.stop(event);
		            this.controller.stageController.pushScene(this.sleepConfigCommand);
                        }
		} else if (event.type == Mojo.Event.commandEnable && 
		         (event.command == Mojo.Menu.helpCmd)) {
			event.stopPropagation();
		}
	},

	activate: function(params){
        Mojo.Log.info("network list activate", Object.toJSON(params));
		
		if (params) {
            this.listSelectionHandler({
                "item": params.target
            });
        } else if(this.params) {
			this.listSelectionHandler({
                "item": this.params.target
            });
			delete this.params;
		}
    },
    
    deactivate: function(){
        Mojo.Log.info("network list deactivate");
    },
    
    cleanup: function(){
        Mojo.Log.info("cleanupViews");
        this.networkInfoListElement.update(""); //cleanup is called when this scene is popped, so you don't need to do this
    },

    selectorChangedHandler: function(e){
        Mojo.Log.info("selectorChangedHandler " + e.value + " " + this.toggleModel.value);
		
		this.toggleModel.disabled = true;
		this.controller.modelChanged(this.toggleModel);

        var toggleValue = '';
        if (e.value == true) { // on
            toggleValue = 'enabled';
//			this.stateEnabled();
        } else { // off
            toggleValue = 'disabled';
//			this.stateDisabled();
        }
        this.stateValue = toggleValue;
        NetworkList.setState(this.controller, toggleValue, this.stateResponseSuccess.bind(this), this.stateResponseFailure.bind(this));
    },

    listAddHandler: function(event){
        Mojo.Log.info("listAddHandler ");
        if (this.toggleModel.value == true) {
            this.joinOtherNetwork();
        }
    },
    
    listSelectionHandler: function(event){
		var item = event.item;
		var ssid_tapped;
	
	Mojo.Log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        
	if (item && item.ssid) {

	    //ssid_tapped=this.remember_item_tapped();
	    //ssid_tapped=item.ssid;

            //Mojo.Log.info("listSelectionHandler " + Object.toJSON(item));
            
            var profile = this.wifiProfile(item);
            Mojo.Log.info("listSelectionHandler profile: " + NetworkList.printProfile(profile));
            
            
            if (item.connectState == "ipConfigured" || item.connectState == "associated" || item.connectState == "ipFailed") {
                NetworkList.getProfile(this.controller, profile, this.getProfileConfigResponseSuccess.bind(this, this.findModelItem(profile)), this.getProfileResponseFailed.bind(this, this.findModelItem(profile)));
            } 
	    else if (profile.profileId) {
                if (item.connectState == "associationFailed") { //associationFailed
                    if (profile.security && 
		         (item.lastConnectError == 'DhcpFailure' || item.lastConnectError == 'IncorrectPasskey' ||
			  item.lastConnectError == 'IdentityRequired' || item.lastConnectError == 'PasswordRequired' ||
			  item.lastConnectError == 'ClientCertificateRequired' || item.lastConnectError == 'IncorrectPassword'
			 )
			) {
                        NetworkList.getProfile(this.controller, profile, this.getProfileResponseSuccess.bind(this, profile), this.getProfileResponseFailed.bind(this, profile));
                     } 
		    else {
			    item.status = list_label_status_connecting ;
			    ssid_tapped=this.remember_item_tapped();
			    NetworkList.connect(this.controller, {ssid: profile.ssid}, this.connectResponseSuccess.bind(this, profile), this.connectResponseFailed.bind(this, profile));

			    this.networkInfoModel.items.each(function(it){
		            	if(event.item!==it)it.status="";  //%
                            }
                            ); 

			    this.updateModelList();
			    //this.wifiNetworkInfoListWidget.mojo.noticeUpdatedItems(item.index, [item]);
			    
         	            this.highlight_list_item_tapped(ssid_tapped);
                    }
                } // associationFailed
		
		else {  


			if (item.connectState != "associating") {

				item.status = list_label_status_connecting ;

				ssid_tapped=this.remember_item_tapped();  //%
				// ssid_tapped=event.item.ssid;


				NetworkList.connect(this.controller, {
					"profileId": profile.profileId
				}, this.connectResponseSuccess.bind(this, profile), this.connectResponseFailed.bind(this, profile));
			
				this.networkInfoModel.items.each(function(it){
				      if(event.item!==it)it.status="";  //%
				    }
				    );   // no need for updating status here, just update it when state settles down.
				
				Mojo.Log.info("STATUS NIM"+ Object.toJSON(this.networkInfoModel)); //%
				Mojo.Log.info("STATUS ITEM"+ Object.toJSON(event.item)); //%
				
				this.updateModelList();

				this.highlight_list_item_tapped(ssid_tapped);
				
				//this.wifiNetworkInfoListWidget.mojo.noticeUpdatedItems(item.index, [item]);
			}
                }
            } 
	    else if (!profile.security || !profile.security.securityType) {
		item.status = list_label_status_connecting ;
		ssid_tapped=this.remember_item_tapped();
                NetworkList.connect(this.controller, profile, 
				    this.connectResponseSuccess.bind(this, profile), 
				    this.connectResponseFailed.bind(this, profile)
				    );

                this.networkInfoModel.items.each(function(it){
		             if(event.item!==it)it.status="";  //%
		}
		);   // no need for updating status here, just update it when state settles down.

		this.updateModelList();

		this.highlight_list_item_tapped(ssid_tapped);


		//this.wifiNetworkInfoListWidget.mojo.noticeUpdatedItems(item.index, [item]);
            } 
	    else {
                this.pushJoinScene(profile);
            }

        }
        else {
            Mojo.Log.info("handleSelection no item");
        }
    },

/* redundant, use event.item.ssid instead. XXX
 * using event.item.ssid doesnt "always" work, why?
 */
    remember_item_tapped: function(){

	var ssid_tapped;

	this.controller.get('wifiNetworkInfoList').descendants().each(function(n)
	{
	       if(n.hasClassName('selected')){
		  Mojo.Log.info("element ******* is" + n.innerHTML);
	          // this.wrap_me=n; //%
		  n.descendants().each(function(m)
		  {
			if (m.hasClassName('ssid')){
				Mojo.Log.info("ssid ******"+m.innerHTML);
				ssid_tapped = m.innerHTML;
			}
	          });
		  }
	}); //%

         
	 return ssid_tapped;

	},

    highlight_list_item_tapped: function(ssid){

	var ssid_tapped = ssid;

	Mojo.Log.info("highlight ssid" + ssid_tapped);

	this.controller.get('wifiNetworkInfoList').descendants().each(function(l)
	{

	    Mojo.Log.info("EQUAL *******\n\n" + l.innerHTML);


	    if(l.hasClassName('ssid')){
		 Mojo.Log.info("IS EQUAL. " + " ssid_tapped: " + ssid_tapped + " | l.innerHTML:" + l.innerHTML);
		 if(l.innerHTML===ssid_tapped){
		    // l.wrap('div',{className:'selected'});
		    //l.style.backgroundColor='Gray';
		    //l.setStyle('color:Red');
		    Mojo.Log.info("EQUAL YES *******"+ l.innerHTML);               


		    // process ancestors
		    l.ancestors().each(function(k)
		    {
			 // if(k.hasClassName('text-group')){
			 //      k.style.backgroundColor='Blue';
			 // }

			  if(k.hasClassName('palm-row')){
			  	k.className= k.className + ' selected';
			 	Mojo.Log.info("className " + k.className);
			  }


		    }
		    );
		  } // added here 1;  
		//  else  // innerHTMl not equal to ssid_nik
	        //  l.status-title.innerHTML="";
		//  Mojo.Log.info("STATUS"+l.siblings().innerHTML);
		//  Mojo.Log.info("STATUS NIM"+ this.networkInfoModel);

	    }
		   //if(l.hasClassName('status-title')Mojo.Log.info("STATUS"+l.innerHTML);
	}
	);


    },
    
    pushJoinScene: function(profile){
        if (profile.security) {
            if (profile.security.securityType != "enterprise") {
                this.joinNetworkWithPassword(profile);
            }
            else {
                this.joinNetworkWithUserNamePassword(profile);
            }
        }
    },
    
    getProfileConfigResponseSuccess: function(item, response){        
		item = response.wifiProfile;
		item.ipInfo = response.ipInfo;		
		
		Mojo.Log.info("handle get profile config " + NetworkList.printProfile(item));
		this.controller.stageController.pushScene('config', item);
    },
    
    getProfileResponseSuccess: function(item, response){
        Mojo.Log.info("handle get profile ");
        this.pushJoinScene(response.wifiProfile);
        // TODO:  what if the profile is open????   
    },
    
    getProfileResponseFailed: function(item, response){
        Mojo.Log.warn("handle failed get profile " + Object.toJSON(response));
    },
    
    connectResponseSuccess: function(item, response){
        Mojo.Log.info("connect Response: " + Object.toJSON(response));
    },
    
    connectResponseFailed: function(item, response){
        Mojo.Log.warn("connect failed: " + Object.toJSON(response));
    },


    model_status_cleanup: function(model_item){  //%
      // clear status of all items except the passed 
      // in item(assumed to be the last one connected).
      var item=model_item;
      this.networkInfoModel.items.each(function(it){
               if(item.ssid!==it.ssid){
                   Mojo.Log.info("model_status ssid model_item item: " + item.ssid+" | "+  it.ssid);
                   Mojo.Log.info("model_status status model_item item: " + item.status + " | " + it.status);    // %
                   it.status="";
               }
      }
      );
    },

    
    findNetworksResponseSuccess: function(networkList){
        Mojo.Log.info("findNetworksResponseSuccess ", Object.toJSON(networkList));
		
		if(networkList.foundNetworks){
		  var list = networkList.foundNetworks;	
		}
         
        if (list) {
            list.each(function(a){
                this.updateItemInfo(a.networkInfo); 
            }.bind(this));
        }
		
        this.wifiNetworkInfoList.each(function(a, index){
            //if was not touched then remove it.
            if (a.touch) {
                delete a.touch;  
            }
            else {
                //remove the item.                
                Mojo.Log.info("remove model item " + index + " " + Object.toJSON(a));
				this.wifiNetworkInfoList.splice(index, 1);
//				this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(index, 1);
            }
        }.bind(this));
        
		if(this.wifiNetworkInfoList.length == 0) {
			this.wifiNetworkInfoList.push(this.emptyListItem);
		}
            // cleaning up the status
            this.networkInfoModel.items.each(function(it){
			    if(!it.touch)it.status=""; //%
			    });


		this.updateModelList();
    },
    
    findNetworksResponseFailed: function(response){
        Mojo.Log.info("findNetworksResponseFailed " + Object.toJSON(response));
		this.findNetworksResponseSuccess(response);
    },
    
    updateItemInfo: function(item){
//		Mojo.Log.info("updateItemInfo");
        var modelItem = this.findModelItem(item);
        if (!modelItem) {			
			var newItem = true;
			modelItem = item;
			modelItem.displayssid = item.ssid.escapeHTML();
			modelItem.displayssid = modelItem.displayssid.replace(/ /g, '&nbsp;');
		} else {
			if (item.signalBars) {
				modelItem.signalBars = item.signalBars;
			}
			
			if (item.lastConnectError) {
				modelItem.lastConnectError = item.lastConnectError;
			}

            if (item.connectState) {
                modelItem.connectState = item.connectState;
            } 
			
			if (item.status) {
				modelItem.status = item.status;
			}
			
            if (item.securityType) {
                modelItem.securityType = item.securityType;
            } else {
                delete modelItem.securityType;
            }

			if (item.profileId) {
				modelItem.profileId = item.profileId;
			} else {
				delete modelItem.profileId;				
			}
		}
		
        if (modelItem.connectState) {
	        this.updateConnectedItemInfo(modelItem);
	//	this.model_status_cleanup(modelItem);  //%
        }
		
		modelItem.touch = true;
		// this.model_status_cleanup(modelItem);  //%
		
        Mojo.Log.info("updateItemInfo" + Object.toJSON(modelItem));
        
        if (modelItem.connectState && modelItem.connectState != "notAssociated" && modelItem.connectState != "associationFailed") {
            
            var index = this.wifiNetworkInfoList.indexOf(modelItem);
            
            // if found and not at the top remove it 
            if (index != -1 && index != 0) {
                this.wifiNetworkInfoList.splice(index, 1);
//				this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(index, 1);
            }
            
            // add it to the top if not already there.
            if (index != 0) {
//                this.controller.getSceneScroller().mojo.revealTop(0);
                this.controller.getSceneScroller().mojo.scrollTo(undefined, 0, true);
                this.wifiNetworkInfoList.splice(0, 0, modelItem);
//				this.wifiNetworkInfoListWidget.mojo.noticeAddedItems(0, [modelItem]);
            }
        }
        else if (newItem) {				
                this.wifiNetworkInfoList.push(modelItem);				
//				modelItem.index = this.wifiNetworkInfoList.indexOf(modelItem); 
//				this.wifiNetworkInfoListWidget.mojo.noticeAddedItems(modelItem.index, [modelItem]);
        }
//         else {
//			this.wifiNetworkInfoListWidget.mojo.noticeUpdatedItems(modelItem.index, [modelItem]);
//		}
			
//		Mojo.Log.info("updateItemInfo " + Object.toJSON(modelItem));
//

//	this.model_status_cleanup(modelItem);// %

    },
    
    findModelItem: function(item){
        var found;

		//don't need to cast as arry already is one
        $A(this.wifiNetworkInfoList).each(function(a, index){
//			a.index = index;
            if (a.ssid == item.ssid && a.isAdHoc == item.isAdHoc) {
                found = a;
            }
        });
        return found;
    },
    
    updateConnectedItemInfo: function(networkInfo){
        var modelItem = networkInfo;
        
	    switch (modelItem.connectState) {
	        case 'associating':
	        case 'associated':
	            modelItem.status = list_label_status_connecting ;
	            break;
	        case 'notAssociated':
	            delete modelItem.status;
	            break;
	        case 'associationFailed':
			    if(modelItem.lastConnectError == "ServerCertificateRequired") {
					modelItem.status = list_label_status_server_cert_required;
				} else if(modelItem.lastConnectError == "ApNotFound") {
					//var item = this.findModelItem(modelItem);
					var index = this.wifiNetworkInfoList.indexOf(modelItem);
					if (index != undefined) {
						this.wifiNetworkInfoList.splice(index, 1);
//						this.wifiNetworkInfoListWidget.mojo.noticeRemovedItems(index, 1);
					}	
				} else {
				   modelItem.status = list_label_status_association_failed;	
				}
	            
	            break;
	        case 'ipFailed':
	            modelItem.status = list_label_status_ip_failed;
	            break;
	        case 'ipConfigured':
	            delete modelItem.status;	            
	            break;
	        default:
			    Mojo.Log.info("default");
			    delete modelItem.status;
	            break;
	    };
//		Mojo.Log.info("updateConnectedItemInfo" + Object.toJSON(modelItem));
    },
    
    handleStatusNotification: function(response){
        Mojo.Log.info("handleStatusNotification " + Object.toJSON(response));
        switch (response.status) {
            case 'connectionStateChanged':
				this.stateEnabled();
				this.updateItemInfo(response.networkInfo);
		                //this.model_status_cleanup(response.networkInfo); //%		
                break;
                
            case 'serviceEnabled':
                this.stateEnabled();
                break;
                
            case 'serviceDisabled':
                this.stateDisabled();
                break;
                
            case 'signalStrengthChanged':
                var item = this.wifiNetworkInfoList.first();
                item.signalBars = response.signalBars;     
//				this.wifiNetworkInfoListWidget.mojo.noticeUpdatedItems(0, [item]);           
                break;
                
            default:
                Mojo.Log.info("handleStatusNotification default ");
                this.stateDisabled();
                break;
        };
		
		this.updateModelList();
    },
    
    getStatusResponseFailed: function(response){
        Mojo.Log.warn("getStatusResponseFailed " + Object.toJSON(response));
    },
    
    stateResponseSuccess: function(response){
        Mojo.Log.info("stateResponseSuccess " + Object.toJSON(response));
    },
    
    stateResponseFailure: function(response){
		this.toggleModel.disabled = false;

        Mojo.Log.warn("stateResponseFailure " + Object.toJSON(response));
        if (this.toggleModel.value == true) {
            this.toggleModel.value = false;
        }
        else {
            this.toggleModel.value = true;
        }
        this.controller.modelChanged(this.toggleModel);
    },
    
    error: function(err){
        Mojo.Log.info("error " + Object.toJSON(err));
    },
    
    stateEnabled: function(){
        if (this.stateValue != 'disabled') {
			this.toggleModel.disabled = false;
            this.toggleModel.value = true;
            this.controller.modelChanged(this.toggleModel);
            delete this.stateValue;
			this.networkInfoListElement.style.display = 'block';
			this.controller.get('wifiInfoText').style.display = 'block';
			this.controller.get('wifiOffText').style.display = 'none';
        }
    },
    
    stateDisabled: function(){
        if (this.stateValue != 'enabled') {
			this.toggleModel.disabled = false;
            this.toggleModel.value = false;
			this.controller.modelChanged(this.toggleModel);

            this.wifiNetworkInfoList.clear();
			this.wifiNetworkInfoList.push(this.emptyListItem);            
            this.updateModelList();
			
            this.controller.getSceneScroller().mojo.scrollTo(undefined, 0, true);
			
            delete this.stateValue;
			this.networkInfoListElement.style.display = 'none';
			this.controller.get('wifiInfoText').style.display = 'none';
			this.controller.get('wifiOffText').style.display = 'block';
        }
    },
    
    updateList: function(){
//        Mojo.Log.info("updateList");

        Mojo.Log.info("ELEMENT is" + event.findElement('item'));

        NetworkList.findNetworks(this.controller, this.findNetworksResponseSuccess.bind(this), this.findNetworksResponseFailed.bind(this));
    },
    
    updateModelList: function(){
//        Mojo.Log.info("updateModelList");
          this.controller.modelChanged(this.networkInfoModel); //%  
    },
    
    wifiProfile: function(networkInfo){
        var profile = {
            ssid: networkInfo.ssid,
            isAdHoc: networkInfo.isAdHoc,
            profileId: networkInfo.profileId,
        };
        
        if (networkInfo.securityType) {
            profile.security = {
                securityType: networkInfo.securityType
            };
        };
        
        return profile;
    },
    
    joinOtherNetwork: function() {
        this.controller.showDialog({
            template: 'joinother/joinother-scene',
            assistant: new JoinotherAssistant(this)
        });
    },

    joinNetworkWithPassword: function(item) {
        this.controller.showDialog({
            template: 'joinpassword/joinpassword-scene',
            assistant: new JoinpasswordAssistant(this, item)
        });
    },
    
    joinNetworkWithUserNamePassword: function(item) {
        this.controller.showDialog({
            template: 'joinuserpassword/joinuserpassword-scene',
            assistant: new JoinuserpasswordAssistant(this, item)
        });
    },

});

