/* Copyright 2009 Palm, Inc.  All rights reserved. */


var TelephonyCommands = {
    svcUri: 'palm://com.palm.telephony',
    dtmfUri: 'palm://com.palm.audio/dtmf',
	displayUri: 'palm://com.palm.display/control',
	oddUri: 'palm://com.palm.oddService',
	powerUri: 'palm://com.palm.power/shutdown',
    carrierDBUri: 'palm://com.palm.data.carriernetworksettings',
	
	initRequestSent: 0,
    
    subscribe: function(name, callback){
        if (MockTelephony.useMock == 1) {
            Mojo.Controller.getAppController().assistant.mockTelephony.subscribe(name, callback);
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'subscribe',
                parameters: {
                    'events': name
                },
                onSuccess: callback,
                onFailure: function(){
					QDLogger.log( "TelephonyCommands::subscribe", "failure");
                }
            });
            this.saveRequest(request);
        }
    },
    
    unsubscribe: function(name){
        if (MockTelephony.useMock == 1) {
            Mojo.Controller.getAppController().assistant.mockTelephony.unsubscribe(name);
        }
    },
	
	callsGetAll: function(subscribe, callback) {
		var request = new Mojo.Service.Request(this.svcUri, {
			method: 'callsGetAll',
			parameters: {
				'subscribe': subscribe
			},
            onSuccess: callback,
            onFailure: function(){
				QDLogger.log( "TelephonyCommands::subscribe", "failure");
			}
		});
        this.saveRequest(request);
	},
    
	// actually just a wrapper; dials after a delay to make sure CDMA
	// data shutdown doesn't slow down reverse lookup
	
	dial: function(number, blockId, failureCb, successCb) {
		TelephonyCommands.dialAfterDelay.bind(this).delay(0.50, number, blockId, failureCb, successCb);
	},
	
    dialAfterDelay: function(number, blockId, failureCb, successCb){
        
		var strippedNumber = this.stripNonNumerics(number);
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.dial(number, blockId);
        }
        else {
            var arg;
			var params = {
					'number': strippedNumber
				}
			// Only send "block caller ID" if specifically requested to do so
           	if (blockId != undefined) {
				params.blockId = blockId;
			}
            arg = {
  				method: 'dial',
                parameters: params,
                onSuccess: function(response){
                    QDLogger.log( "TelephonyCommands::dial", "successful: " , number);
					if (successCb) {
						successCb();
					}
					this.cancelTempSaveRequest("dial");
                }.bind(this),
                onFailure: function(response){
					failureCb(response, number);
					this.cancelTempSaveRequest("dial");
				}.bind(this)
            }
            
            var request = new Mojo.Service.Request(this.svcUri, arg);
            this.tempSaveRequest("dial", request);
        }
    },
    
	// strips characters that the radio can't handle
    stripNonNumerics: function(number){
    
        var digits = "1234567890*#+";
        var out = "";
        for (i = 0; i < number.length; i++) {
            var c = number.charAt(i);
            if (digits.indexOf(c) != -1) {
                out += c;
            }
        }
        
        return out;
    },
	
	// strips characters that aren't valid for dialing at all
	normalizeNumber: function(number) {
		if (!number)  
			return "";
		
		number += "";
		
		if (number.length < 1) {
			return "";
		}
		
		number.toLowerCase();
			
		var validDigits = "+01234567890*#pwt";
		
		var out = "";
		for (var i = 0; i < number.length; i++) {
			var curDigit = number.charAt(i);
			if (validDigits.indexOf(curDigit) >= 0) {
				out += curDigit;
			}
		}
		
		// numbers starting with p or w aren't valid
		if (out.length > 0) {
			var firstDigit = out.charAt(0);
			switch (firstDigit) {
				case 'p':
				case 'w':
				case 't':
					return "";
			}
		}
		
		return out;
	},
	
	setPower: function(state, callback){
		QDLogger.log( "TelephonyCommands::setPower", state);
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'powerSet',
            parameters: {
                'state': (state ? "on" : "off")
            },
			onSuccess: callback,
			onFailure: callback
        });
        this.tempSaveRequest("powerSet", request);
        return request;
    },
    
    getPower: function(subscribe, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'powerQuery',
			parameters: {
				'subscribe': subscribe
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::getPower", "failure");
			}
        });
        this.saveRequest(request);
        return request;
    },
    
	getNetworkStatus: function(subscribe, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'networkStatusQuery',
			parameters: {
				'subscribe': subscribe
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::getNetworkStatus", "failure");
			}
        });
        this.saveRequest(request);
        return request;
    },
	
	networkSelectionModeQuery: function(callback) {
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'networkSelectionModeQuery',
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::networkSelectionModeQuery", "failure");
			}
        });
        this.tempSaveRequest("networkStatusQuery", request);
        return request;
	},
	
	// DO NOT SAVE THIS REQUEST HERE
	lockStatusSubscribe: function(callback){
        var request = new Mojo.Service.Request("palm://com.palm.systemmanager/", {
            method: 'getLockStatus',
			parameters: {
				'subscribe': true
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::lockStatusSubscribe", "failure");
			}
        });
        return request;
    },
	
	lockScreenButtonSubscribe: function(callback){
        var request = new Mojo.Service.Request("palm://com.palm.systemmanager/", {
            method: 'lockButtonTriggered',
			parameters: {
				'subscribe': true
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::lockScreenButtonSubscribe", "failure");
			}
        });
        return request;
    },
	
	deviceLockModeSubscribe: function(callback){
        var request = new Mojo.Service.Request("palm://com.palm.systemmanager/", {
            method: 'getDeviceLockMode',
			parameters: {
				'subscribe': true
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::lockStatusSubscribe", "failure");
			}
        });
        return request;
    },
	
	// DO NOT SAVE THIS REQUEST HERE
	powerButtonSubscribe: function(enable, clientName, callback) {
        var request = new Mojo.Service.Request(this.displayUri, {
            method: 'setProperty',
			parameters: {
				'powerKeyBlock': enable,
				'client': clientName
			},
			onSuccess: function(payload){
				if (callback) callback(payload);
			},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::powerButtonSubscribe", "failure");
			}
        });
      
        return request;
	},

	// DO NOT SAVE THIS REQUEST HERE
	displayStatusSubscribe: function(callback) {
        var request = new Mojo.Service.Request("palm://com.palm.display/control", {
            method: 'status',
				parameters: {'subscribe': true},
			onSuccess: function(payload){
				if (callback) callback(payload);
			},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::displayStatusSubscribe", "failure");
			}
        });
      
        return request;
	},

	// DO NOT SAVE THIS REQUEST HERE	
	wiredButtonSubscribe: function(callback){
        var request = new Mojo.Service.Request("palm://com.palm.keys/headset", {
            method: 'status',
			parameters: {
				'subscribe': true
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::wiredButtonSubscribe", "failure");
			}
        });
      
        return request;
    },
	
	// DO NOT SAVE THIS REQUEST HERE	
	sliderSubscribe: function(callback){
        var request = new Mojo.Service.Request("palm://com.palm.keys/switches", {
            method: 'status',
			parameters: {
				'subscribe': true
			},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::sliderSubscribe", "failure");
			}
        });
      
        return request;
    },
	
	// DO NOT SAVE THIS REQUEST HERE
	puckStatusSubscribe: function(callback){
		var request = new Mojo.Service.Request('palm://com.palm.bus/signal/', {
			method: 'addmatch',
			parameters: {"category":"/com/palm/power","method":"chargerStatus"},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::puckStatusSubscribe", "failure");
			}
		});
		
		return request;
	},
	
	// cause current puck status to be signaled
	chargeSignalQuery: function() {
		var request = new Mojo.Service.Request(this.svcUri, {
            method: 'chargeSourceQuery',
			onSuccess: function() {},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::chargeSignalQuery", "failure");
			}
        });
	},
    
	vibratorTurnOn: function(){
        var request = new Mojo.Service.Request("palm://com.palm.vibrate", {
            method: 'vibrate',
			parameters: {
				'period': 125,
				'duration': 500
			},
			onSuccess: function() {
				QDLogger.log( "TelephonyCommands::vibratorTurnOn", "turned on");
			},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::vibratorTurnOn", "failed to turn on");
			}
        });
        this.tempSaveRequest("vibratorTurnOn", request);
        return request;
    },
    
    answer: function(callId){
        QDLogger.log( "TelephonyCommands::answer");
        
        var shouldHangupAll = (callId === undefined);
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.answer();
        }
        else {
            QDLogger.log( "TelephonyCommands::answer", "Real call answer");
			
			// if this is the first call, route audio here			
			if (!(this.isConnected())) {
				var audioReq = new Mojo.Service.Request("palm://com.palm.audio/telephony", {
					method: 'answered',
					parameters: {
						"client": "phone app"
					},
					onSuccess: function(){
						QDLogger.log( "TelephonyCommands::answer", "audio set succeeded");
					},
					onFailure: function(){
						QDLogger.log( "TelephonyCommands::answer", "audio set failed");
					}
				});
				this.tempSaveRequest("audioreq", audioReq);
			}
            
            var request = new Mojo.Service.Request(this.svcUri, {
                method: ('answer'),
                parameters: ({
                    "id": callId
                })
            });
            this.tempSaveRequest("answer", request);
        }
    },
    
    disconnect: function(callId){
        QDLogger.log( "TelephonyCommands::disconnect", callId);
        
        var shouldHangupAll = (callId === undefined);
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.disconnect();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: (shouldHangupAll ? 'hangupAll' : 'hangup'),
                parameters: ((shouldHangupAll ? {} : {
                    "id": callId
                }))
            });
            this.tempSaveRequest("disconnect", request);
        }
    },
    
    disconnectActiveCallMmi: function(callId){
        QDLogger.log( "TelephonyCommands::disconnectActiveCallMmi", callId);
        
        var shouldHangupAll = (callId === undefined);
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.disconnect();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'hangupActiveCall',
                parameters: {
                    "id": callId
                }
            });
            this.tempSaveRequest("hangupActiveCall", request);
        }
    },
    
    disconnectCallMmi: function(callId){
        QDLogger.log( "TelephonyCommands::disconnectCallMmi", callId);
        
        var shouldHangupAll = (callId === undefined);
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.disconnect();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'hangupMMI',
                parameters: {
                    "id": callId
                }
            });
            this.tempSaveRequest("hangupMMI", request);
        }
    },
    
    disconnectConference: function(){
        QDLogger.log( "TelephonyCommands::disconnectConference");
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.disconnect();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: ('hangupAllConference'),
                parameters: ({})
            });
            this.tempSaveRequest("hangupAllConference", request);
        }
    },
    
    disconnectAllActive: function(){
        QDLogger.log( "TelephonyCommands::disconnectAllActive");
        
        //if (MockTelephony.useMock == 1) {
        //  return Mojo.Controller.getAppController().assistant.mockTelephony.disconnectConference();
        //} else {
        var request = new Mojo.Service.Request(this.svcUri, {
            method: ('hangupAllActive'),
            parameters: ({})
        });
        this.tempSaveRequest("hangupAllActive", request);
        //}
    },
    
    disconnectAllHeld: function(){
        QDLogger.log( "TelephonyCommands::disconnectAllHeld");
        
        //if (MockTelephony.useMock == 1) {
        //  return Mojo.Controller.getAppController().assistant.mockTelephony.disconnectConference();
        //} else {
        var request = new Mojo.Service.Request(this.svcUri, {
            method: ('hangupAllHeld'),
            parameters: ({})
        });
        this.tempSaveRequest("hangupAllHeld", request);
        //}
    },
    
    merge: function(){
        QDLogger.log( "TelephonyCommands::merge");
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.merge();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'conference',
                parameters: {}
            });
            this.tempSaveRequest("conference", request);
        }
    },
    
    extract: function(callId){
        QDLogger.log( "TelephonyCommands::extract");
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.extract();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'extract',
                parameters: {
                    'id': callId
                }
            });
            this.tempSaveRequest("extract", request);
            
        }
    },
    
    extractMmi: function(callId){
        QDLogger.log( "TelephonyCommands::extractMmi");
        
        if (MockTelephony.useMock == 1) {
            return Mojo.Controller.getAppController().assistant.mockTelephony.extract();
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'extractMmi',
                parameters: {
                    'id': callId
                }
            });
            this.tempSaveRequest("extractMmi", request);
            
        }
    },
    
    mute: function(state){
        QDLogger.log( "TelephonyCommands::mute");
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'mute',
            parameters: {
                'enable': state
            }
        });
    },
	
	disconnectDelaySet: function(time){
        QDLogger.log( "TelephonyCommands::disconnectDelaySet");
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'disconnectDelaySet',
            parameters: {
                'ms': time
            }
        });
    },
	
	muteRingtone: function(callback){
		QDLogger.log( "TelephonyCommands::muteRingtone");
        var request = new Mojo.Service.Request("palm://com.palm.audio/ringtone", {
            method: 'setMuted',
			parameters: {
				'muted': true
			},
			onSuccess: function() {
				QDLogger.log( "TelephonyCommands::muteRingtone", "success");
			},
			
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::muteRingtone", "failure");
			}
        });
        this.tempSaveRequest("muteRingtone", request);
        return request;
    },
    
    hold: function(){
        QDLogger.log( "TelephonyCommands::hold");
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'swap',
            parameters: {}
        });
    },
    
    resume: function(){
        QDLogger.log( "TelephonyCommands::resume");
        this.hold();
    },
    
    swap: function(){
        this.hold();
    },
    
    getCurrentState: function(callback){
        if (MockTelephony.useMock == 1) {
            Mojo.Controller.getAppController().assistant.mockTelephony.getCurrentState(callback);
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'macroCallQuery',
                onSuccess: callback
            });
            this.tempSaveRequest("macroCallQuery", request);
        }
    },
    
    checkEmergencyMode: function(callback){
        if (MockTelephony.useMock == 1) {
            Mojo.Controller.getAppController().assistant.mockTelephony.checkEmergencyMode(callback);
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: 'isTelephonyReady',
                onSuccess: callback
            });
            this.tempSaveRequest("isTelephonyReady", request);
        }
    },
    
    
    noTelephonyFailure: function(){
        Mojo.Controller.errorDialog(Messages.noTelephonyServiceError);
    },
    
    isAllDigits: function(pin){
        // TODO FIXME: we ought not call this, eh?
        return true;
    },
    
    isValidPin: function(pin){
        var ret = (pin !== undefined &&
        pin.length !== undefined &&
        pin.length >= 4 &&
        pin.length <= 8 &&
        this.isAllDigits(pin));
        if (!ret) {
            Mojo.Controller.errorDialog("Pins are 4-8 digits. Invalid :" + pin);
        }
        return ret;
    },
    
    getPin1Status: function(subscribe, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'pin1Status',
            onSuccess: callback,
            onFailure: function(response){
                Mojo.Log.info( "PhoneApp: TelephonyCommands::pin1Status failed %j", response);
            },
            parameters: {
                'subscribe': subscribe
            },
        });
		this.saveRequest(request);
    },

    deviceLockQuery: function(subscribe, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'deviceLockQuery',
            onSuccess: callback,
            onFailure: function(response){
                Mojo.Log.info( "PhoneApp: TelephonyCommands::deviceLockQuery failed %j", response);
            },
            parameters: {
                'subscribe': subscribe
            },
        });
		this.saveRequest(request);
    },
    
	sendDTMF: function(tone, feedback){
        if (MockTelephony.useMock == 1) {
        }
        else {
            var request = new Mojo.Service.Request(this.dtmfUri, {
                method: ('playDTMF'),
                parameters: ({
                    "id": tone,
					oneshot: true,
					feedbackOnly: feedback
                })
            });
        }
    },
    
    startDTMF: function(tone, feedback){
        if (MockTelephony.useMock == 1) {
        }
        else {
            var request = new Mojo.Service.Request(this.dtmfUri, {
                method: ('playDTMF'),
                parameters: ({
                    "id": tone,
					oneshot: false,
					feedbackOnly: feedback
                })
            });
        }
    },
    
    endDTMF: function(tone){
        if (MockTelephony.useMock == 1) {
        }
        else {
            var request = new Mojo.Service.Request(this.dtmfUri, {
                method: ('stopDTMF'),
                parameters: {}
            });
        }
    },
    
    exitEmergencyMode: function(){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'emergencyModeEnd',
            parameters: {}
        });
        
    },
    
	// Get the list of emergency phone numbers from the TIL
 	emergencyNumberQuery: function(callback) {
		var request = new Mojo.Service.Request(this.svcUri, {
            method: 'emergencycalllistQuery',
            onSuccess: callback,
			onFailure: function() {
				 QDLogger.log( "TelephonyCommands::emergencyNumberQuery", "failed");
			}
        });
        TelephonyCommands.tempSaveRequest("emergencycalllistQuery", request);
	},
	
	playEmergencySound: function() {
		var request = new Mojo.Service.Request(this.dtmfUri, {
			method: 'emergencyCall',
			onSuccess: function() {
				QDLogger.log( "TelephonyCommands::playEmergencySound", "success");		
			},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::playEmergencySound", "failure");
			}
		});
		TelephonyCommands.tempSaveRequest("playEmergencySound", request);
	},
	
	proxSet: function(state, callback) {
		 var request = new Mojo.Service.Request(this.displayUri, {
            method: 'setProperty',
			parameters: {
				'proximityEnabled': state,
				'client': "phoneapp"
			},
			onSuccess: function(payload){
				if (callback) callback(payload);
			},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands#proxSet", "failure");
			}
        });
      
        return request;
	},
	
    sendStkCommand: function(response){
        QDLogger.log( "TelephonyCommands::sendStkCommand", response);
        if (MockTelephony.useMock == 1) {
        }
        else {
            var request = new Mojo.Service.Request(this.svcUri, {
                method: ('stkDisplayTextResponse'),
                parameters: ({
                    "stkResponse": response
                })
            });
        }
    },
    
    
    voicemailCountQuery: function(sub, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'voicemailCountQuery',
            onSuccess: callback,
            onFailure: function(response){
                QDLogger.log( "TelephonyCommands::subscribeVoicemail", "failed.");
            },
            parameters: {
                'subscribe': sub
            },
        });
        
        this.saveRequest(request);
        
    },
    
	// don't save request here
    voicemailNumberCarrierDBQuery: function(callback){
    
        var request = new Mojo.Service.Request('palm://com.palm.data.carriernetworksettings', {
            method: 'getCurrentSettings',
			parameters:{'settings':['voicemailNumber'],"subscribe":true},
            onSuccess: function(response){
                callback(true, response.voicemailNumber)
            },
            onFailure: function(response){
                callback(false, (Messages.generalServiceError))
            }
        });
		
		return request;
		
    },
	
	voicemailNumberQuery: function(callback, subscribe){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'voicemailNumberQuery',
			parameters: {'subscribe':subscribe},
            onSuccess: function(response){
                callback(true, response.extended.number)
            },
            onFailure: function(response){
                callback(false, (Messages.generalServiceError))
            }
        });
		
		this.tempSaveRequest("voicemailNumberQuery", request);
		return request;
		
    },
	
	phoneNumberQuery: function(callback){
    
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'phoneNumberQuery',
            onSuccess: function(response){
                callback(true, response.extended.number)
            },
            onFailure: function(response){
                callback(false, (Messages.generalServiceError))
            }
        });
		this.tempSaveRequest("phoneNumberQuery", request);
    },
    
    /** audio **/
    subscribeAudioRouting: function(callback){
        Mojo.Controller.getAppController().assistant.audioEnabledProfiles = new Object();
        // Subscribe to audio notifications
        
        var request = new Mojo.Service.Request("palm://com.palm.audio/phone/status", {
            parameters: {
                subscribe: true
            },
            onSuccess: callback
        });
        this.tempSaveRequest("subscribeAudioRoutingStatus", request);
        
        // Get the list of available audio scenarios now
        request = new Mojo.Service.Request("palm://com.palm.audio/phone/listScenarios", {
            parameters: {
                enabled: true
            },
            onSuccess: callback
        });
        this.tempSaveRequest("subscribeAudioRoutingList", request);
    },
    
    setAudioScenario: function(scenario){
        var request = new Mojo.Service.Request("palm://com.palm.audio/phone/setCurrentScenario", {
            parameters: {
                scenario: scenario
            }
        });
        this.tempSaveRequest("setAudioScenario", request);
    },
    
    getPlatformType: function(successCB, failureCB){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'platformQuery',
            onSuccess: successCB,
            onFailure: failureCB,
        });
		
		this.tempSaveRequest("getPlatformType", request);
    },
    
	// TODO: CLEAN THIS UP!
    saveRequest: function(request){
        if (!Mojo.Controller.getAppController().assistant.telephonyEventListener.requestSaver) {
            Mojo.Controller.getAppController().assistant.telephonyEventListener.requestSaver = [];
        }
        Mojo.Controller.getAppController().assistant.telephonyEventListener.requestSaver.push(request);
    },
    
    tempSaveRequest: function(key, request){
        if (!Mojo.Controller.getAppController().assistant.telephonyEventListener.tempRequestSaver) {
            Mojo.Controller.getAppController().assistant.telephonyEventListener.tempRequestSaver = {};
        }
        
        Mojo.Controller.getAppController().assistant.telephonyEventListener.tempRequestSaver[key] = request;
    },
	
	cancelTempSaveRequest: function(key) {
		var req = Mojo.Controller.getAppController().assistant.telephonyEventListener.tempRequestSaver[key];
		if (req) {
			req.cancel();
			Mojo.Controller.getAppController().assistant.telephonyEventListener.tempRequestSaver[key] = undefined;
		}
	},
	
	cancelSavedRequests: function() {
		var saver = Mojo.Controller.getAppController().assistant.telephonyEventListener.requestSaver;
		if (saver) {
			while (saver.length > 0) {
				var req = saver.pop();
				if (req) {
					req.cancel();
					delete req;
				}		
			}
		}
	},
	
	isConnected: function() {
		return Mojo.Controller.getAppController().assistant.telephonyEventListener.isConnected();
	},
    
    /*
     * Send the USSD code and display the result
     */
    sendUSSD: function(dialString, msgCb){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'sendUssd',
            parameters: {
                code: dialString
            },
            onSuccess: function(response){
                msgCb(Messages.ussdSuccess);
            },
            onFailure: function(response){
                if (Messages.serviceErrors[response.errorCode]) 
                    msgCb(Messages.ussdError + Messages.serviceErrors[response.errorCode]);
                else 
                    msgCb(Messages.ussdError);
            }
        });
        
    },
    
    /* CDMA programming related activities
     */
    verifyMsl: function(mslValue, callback){
    
        if (!mslValue) 
            return;
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'programModeEnter',
            onSuccess: function(response){
                QDLogger.error("TelephonyCommands#verifyMsl", "entering program mode successfully.");
                callback(true);
            },
            onFailure: function(response){
                QDLogger.error("TelephonyCommands#verifyMsl", "invalid MSL, but radio is now off");
                callback(false);
            },
            parameters: {
                "msl": mslValue
            },
        });
		this.tempSaveRequest("verifyMsl",request);
    },
    
    getActivationInfo: function(responseCallback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'activationInfoQuery',
            onSuccess: function(response){
                responseCallback(true, "success", response.extended.mdn, response.extended.msid);
            },
            onFailure: function(response){
                responseCallback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "", "");
            },
        });
		this.tempSaveRequest("actinfo",request);
    },
    
    setActivation: function(mdn, msid, callback){
        QDLogger.log( "TelephonyCommands::setActivation", mdn  , msid);
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'activationInfoSet',
            onSuccess: function(response){
                callback(true, "");
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError));
            },
            parameters: {
                mdn: mdn,
                msid: msid
            },
        });
		
		this.tempSaveRequest("setActivation",request);
        
    },
    
    exitProgramMode: function(handler){
    
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'programModeExit',
            onSuccess: function(response){
				if(handler)
               		handler(true, "success");
            },
            onFailure: function(response){
				if(handler)
               		handler(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError));
            },
        });
		
		this.tempSaveRequest("exitProgramMode",request);
    },
    
    enterProgramMode: function(msl, callback){
    
        //Call the Mojo Service to set the MSL
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'programModeEnter',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError));
            },
            parameters: {
                "msl": msl
            },
        });
		
		this.tempSaveRequest("enterProgramMode",request);
    },
    
    setAkey: function(akey, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'akeySet',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false, (Messages.akeyError[response.errorCode] 
					|| Messages.serviceErrors[response.errorCode] || Messages.generalServiceError));
            },
            parameters: {
                "akey": akey
            },
        });
		
		this.tempSaveRequest("setAkey",request);
        
    },
	
	setOmadmUrl: function(msl, url, callback){
        var request = new Mojo.Service.Request("luna://com.palm.provisioning", {
            method: 'SetURL',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false, (Messages.generalServiceError));
            },
            parameters: {
                "URL": url,
				"MSL": msl
            },
        });
		
		this.tempSaveRequest("setOmadmUrl",request);
    },
   
    getOmadmUrl: function(callback){
        var request = new Mojo.Service.Request("luna://com.palm.provisioning", {
            method: 'GetURL',
            onSuccess: function(response){
                callback(response);
            },
            onFailure: function(response){
                QDLogger.log( "TelephonyCommands::getOmadmUrl failed");	
            }
        });
		
		this.tempSaveRequest("getOmadmUrl",request);
        
    },
    
    setPrev: function(prev, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'protocolRevisionSet',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError));
            },
            parameters: {
                revision: parseInt(prev)
            },
        });
		
		this.tempSaveRequest("setPrev",request);
    },
    
    setVoicePrivacy: function(enable, msgCb){
        var message;
        
        if (enable) 
            message = Messages.voicePrivacyOn;
        else 
            message = Messages.voicePrivacyOff;
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'voicePrivacySet',
            onSuccess: function(response){
                msgCb(message);
            },
            onFailure: function(response){
				
                msgCb(Messages.serviceErrors[response.errorCode] || Messages.generalServiceError);
            },
            parameters: {
                "enable": enable
            },
        });
		
		this.tempSaveRequest("voicePrivacySet",request);
    },
	
	setAudEq: function(enable){
        var message;
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'museSet',
            onSuccess: function(response){
                QDLogger.log( "TelephonyCommands::museSet succeeded");
            },
            onFailure: function(response){
				QDLogger.error( "TelephonyCommands::museSet failed");
            },
            parameters: {
                "enable": enable
            },
        });
		
		this.tempSaveRequest("museSet",request);
    },
    
    /*
     * tty functions
     */
    ttyQuery: function(callback){
    
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'ttyQuery',
            onSuccess: function(response){
                callback(true, "success", response.extended.mode);
                
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
        });
		this.tempSaveRequest("tty",request);
    },
    
    ttySet: function(ttyMode, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'ttySet',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false(Messages.serviceErrors[response.errorCode] || Messages.generalServiceError));
            },
            parameters: {
                mode: ttyMode
            },
        });
		
		this.tempSaveRequest("ttySet",request);
    },
    
    /*
     * evdo functions
     */
    evdoQuery: function(callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'evdoDataModeQuery',
            onSuccess: function(response){
                callback(true, "success", response.extended.mode);
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
        });
		this.tempSaveRequest("evdo",request);
    },
    
    evdoSet: function(evdoMode, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'evdoDataModeSet',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
            parameters: {
                mode: evdoMode
            },
        });
		
		this.tempSaveRequest("evdoSet",request);
    },
	
	resetRadio: function(callback) {
		var request = new Mojo.Service.Request(this.svcUri, {
            method: 'resetRadio',
            onSuccess: function(response){
                callback(true, "success");
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },            
        });
		
		this.tempSaveRequest("resetRadio",request);
	},
	
	/*
     * RTN Info Query functions
     */
    rtnQuery: function(callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'returnInfoQuery',
            onSuccess: function(response){
                callback(true, "success", response.extended);
            },
            onFailure: function(response){
                callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
        });
		this.tempSaveRequest("rtn",request);
    },
	
	versionOsQuery: function(callback) {
		var request = new Mojo.Service.Request("palm://com.palm.preferences/systemProperties", {
            method: 'Get',
			parameters: {"key":"com.palm.properties.version"},
            onSuccess: function(response) {
				if (response && response["com.palm.properties.version"]) {
					callback( response["com.palm.properties.version"])
				} else {
					QDLogger.log( "TelephonyCommands::versionOsQuery", "not found");	
				}
			},
            onFailure: function(){
               QDLogger.log( "TelephonyCommands::versionOsQuery", "failure");
            },
        });
		this.tempSaveRequest("versionOsQuery",request);
	},
		
	versionFirmwareQuery: function(callback) {
		var request = new Mojo.Service.Request(this.svcUri, {
            method: 'modemfirmwareversionQuery',
            onSuccess: function(response) {
				if (response && response.extended && response.extended.value) {
					callback(response.extended.value);
				} else {
					QDLogger.log( "TelephonyCommands::versionCustomizationQuery", "not found");	
					callback("unknown");
				}
			},
            onFailure: function(){
               QDLogger.log( "TelephonyCommands::versionCustomizationQuery", "failure");
			   callback("unknown");
            },
        });
		this.tempSaveRequest("versionFirmwareQuery",request);
	},
	
	hardwareRevisionQuery: function(callback) {
		var request = new Mojo.Service.Request("palm://com.palm.preferences/systemProperties", {
            method: 'Get',
			parameters: {"key":"com.palm.properties.HWoRev"},
            onSuccess: function(response) {
				if (response && response["com.palm.properties.HWoRev"]) {
					callback( response["com.palm.properties.HWoRev"])
				} else {
					QDLogger.error( "TelephonyCommands::hardwareRevisionQuery", "not found");	
				}
			},
            onFailure: function(){
               QDLogger.error( "TelephonyCommands::hardwareRevisionQuery", "failure");
            },
        });
		this.tempSaveRequest("hardwareRevisionQuery",request);
	},
	
	getCarrierName: function(callback) {
		QDLogger.log("getCarrierName");
		var request = new Mojo.Service.Request(this.carrierDBUri, {
			method: 'getCarrierName',
			parameters: {},
			onSuccess: callback,
			onFailure: callback,
	    });	
		this.tempSaveRequest("getCarrierName",request);
	},
	
	radioDefaultsRestore: function(rtnMode,msl, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'radioDefaultsRestore',
            onSuccess: function(response){
				if(callback)
                	callback(true, "success");
            },
            onFailure: function(response){
				if(callback)
               	 callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
            parameters: {
                mode: rtnMode,
				msl : msl				
            },
        });
		
		this.tempSaveRequest("radioDefaultsRestore",request);
    },
	
	wipeDevice: function() {
		 QDLogger.log( "TelephonyCommands::wipeDevice");
		 var request = new Mojo.Service.Request("palm://com.palm.storage/erase", {
            method: 'EraseAll',
            onSuccess: function(response){
				QDLogger.error( "TelephonyCommands::wipeDevice", "you are success.  a winner is you.");
            },
            onFailure: function(response){
				QDLogger.error( "TelephonyCommands::wipeDevice", "we are fail");
			}
          
        });
		this.tempSaveRequest("wipeDevice",request);
	},
	
	rebootPhone: function() {
		QDLogger.log( "TelephonyCommands::rebootPhone");
		 var request = new Mojo.Service.Request(this.powerUri, {
            method: 'machineReboot',
			parameters: {
				reason: "User initiated/PhoneApp"                             
			},
            onSuccess: function(response){
				QDLogger.error( "TelephonyCommands::rebootPhone", "you are success.  a winner is you.");
            },
            onFailure: function(response){
				QDLogger.error( "TelephonyCommands::rebootPhone", "we are fail");
			}
          
        });
		this.tempSaveRequest("rebootPhone",request);
	},
	
	/*
	 * DEBUG - functions
	 */
	radioDebugSet: function(enable, subscribe, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'radioDebugSet',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success",response.extended);
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
			parameters: {
				enable : enable,
				subscribe: subscribe
			},
        });
		return request;
    },
	
	/*
	 * DATA - functions
	 */
	
	pdpSlotQuery: function(callback) {
		var request = new Mojo.Service.Request(this.svcUri, {
            method: 'pdpSlotQuery',
            onSuccess: function(response){
				if(callback)
               		callback(true, response);
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },			
        });	
		this.tempSaveRequest("pdpslot",request);	
	},
	
	pdpProfileQuery: function(slot, callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'pdpProfileQuery',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success", response.extended);
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
			parameters: {
				slot : slot				
			},
        });
		this.tempSaveRequest("pdpprofile",request);
    },
	
	pdpProfileSet: function(slot, key, value, callback){
		 params = {}
     	params[key] = value;
		params['slot'] = slot;
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'pdpProfileSet',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success");
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
			parameters: params,
        });
		this.tempSaveRequest("pdpProfileSet",request);
		
    },
	
	dataExtFieldsQuery: function(callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'dataExtFieldsQuery',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success", response.extended);
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },		
        });
		this.tempSaveRequest("dataext",request);
    },
	
	dataExtFieldsSet: function(params,callback){
        //params = {}
     	//params[key] = value;
		
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'dataExtFieldsSet',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success");
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
			parameters: params,
        });
		
		this.tempSaveRequest("dataExtFieldsSet",request);
    },
	
	dataFieldsQuery: function(callback){
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'dataFieldsQuery',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success", response.extended);
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },		
        });
		this.tempSaveRequest("dataQuery",request);
    },
	
	dataFieldsSet: function(key,value,callback){
        params = {}
     	params[key] = value;
		
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'dataFieldsSet',
            onSuccess: function(response){
				if(callback)
               		callback(true, "success");
            },
            onFailure: function(response){
				if(callback)
                	callback(false, (Messages.serviceErrors[response.errorCode] || Messages.generalServiceError), "");
            },
			parameters: params,
        });
		
		this.tempSaveRequest("dataFieldsSet",request);
    },
	
	
    
    /*
     * links to other apps
     */

	contactsLaunchWithPseudocard: function(number) {
		var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
			parameters: {
				id: "com.palm.app.contacts",
				params: {
					contact: {
						phoneNumbers: [{
							value: number
						}]
					},
					launchType: "pseudo-card"
				}
			}              
		});
	},
	
	contactsLaunchWithId: function(personID) {
		var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
			parameters: {
				id: "com.palm.app.contacts",
				params: {
					id:personID
				}
			}              
		});
		
	},
	
	messagingLaunch: function(address, personId, contactPointId) {
		var params = {};
		if ( contactPointId ) {
			params = {
				contactPointId: contactPointId,
				personId: personId
			};
		} else {
			params = {
				address: address
			};
		}
		new Mojo.Service.Request("palm://com.palm.applicationManager/launch", {
			parameters: {
				id: "com.palm.app.messaging",
				params: params
			}              
		});
	},
	
	/*
	contactsShowPseudoCard: function(stageController, number) {
		var contact = {
			phoneNumbers:[{ value:number}]
		}
		
		Pseudocard.pushPseudocard(stageController, {
			"contact": contact
		});
 	},
    
    contactShowDetails: function(stageController, id){
		Pseudocard.pushPseudocard(stageController,{
			"personId": id
		});        
    },
	*/
	
	
	
	contactPromptToAdd: function(sceneController, number) {
			sceneController.showAlertDialog({
            	onChoose: this.doHandleContactSave.bind(this, number),
            	choices: [
					{
                		label: $L('Save as new'),
                		value: 'NEW'
            		}, {
                		label: $L('Add to existing'),
                		value: 'EXISTING'
            		}, {
                		label: $L('Cancel'),
						type: 'dismiss',
                		value: 'CANCEL'
            		}
				]
        });
	},
    
	doHandleContactSave: function(number, choice) {
		var launchType ='';
		switch (choice) {
			case 'EXISTING':
				launchType = "addToExisting";
				break;
			case 'NEW':
				launchType = "newContact";	
				break;
			default:
				return;
			
		}
		
		var contact = {
			phoneNumbers:[{ value:number}]
		}
		
		var request = new Mojo.Service.Request("palm://com.palm.applicationManager", {
        		method: "open",
				parameters: {
					id: "com.palm.app.contacts",
					params: {
						"contact": contact,
                        "launchType": launchType
					}
				}
		});
		                       
     },
	
	
    dialExternally: function(number){
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                id: 'com.palm.app.phone',
                params: {
                    "number": number
                }
            }
        });
    },
	
	launchCroTest: function(){
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                id: 'com.palm.app.crotest',
            }
        });
    },
	
	launchExternalProgram: function(name, p) {
		if (!p) p = ""; 
		QDLogger.log("Load external application", name); 
		var request = new Mojo.Service.Request( 'palm://com.palm.applicationManager', { 
			method: 'open', 
			parameters: { 
				id: 'com.palm.app.' + name, 
				params: p 
			} 
		}); 
	},
	
	displayNetworkSelection: function() {
		QDLogger.log( "TelephonyCommands::displayNetworkSelection");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'networkSelection',
				}   
            }
        });
	},
	
	displayPin1Lock: function() {
        QDLogger.log( "TelephonyCommands::displayPin1Lock");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'unlockTelephony',
				}   
            }
        });		
		
	},
	
	displayPin2Lock: function(number) {
        QDLogger.log( "TelephonyCommands::displayPin2Lock");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'fdnDisable',
					number: number
				}   
            }
        });		
		
	},
	
	displayPuk1Lock: function() {
        QDLogger.log( "TelephonyCommands::displayPuk1Lock");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'puk1Lock',
				}   
            }
        });		
		
	},
	
	displayPuk2Lock: function() {
        QDLogger.log( "TelephonyCommands::displayPuk2Lock");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'puk2Lock',
				}   
            }
        });		
		
	},
	
	displaySimLock: function() {
        QDLogger.log( "TelephonyCommands::displayPuk2Lock");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'simlock',
				}   
            }
        });		
		
	},
	
	displayDeviceLock: function(type, unblock) {
        QDLogger.log( "TelephonyCommands::displayDeviceLock");
        
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
				params: {
					launchType: 'devicelock',
					type: type,
					unblock:unblock
				}   
            }
        });		
		
	},
	
	getListener: function() {
		return Mojo.Controller.getAppController().assistant.telephonyEventListener;
	},
	
/*
 * provisioning status 
 */
    provisioningStatusSubscribe: function(callback){
			if (this.provisionRequest !== undefined)
				this.provisionRequest.cancel();

			this.provisionRequest = new Mojo.Service.Request("palm://com.palm.provisioning/SessionStatus",{
			parameters: {
				'subscribe': true
			},

			onSuccess: callback,
			onFailure: callback
        });
		
		
    },

	initOnProvisionStart: function(callback) {
		// Register to receive a callback when the service starts
		var request = new Mojo.Service.Request('palm://com.palm.bus/signal/', {
			method: 'registerServerStatus',
			parameters: {'serviceName':"com.palm.provisioning"},
			onSuccess: this.handleProvisionServerStatus.bind(this, callback)
		});
		
		this.tempSaveRequest("initOnProvisionStart",request);
	},
	
	handleProvisionServerStatus: function(callback, payload) {
		QDLogger.log( "TelephonyCommands::handleProvisionServerStatus");
		if (payload.connected == true)
			this.provisioningStatusSubscribe(callback);
		else{//provision is down
			if (this.provisionRequest !== undefined)
				this.provisionRequest.cancel();
			this.provisionRequest = undefined;
		}
	},
	/** other **/
	buildNameQuery: function(callback) {
		var request = new Mojo.Service.Request('palm://com.palm.preferences', {
				method: 'systemProperties/Get',
			parameters: {key: "com.palm.properties.buildName"},
			onSuccess: callback,
			onFailure: function(response){
				QDLogger.log( "TelephonyCommands::buildNameQuery", "we are fail");
			}				
    	});	
		
		this.tempSaveRequest("buildNameGet",request);
	},

	// turns the screen on
	displayOn: function() {
		QDLogger.log( "TelephonyCommands::displayOn");
		var request = new Mojo.Service.Request('palm://com.palm.display', {
				method: 'control/setState',
				parameters: {state: "on"},
				onSuccess: function(response){
					QDLogger.log( "TelephonyCommands::displayOn", "you are success.  a winner is you.");
				}			,
				onFailure: function(response){
					QDLogger.log( "TelephonyCommands::displayOn", "we are fail");
				}				
    	});	
		
		this.tempSaveRequest("displayOn",request);
	},
	
	// DO NOT SAVE THIS REQUEST HERE
	displayDNAST: function(enable, callback) {
        var request = new Mojo.Service.Request(this.displayUri, {
            method: 'setProperty',
			parameters: {
				'requestBlock': enable,
				'client': "phoneapp"
			},
			onSuccess: function(payload){
				if (callback) callback(payload);
			},
			onFailure: function() {
				QDLogger.log( "TelephonyCommands::displayDNAST", "failure");
			}
        });
      
        return request;
	},
	
	displayChangeBlockWithTimeout: function(callback) {
		
		var req = this.displayDNAST(true, callback);
		if (req) {
			req = this.cancelRequestAfterTimeout(req, 60 * 1000);
		}
		return req;
	},
	
	powerButtonBlockWithTimeout: function(name, callback) {
		var req = this.powerButtonSubscribe(true, name, callback);
		if (req) {
			req = this.cancelRequestAfterTimeout(req, 60 * 1000);
		}
		return req;
	},
	
	cancelRequestAfterTimeout: function(request, timeout) {
		var r = {};
		if (request) {
			r.req = request;
			r.cancel = function() {
				if (this.req) {
					this.req.cancel();
					clearTimeout(r.timer);
					delete this.req;
				}
			}
			
			r.timer = setTimeout(function() {
				r.cancel();
			}, timeout);
		}
		
		return r;
		
	},
	
	// increases logging in service
	
	loggingVerboseSet: function(verbose){
        var message;
        
        var request = new Mojo.Service.Request(this.svcUri, {
            method: 'loggingSet',
            onSuccess: function(response){
                QDLogger.log( "TelephonyCommands#loggingVerboseSet", "we are success");
            },
            onFailure: function(response){
				QDLogger.log( "TelephonyCommands#loggingVerboseSet", "we are fail");
            },
            parameters: {
                "verbose": verbose
            },
        });
		
		this.tempSaveRequest("loggingVerboseSet",request);
    },
    
	subscribePreference: function(key, callback) {
		var request = new Mojo.Service.Request('palm://com.palm.systemservice', {
	     	method: 'getPreferences',
	        parameters: {
				'keys': [key],
				subscribe: true
			},
	        onSuccess: function(response) {
				if ( response && ! Object.isUndefined(response[key]) ) {
					callback(response[key]);
				}
			},
			onFailure: function(r) {
				QDLogger.log( "Failure calling palm://com.palm.systemservice/getPreferences with response %j",r);
			}
		});
		this.tempSaveRequest("subscribePreference "+key, request);
	},
		
	// runs callback if LunaSysService is up
	subscribeSystemServiceStatus: function(callback) {
		// Register to receive a callback when the service starts
		var request = new Mojo.Service.Request('palm://com.palm.bus/signal/', {
			method: 'registerServerStatus',
			parameters: {'serviceName':"com.palm.systemservice"},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log( "TelephonyCommands#subscribeSystemServiceStatus", "failure");
			}
		});
		
		return request;
		
	},
	
	subscribeServiceStatus: function(service, callback) {
		var request = new Mojo.Service.Request('palm://com.palm.bus/signal', {
                method: 'registerServerStatus',
                parameters: {
                    'serviceName': service
                },
                onSuccess: callback,
                onFailure: function(){
                    QDLogger.log( "TelephonyCommands#subscribeSystemServiceStatus", "failure")
                }
            });
			
		return request;
	},
	
	getOnDeviceDemoState: function(onSuccess) {
		var request = new Mojo.Service.Request(this.oddUri, {
            method: 'demoState',
            onSuccess: onSuccess
        });
	},

	toggleOnDeviceDemo: function(onComplete) {
		var request = new Mojo.Service.Request(this.oddUri, {
            method: 'toggleDemo',
            onComplete: onComplete
        });
	}
};
