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

var Util = Class.create ({

	MINPASSWORDLENGTH : 6,
	MAXPASSWORDLENGTH : 20,	
		
	addDashboardOdd: function(target) {
		var info = Mojo.View.render({template: 'dashboard/dashboard-odd'});
        target.update(info);
	},	
	
	addDashboardSmall: function(target) {
		var info = Mojo.View.render({template: 'dashboard/dashboard-small'});
        target.update(info);
	},	

	addDashboardBig: function(target) {
		var info = Mojo.View.render({template: 'dashboard/dashboard-big'});
        target.update(info);
	},
	
	addDashboardOtasp: function(target) {
		var info = Mojo.View.render({template: 'dashboard/dashboard-otasp'});
        target.update(info);
	},	
	
	loadValues: function () {
		this.getEmergencyNumbers();
		this.getCarrierName();
		this.getCarrierDetails();
	}, 
	
	getCarrierDetails: function () {
		FirstUseUtil.carrierUrl = "";
		FirstUseUtil.customerCareNumber = "";
		FirstUseUtil.carrierString = "";
		FirstUseUtil.activationCareNumber= "";
		this.detailsRequest = AppAssistant.accountService.getCarrierDetails(
				this.readCarrierDetails.bind(this), this.errorCarrierDetails.bind(this));
	},
	
	readCarrierDetails: function(response) {
		if(response) {
			if(response.carrierString) {
				if (Object.isString(response.carrierString)) {
					FirstUseUtil.carrierString = response.carrierString.gsub("\"", "");
				} else {
					FirstUseUtil.carrierString = response.carrierString;
				}	
			}
			if(response.carrierUrl) {
				if (Object.isString(response.carrierUrl)) {
					FirstUseUtil.carrierUrl = response.carrierUrl.gsub("\"", "");
				} else {
					FirstUseUtil.carrierUrl = response.carrierUrl;
				}	
			}
			if(response.customerCareNumber) {
				if (Object.isString(response.customerCareNumber)) {
					FirstUseUtil.customerCareNumber = response.customerCareNumber.gsub("\"", "");
				} else {
					FirstUseUtil.customerCareNumber = response.customerCareNumber;
				}
			}
			if(response.activationCareNumber) {
				if (Object.isString(response.activationCareNumber)) {
					FirstUseUtil.activationCareNumber = response.activationCareNumber.gsub("\"", "");
				} else {
					FirstUseUtil.activationCareNumber = response.activationCareNumber;
				}
			}
		}
	},
	
	errorCarrierDetails: function (response) {
		Mojo.Log.error("----------- Cannot get carrier details -----------------%j", response);
		if(response.errorCode == -1) {
			this.detailsRequest = AppAssistant.accountService.getCarrierDetails(
				this.readCarrierDetails.bind(this), this.errorCarrierDetails.bind(this));
		}
	},
	
	getCarrierName: function () {
		//this.carrierName = $L("Customer Care");
		FirstUseUtil.carrierShortName = "";
		this.carrierRequest = AppAssistant.accountService.getCarrierName(
				this.readCarrierName.bind(this));
	},
	
	readCarrierName: function(response) {
		Mojo.Log.info("----------------- readCarrierName----------------%j", response);
		if(!response)			
			return;
			
		if(response.returnValue && response.returnValue == true) {
			FirstUseUtil.carrierShortName = response.shortName;
			if (FirstUseUtil.carrierShortName) {
				if(this.carrierRequest) {
					this.carrierRequest.cancel();
				}
				//var locCarrier = $L(FirstUseUtil.carrierShortName);
				//this.carrierName = $L("#{carrier} Customer Care").interpolate({
				//	carrier: locCarrier
				//});
			}	
		}
	},	
	
	carrierName: function()
	{
		//if (this.carrierShortName)
		//{
		//	return $L("#{carrier} Customer Care").interpolate({ carrier: $L(this.carrierShortName) });
		//}
		//else
		//{
		//	return $L("Customer Care");
		//}
		return (this.carrierShortName ? undefined : $L("Customer Care"));
	},
	
	getEmergencyNumbers: function() {
		this.emergencyNumber = "911";
		this.emergencyRequest = AppAssistant.accountService.getEmergencyNumbers(
				this.readEmergencyNumbers.bind(this), 
				this.errorEmergencyNumbers.bind(this));
	},
	
	readEmergencyNumbers: function(response) {
		
		Mojo.Log.info("Response from telephony -------------> %j ", response);
	  	if(response.returnValue == true) {
			var numbers = response.extended.value;
			if((!(numbers.empty())) && (numbers.indexOf(",") > -1)) {
				this.emergencyNumber = numbers.substring(0, numbers.indexOf(","));
				this.emergencyNumbers = numbers;
				this.emergencyNumbers = numbers.split(',');
			}
		}
		Mojo.Log.info("------------- Emergency number, numbers --------- %j, %j ", this.emergencyNumber, this.emergencyNumbers);
  	},
  
  	errorEmergencyNumbers: function(response) {
  		Mojo.Log.info("No emergency number found: %o ", $H(response));
  		this.emergencyNumber = "911";	
		this.emergencyNumbers = ["911"];	
 	},
	
	getTutorialOverride: function() {
		this.tutorialRequest = AppAssistant.accountService.getTutorialOverride(
			this.setTutorialOverride.bind(this),
			this.errorTutorialOverride.bind(this));
	},

	setTutorialOverride: function(response) {
		Mojo.Log.info("Overriding the default tutorial: " + response['tutorialOverride']);
		if (response['tutorialOverride'] != undefined) {
			tutorialScript = response['tutorialOverride'];
		}

		// Now that we have a response, push the home scene.
		pushHome();
	},

	errorTutorialOverride: function(response) {
		Mojo.Log.info("Stay with the default tutorial");

		// Now that we have a response, push the home scene.
		pushHome();
	},

 	
	// launch app and close this
  	tapHandler: function (event) {		
		// For all pages with small icon
  		var near = this.controller.get('phoneBannerSmallIcon');
	
		if(!near) {
			// For intro scene where it changes from big icon to small icon
			var tmp =  this.controller.get('phoneBannerIcon');
			if (tmp && tmp.style.display != 'none') {
				near = tmp;
			}
			else {
				// For all pages with big icon
				near = this.controller.get('target');
			}	
		}
		Mojo.Log.info("------------ tapHandler show pop up--------- %j", near);
		Mojo.Log.info("------------ tapHandler show pop up---------this.controller", this.controller);
  		var labels;
		if(isDemoMode){
			labels = [{label: $L('Exit'), command: 'exit'}, 
				{label: $L('Cancel'), command: 'cancel'}
				];
		}
		else{
			labels = [{label: $L('Emergency call'), command: 'emergency-call'}, 
				{label: $L('Cancel'), command: 'cancel'}
				];
			if(FirstUseUtil.customerCareNumber && FirstUseUtil.customerCareNumber.length > 0) {
				labels = [{label: $L('Emergency call'), command: 'emergency-call'}, 
					{label: $L('Call customer service'), command: 'customer-care'},
					{label: $L('Cancel'), command: 'cancel'}
				];
			}
		}
  		this.controller.popupSubmenu({
  			onChoose: FirstUseUtil.popupChoose,
  			placeNear:near, 
			items:labels
		});	
  	},
  
  	popupChoose: function(value) {
		if(value == "emergency-call") {
			AppAssistant.accountService.makeEmergencyCall(FirstUseUtil.emergencyNumber);
		} else if (value == "customer-care") {
			Mojo.Log.info("----------------- FirstUseUtil.carrierName ----------------", FirstUseUtil.carrierName());
			AppAssistant.accountService.callCustomerCare(FirstUseUtil.customerCareNumber, $L(Mojo.Environment.DeviceInfo.carrierName));
		} else if(value == "exit"){
			new Mojo.Service.Request('palm://com.palm.oddService', {
            	method:'closetutorial',
	            parameters: {}
    	    });     
  		}
 	},
 	 	
 	handleKeyPressEvent: function(event) {
		// Ignore Sym key	
		if(event.originalEvent.keyCode == 129) {
			return;
		}
		var eventChar = String.fromCharCode(event.originalEvent.keyCode);

		if(!FirstUseUtil.previousKeyPressed) {
			FirstUseUtil.previousKeyPressed = new Array(3);
			FirstUseUtil.previousIdPressed = new Array(3);
		}
		
		FirstUseUtil.previousKeyPressed.shift();
		FirstUseUtil.previousKeyPressed.push(eventChar);
		
		FirstUseUtil.previousIdPressed.shift();
		FirstUseUtil.previousIdPressed.push(KeyMapping.translateKey(event.originalEvent.keyIdentifier));
		
		FirstUseUtil.arrayValue = FirstUseUtil.previousKeyPressed.join("");
		FirstUseUtil.keyValue = FirstUseUtil.previousIdPressed.join("");
		
		if(!FirstUseUtil.arrayValue.empty()) {
			if (((FirstUseUtil.arrayValue.endsWith("##")) || (FirstUseUtil.keyValue.endsWith("##")))
					  && (Account.platformType.toLowerCase() === "cdma")) {
				FirstUseUtil.disconnectPreviousCall();
		 		AppAssistant.accountService.makeEmergencyCall("##");
		 	} else if (((FirstUseUtil.arrayValue.endsWith("#*")) || (FirstUseUtil.keyValue.endsWith("#*")))
						 && (Account.platformType.toLowerCase() === "gsm")) {
		 		AppAssistant.accountService.makeEmergencyCall("#*");
		 	} else if (FirstUseUtil.arrayValue == FirstUseUtil.emergencyNumber || FirstUseUtil.keyValue == FirstUseUtil.emergencyNumber) {
				FirstUseUtil.previousKeyPressed = undefined;
				FirstUseUtil.previousIdPressed = undefined;
				FirstUseUtil.disconnectPreviousCall();
		 		AppAssistant.accountService.makeEmergencyCall(FirstUseUtil.emergencyNumber);
		 	} else if (FirstUseUtil.arrayValue.length >= 2 && FirstUseUtil.keyValue.length >= 2) {
		 		 FirstUseUtil.emergencyNumbers.each(function(number) {
		 		 	if(number == FirstUseUtil.arrayValue || number == FirstUseUtil.keyValue) {
						FirstUseUtil.previousKeyPressed = undefined;
						FirstUseUtil.disconnectPreviousCall();
		 				AppAssistant.accountService.makeEmergencyCall(number);
						throw $break;
		 		 	}
		 		 });
		 	} 
		}  
		
	},
	
	disconnectPreviousCall: function () {
		if((Account.platformType.toLowerCase() === "cdma") && (cdmaType === "otasp")) {
			AppAssistant.otaspService.disconnectCalls();
		}
	},
	
	initValues: function() {
		this.devProfileRequest = AppAssistant.accountService.getDeviceProfile(this.deviceProfileSuccess.bind(this), 
																				this.deviceProfileFailure.bind(this));
		this.versionRequest = AppAssistant.accountService.getDbSchemaVersion(this.readDbSchemaVersion.bind(this));														
	},
	
	readDbSchemaVersion: function (response) {
		Mojo.Log.info("----------------- Db schema version ------------------%o", $H(response));
		if(response && response.SCHEMA_VERSION) {
			dbVersion = response.SCHEMA_VERSION;
			if(this.versionRequest) {
				this.versionRequest.cancel();
			}
		}
	},
	
	changeLocale: function(){
		return new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
			parameters: {
				'id': "com.palm.systemui",
				params: {
					action: 'changeLocale',
					locale: Account.language + "_" + Account.country,
					region: Account.country
				}
			}
		});
	},	
	deviceProfileSuccess:function (response) {
		Mojo.Log.info("---------------- deviceProfileSuccess() --------------------");
		Account.deviceId = response.deviceInfo.deviceId;
		deviceCarrier = response.deviceInfo.carrier;
	},
	
	deviceProfileFailure:function (response) {
		Mojo.Log.info("---------------- deviceProfileFailure() --------------------");
		Mojo.Log.error("Device profile error: %j ", response);
	},
	
	displayFDNUnLock: function() {  
		simStatus = "none";     
        return new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
                params: {
                    launchType: 'fdnDisable',
					callingapp: 'firstuse',
					locale: Account.language + '_' + Account.country
                } 
            }
        });
    },
	
	displayPin1Lock: function() {  
		simStatus = "none";     
        return new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
                params: {
                    launchType: 'unlockTelephony',
					callingapp: 'firstuse',
					locale: Account.language + '_' + Account.country
                } 
            }
        });
    },
	
	displayPuk1Lock: function() {
		simStatus = "none";
        return new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                'id': "com.palm.app.phoneprefs",
                params: {
                    launchType: 'puk1Lock',
					callingapp: 'firstuse',
					locale: Account.language + '_' + Account.country
                } 
            }
        });       
    },
	
	validateEmail: function (strValue) {
		var emailRegEx = /^[A-Z0-9]+([A-Z0-9._%+-]*)+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	  	//check for valid email
	 	 return (strValue.search(emailRegEx) != -1);
	},	
	
	filterSpace: function(value) {
		if(Mojo.Char.spaceBar === value) {
			return false;
		}			
		return true;
	},
	
	setDefaultTimeFormat: function (format) {
		this.timeFormatRequest = AppAssistant.accountService.setDefaultTimeFormat(
							format,
							this.timeFormatSuccess.bind(this), this.timeFormatError.bind(this));
	},
	
	timeFormatSuccess: function (response) {
		Mojo.Log.info("-------------- Successfully set time format ---------------%o", $H(response));
		if(response.returnValue == true) {
			if(this.timeFormatRequest) {
				this.timeFormatRequest.cancel();
			}
		} 
	},
	
	timeFormatError: function(response) {
		Mojo.Log.info("-------------- Error in setting time format ---------------%o", $H(response));
	},
	
	saveDoneState: function () {
		FirstUseUtil.language = Account.language;
		FirstUseUtil.country = Account.country;
		FirstUseUtil.regionCountryCode = Account.regionCountryCode;
		FirstUseUtil.regionCountryName = Account.regionCountryName;
		// NOV-94051: If it is GSM, call customization again to load settings. If the device had been pin locked,
		// the mcc/mnc values during the first time populateDefaults is called is 0/0.
		if (Account.platformType.toLowerCase() === "gsm") {
			this.custRequest = AppAssistant.accountService.populateDefaults(Account.language, Account.country, this.readStatus.bind(this), this.errorStatus.bind(this));
		}	
		// Clear values in db and save 'done' as the state
		Account = new NovaAccount()
		saveCurrentState("done");
		// Giving it sometime to save the db changes
		this.wrapRequest = setTimeout(this.wrapUp.bind(this), 500);
	},
	
	wrapUp: function() {
		clearTimeout(this.wrapRequest);
		if (FirstUseUtil.isSimulator()) {
			// It is either emulator or simulator
			Mojo.Controller.stageController.topScene().assistant.controller.window.close();
			return;
		}
		
		// Enable roamguard 
		this.roamRequest = AppAssistant.accountService.setWanConfig("enable",
								this.readRoamGuardStatus.bind(this), this.errorRoamGuardStatus.bind(this));
							
		PalmSystem.shutdown();
	},
	
	readRoamGuardStatus: function(response) {
		Mojo.Log.info("---------------- readRoamGuardStatus -------------------- %j", response);
	}, 
	
	errorRoamGuardStatus: function (response) {
		Mojo.Log.error("---------------- errorRoamGuardStatus -------------------- %j", response);
	},
	
	readStatus: function(response) {
		Mojo.Log.info("------------- read populate defaults response -----------%j", response);
	},
	
	errorStatus: function (response) {
		Mojo.Log.error("------------- error in populating defaults --customization---------%j", response);
	},
	
	handlePowerKey: function()	{
		this.powerOffRequest = AppAssistant.accountService.notifyPowerKeyPress(this.readPowerKeyResponse.bind(this),
									this.errorPowerKeyResponse.bind(this));
	},
	
	readPowerKeyResponse: function (response) {
		Mojo.Log.info("------------ powerKeyPressed --------- %j", response);
		if (response.showDialog && response.showDialog === true)    {
			
			this.scene = Mojo.Controller.stageController.topScene(); 
			var sceneName = this.scene.sceneName;
			if(sceneName == "home" || sceneName == "language" || sceneName == "confirmlanguage") {
				return;
			}
			this.controller = this.scene.assistant.controller;
	  		
			var dialog = this.controller.showDialog({
				template: 'poweroffalert/poweroffalert',
				assistant: new PoweroffalertAssistant(this.scene.assistant)
			});
			dialog.observe(Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this.scene.assistant));
			
    	}
	},
	
	errorPowerKeyResponse: function (response) {
		Mojo.Log.error("------------error powerKeyPressed --------- %j", response);
	},
	
	powerDownDevice: function (reason) {
		this.powerRequest = AppAssistant.accountService.powerDown(this.successPowerDown.bind(this), this.errorPowerDown.bind(this), reason);				
	},
	
	successPowerDown: function (response) {
		Mojo.Log.info("------------- power off success --------------%j", response);
		this.animationRequest = AppAssistant.accountService.runProgressAnimation();
	},
	
	errorPowerDown: function (response) {
		Mojo.Log.error("----------- Could not power down the device %j ", response);
	},
	
	isSimulator: function () {
		return PalmSystem.version.match("desktop");
	}
		
});

var FirstUseUtil = new Util();
