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

var FirstUseUtil = Class.create ({

	initialize: function() {
		Mojo.Log.info("FirstUseUtil initialize");
		this.customerCareNumber = undefined;
		this.populateCustomerCareNumber();
		
		this.emergencyNumbers = ["911"]; // default
		this.populateEmergencyNumbers();
		
		this.platformType = "";
		this.getPlatformType();
		
		this.cdmaType = "";
		this.getCDMAType();
	},
	
	populateCustomerCareNumber: function() {
		Mojo.Log.info("FirstUseUtil populateCustomerCareNumber");
		this.requestCustomer = new Mojo.Service.Request('palm://com.palm.systemservice', {
			method: 'getPreferences',
			//parameters: {"keys":["carrierString", "carrierUrl", "customerCareNumber", "activationCareNumber"]},
			parameters: {"keys":["customerCareNumber"]},
			onSuccess: this.readCarrierDetails.bind(this),
			onFailure: this.errorCarrierDetails.bind(this),
			onComplete: function() {
				this.requestCustomer = undefined;
			}
		});
	},

	readCarrierDetails: function(response) {
		Mojo.Log.info("FirstUseUtil readCarrierDetails---%j", response);
		if(response) {
			if(response.customerCareNumber) {
				if (Object.isString(response.customerCareNumber)) {					
					this.customerCareNumber = response.customerCareNumber.gsub("\"", "");
				} else {
					this.customerCareNumber = response.customerCareNumber;
				}
			}
		}
	},

	errorCarrierDetails: function (response) {
		Mojo.Log.error("FirstUseUtil errorCarrierDetails----%j", response);
		if(response.errorCode == -1) {
			this.detailsRequest = AppAssistant.accountService.getCarrierDetails(
				this.readCarrierDetails.bind(this), this.errorCarrierDetails.bind(this));
		}
	},

	populateEmergencyNumbers: function() {
		Mojo.Log.info("FirstUseUtil populateEmergencyNumbers");
		this.requestEmergency = new Mojo.Service.Request("palm://com.palm.telephony", {
	        method: 'emergencycalllistQuery',
	        onSuccess: function(payload) {
				Mojo.Log.info("FirstUseUtil popEmergency success", Object.toJSON(payload));
				if (payload && payload.extended && payload.extended.value) {
		            this.emergencyNumbers = payload.extended.value.match(/[\*\#0-9]+/g);
				}
			}.bind(this),
			onFailure: function(e) {
				 Mojo.Log.error("palm://com.palm.telephony/emergencycalllistQuery failed with error %j",e);
			},
			onComplete: function() {
				this.requestEmergency = undefined;
			}
	    });
	},

	getPlatformType: function() {
		Mojo.Log.info("FirstUseUtil getPlatformType");
		this.requestPlatform = new Mojo.Service.Request('palm://com.palm.telephony', {
            method: 'platformQuery',
            parameters: {},
            onSuccess: function(payload) {
			    Mojo.Log.info("FirstUseUtil getPlat success", Object.toJSON(payload));
			    if(payload.returnValue == true) {
			    	this.platformType = payload.extended.platformType;                                    
			    } else {
			        Mojo.Log.error("Telephony error === %j ", payload);
			    }
			}.bind(this),
            onFailure: function (payload) {
			    Mojo.Log.error("Telephony error === %j ", payload);
			}.bind(this),
			onComplete: function() {
				this.requestPlatform = undefined;
			}
	    });
	},
	
	getCDMAType: function() {
		Mojo.Log.info("FirstUseUtil getCDMAType");
		this.requestCdmaType = new Mojo.Service.Request('palm://com.palm.systemservice', {
			method: 'getPreferences',
			parameters: {"keys":["omadmActivation", "otaspActivation"]},
			onSuccess: function (response) {
				Mojo.Log.info("FirstUseUtil CDMA type ------------%j", response);
				if(response.otaspActivation) {
					this.cdmaType = "otasp";
				} else {
					this.cdmaType = "omadm";
				}
			}.bind(this),
			onFailure: function (response) {
				Mojo.Log.error("------------ Error CDMA type ------------%j", response);
			},
			onComplete: function() {
				this.requestCdmaType = undefined;
			}
		});
	},

	
	handleKeyPressEvent: function(event) {
		// Ignore Sym key	
		if(event.originalEvent.keyCode == 129) {
			return;
		}
		var eventChar = String.fromCharCode(event.originalEvent.keyCode);
	
		if(!FirstUseUtil.util.previousKeyPressed) {
			FirstUseUtil.util.previousKeyPressed = new Array(3);
			FirstUseUtil.util.previousIdPressed = new Array(3);
		}
		
		FirstUseUtil.util.previousKeyPressed.shift();
		FirstUseUtil.util.previousKeyPressed.push(eventChar);
		
		FirstUseUtil.util.previousIdPressed.shift();
		FirstUseUtil.util.previousIdPressed.push(KeyMapping.translateKey(event.originalEvent.keyIdentifier));
		
		FirstUseUtil.util.arrayValue = FirstUseUtil.util.previousKeyPressed.join("");
		FirstUseUtil.util.keyValue = FirstUseUtil.util.previousIdPressed.join("");
		
		if(!FirstUseUtil.util.arrayValue.empty()) {
			if (((FirstUseUtil.util.arrayValue.endsWith("##")) || (FirstUseUtil.util.keyValue.endsWith("##")))
					  && (FirstUseUtil.util.platformType.toLowerCase() === "cdma")) {
				
				FirstUseUtil.util.disconnectPreviousCall();
				FirstUseUtil.util.makeEmergencyCall("##");
				
		 	} else if (((FirstUseUtil.util.arrayValue.endsWith("#*")) || (FirstUseUtil.util.keyValue.endsWith("#*")))
						 && (FirstUseUtil.util.platformType.toLowerCase() === "gsm")) {
						 	
		 		FirstUseUtil.util.makeEmergencyCall("#*");
				
		 	} else if (FirstUseUtil.util.arrayValue == FirstUseUtil.util.emergencyNumber || FirstUseUtil.util.keyValue == FirstUseUtil.util.emergencyNumber) {

				FirstUseUtil.util.previousKeyPressed = undefined;
				FirstUseUtil.util.previousIdPressed = undefined;
				FirstUseUtil.util.disconnectPreviousCall();
		 		FirstUseUtil.util.makeEmergencyCall(FirstUseUtil.util.emergencyNumber);

		 	} else if (FirstUseUtil.util.arrayValue.length >= 2 && FirstUseUtil.util.keyValue.length >= 2) {

		 		 FirstUseUtil.util.emergencyNumbers.each(function(number) {
		 		 	if(number == FirstUseUtil.util.arrayValue || number == FirstUseUtil.util.keyValue) {
						FirstUseUtil.util.previousKeyPressed = undefined;
						FirstUseUtil.util.disconnectPreviousCall();
		 				FirstUseUtil.util.makeEmergencyCall(number);
						throw $break;
		 		 	}
		 		 });
		 	} 
		}  
		
	},

	disconnectPreviousCall: function () {
		if((this.platformType.toLowerCase() === "cdma") && (this.cdmaType.toLowerCase() === "otasp")) {

			this.disconnectRequest = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
				parameters: {
					id: 'com.palm.app.phone',
					params: {
						"firstuse": true,
						"action": "disconnect",					
						"locale": this.locale
					}
				},
				onComplete: function() {
					this.disconnectRequest = undefined;
				}
			});
		}
	},


	makeEmergencyCall: function (emergencyNumber) {
	    Mojo.Log.info("FirstUseUtil Emegerncy call to phone app -------------------------------------------------: ",emergencyNumber);
	    this.emergencyCallRequest = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
		    parameters: {
		        id: 'com.palm.app.phone',
		        params: {
		            "prefill": emergencyNumber,
		            "firstuse":true,
		            "locale": this.locale
		        }
		    },
			onComplete: function() {
				this.emergencyCallRequest = undefined;
			}
		});
	},
	
	callCustomerCare: function (number) {
	    Mojo.Log.info("FirstUseUtil call to phone app -------------------------------------------------: ", number);
	    this.customerCallRequest = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
		    parameters: {
		        id: 'com.palm.app.phone',
		        params: {
					"number": number,
					"firstuse":true,
					"name": $L(Mojo.Environment.DeviceInfo.carrierName),
		            "locale": this.locale
		        }
		    },
			onComplete: function() {
				this.customerCallRequest = undefined;
			}
		});
	},
	
	setLocale: function (locale){
		this.locale = locale;		
	}
});


FirstUseUtil.util = null;
FirstUseUtil.getUtil = function() {
	if (!FirstUseUtil.util) {
		FirstUseUtil.util = new FirstUseUtil();
	}
	return FirstUseUtil.util;
};