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

var PrefsAssistant = Class.create(
{
    initialize: function()
	{
		this._ccInfos = [];
		
	},
	
    setup: function()
	{
		this._addedPrefs = this.controller.document.body.hasClassName("prefs") || this.controller.document.body.addClassName("prefs");
		
		this._spinner = new Spinner(this, 'spinner', true, 'large');
		this.invoiceEmailContainer = this.controller.get("invoiceEmailContainer");
		
		this.addAccount = this.addOrEditAccount.bindAsEventListener(this, false);
		this.editAccount = this.addOrEditAccount.bindAsEventListener(this, true);
		this.createAccount = this.createAccount.bind(this);
		this.saveInvoiceEmailHandler = this.handleSaveInvoiceEmail.bind(this);
		//this._handleEmbargoAcc = this._handleEmbargoAcc.bind(this);
		//this._doEmbargoCheck = this._doEmbargoCheck.bind(this);
		
		this._passwordModel = {passwordReq: Preferences.getPaymentLogin() };
		this._passwordTypes = 
		[
			{label: $L('Once every 4 hours'), value:'timeout'},
			{label: $L('Every Purchase'), value:'every'}
		];

		this.controller.setupWidget('passwordReqSelector', {label: "", choices: this._passwordTypes, modelProperty:'passwordReq'}, this._passwordModel);
		this.controller.listen('passwordReqSelector', Mojo.Event.propertyChange, this.handlePasswordSelected);
	
		this.controller.listen("addAccountButton", Mojo.Event.tap, this.addAccount);
        this.controller.listen("currentAccount", Mojo.Event.tap, this.editAccount);
		this.invoiceEmailAttr = {
			multiline: false,
			focus: false,
			limitResize: false,
			enterSubmits: false,
			textCase: Mojo.Widget.steModeLowerCase,
			changeOnKeyPress: false
		};
		this.invoiceEmailModel = {
		 	value : ""
		};
		this.controller.setupWidget('invoiceEmail', this.invoiceEmailAttr, this.invoiceEmailModel);
		
		
		
	},

	handlePasswordSelected:function(ev) 
	{
		Preferences.setPaymentLogin(ev.value);
	},
	
	_verifyPaymentSetup: function()
	{		
		var self = this;	
		// We only run the spinner the first time we enter this scene, so we dont start it here - but we always stop it (does no harm)
		Weave.Services.PaymentServer.verifyPaymentSetup(function(status, response)
		{
			self._spinner.stop();			
			
			Mojo.Log.info("status, response: (%j, %j)", status, response);
			self._invoiceEmail = "";
			if (status && response.OutGetCCPaymentInfos.ccPaymentInfos.length > 0) 
			{
				myProfile.validCC = response;
				if(response.OutGetCCPaymentInfos.invoiceEmail)
					self._invoiceEmail = response.OutGetCCPaymentInfos.invoiceEmail;
				Mojo.Log.info("invoice email: %s", self._invoiceEmail);
				self._ccinfos = response.OutGetCCPaymentInfos.ccPaymentInfos;
				var ccType = self._ccinfos[0].creditCard.type;
				var ccNum = self._ccinfos[0].creditCard.number;
				
				var creditCardTypeAndLast4digits = ccType + " " + ccNum.substring(ccNum.length - 5);
				
				var userName = self._ccinfos[0].billTo.firstName +
				" " +
				self._ccinfos[0].billTo.lastName;
				self.controller.get('addAccountButton').hide();
				self.controller.get('currentAccount').show();
				
				self.controller.get('creditCardTypeAndLast4digits').update(creditCardTypeAndLast4digits);
				self.controller.get('userName').update(userName);
				self.controller.get('requiredtopurchase').hide();
				
			}
			else 
			{
				if (!status) 
				{
					var err = response.errorCode ? response.errorCode : response;
					if(err == "PMT04800")
						err = "dplfailed";
					Utilities.Errors.displayError(err, {errCode: err}, "PMT_catchAll_default");
				}
				myProfile.validCC = undefined;
				self.controller.get('addAccountButton').show();
				self.controller.get('currentAccount').hide();
				self.controller.get('requiredtopurchase').show();
			}
			
				self._setupInvoiceEmail();
		
			
		});
	},
	
	//invoice email field is only set up if there is existing account
	_setupInvoiceEmail: function(){
		Mojo.Log.info("_setupInvoiceEmail");
		if (this._invoiceEmail) {
			this.invoiceEmailModel.value = this._invoiceEmail;
			this.controller.modelChanged(this.invoiceEmailModel, this);
			this.controller.listen("invoiceEmail", Mojo.Event.propertyChange, this.saveInvoiceEmailHandler);
			this.invoiceEmailContainer.show();
		}
		else{
			if (this.saveInvoiceEmailHandler)
				this.controller.stopListening("invoiceEmail", Mojo.Event.propertyChange, this.saveInvoiceEmailHandler);
			this.invoiceEmailContainer.hide();
		}
	},
	
	handleSaveInvoiceEmail: function(event){
		this.controller.get("embargoedAddError").hide();
		this.controller.get("emailNotValidError").hide();
		Mojo.Log.info("handleSaveInvoiceEmail Email:%sAddress", event.value);
			
			Event.stop(event);
			var self =  this;
			var ext = event.value.substring(event.value.indexOf(".") + 1);
			if (event.value.search(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) == -1)
			{
				this.controller.get("emailNotValidError").show();
				this.controller.get("invoiceEmail").focus();
			}
			else{
				this._doEmbargoCheck(event.value, function(status){
					
					if(status){
						Mojo.Log.info("embargoed**");
						self.controller.get("embargoedAddError").show();
						self.controller.get("invoiceEmail").focus();
					}
					else
					{
						Weave.Services.PaymentServer.setInvoiceEmail(event.value, function(status, response){
						Mojo.Log.info("status, response: (%j, %j)", status, response);
						//not worried about response indicating embargo as check already done
						});
					}
					
					
				});
			}
	},
	
	activate: function()
	{
		//update the account list
		this._verifyPaymentSetup();
	},
	
	cleanup: function()
	{
		this._addedPrefs !== true && this.controller.document.body.removeClassName("prefs");
		this.controller.stopListening("addAccountButton", Mojo.Event.tap, this.addAccount);
		this.controller.stopListening("currentAccount", Mojo.Event.tap, this.editAccount);
		this.controller.stopListening('passwordReqSelector', Mojo.Event.propertyChange, this.handlePasswordSelected);
		this.controller.stopListening("invoiceEmail", Mojo.Event.propertyChange, this.saveInvoiceEmailHandler);
	},
	
	addOrEditAccount:function(event, edit) 
	{
		// have the user login first
		if (Weave.Services.ConnectionManager.isOnline() === false) 
		{
			//Weave.Services.ConnectionManager.showConnectionError();
		} 
		else 
		{
			var self = this;
			this.controller.showDialog(
			{
				template: 'payment-setup/password-dialog',
				assistant: new PasswordAssistant(this, 
				{
					onComplete: function(ret)
					{
						if (ret.passwordValid)
						{
							Utilities.Common.doEmbargoCheck(edit, self.createAccount);
							
						}
					}
				})
			});
		}
	},
	
	

	createAccount: function(edit){
		var params = {
					edit: edit,
					ccInfos: this._ccinfos ? this._ccinfos[0] : undefined,
					appid: this._appid,
					onComplete: function(){
						this.controller.stageController.popScenesTo("prefs");
					}
				};
		if (edit) 
			this.controller.stageController.pushScene('create-account', params);
		else {
			this.controller.showAlertDialog({
				onChoose: function(value){
					switch (value) 
					{
						case "ok":
							this.controller.stageController.pushScene('create-account', params);
							break;
							
						case "change":
							this.controller.stageController.pushScene('change-email-address', params);
							break;
							
						default:
							break;
					}
				},
				title: $L("Verify Email Address"),
				message: $L("When you purchase items, we'll send receipts to #{email}.").interpolate(myProfile),
				choices: [{
					label: $L("OK"),
					value: "ok",
					type: "primary"
				}, {
					label: $L('Change Email Address'),
					value: "change",
					type: "secondary"
				}, ],
			});
		}
		
	},
	
	_doEmbargoCheck:function(email, callback)
	{
		Mojo.Log.info("Prefs-assistant, doEmbargoCheck, new address%s", email);
		
		var ext = email.substring(email.lastIndexOf(".") + 1);
		
		if (AppAssistant.embargoedList) {
			if( AppAssistant.embargoedList.indexOf(ext) != -1)
				callback(true);
			else
				callback(false);
		}
		else {
			
			var self = this;
			Weave.Services.PaymentServer.getEmbargoedEmailExtensions(function(status, response){
				Mojo.Log.info("getEmbargoedCountryList %j", response);
				if (status) {
					AppAssistant.embargoedList = response.OutGetEmbargoedEmailExtensions.embargoedEmailExtensions;
					if( AppAssistant.embargoedList.indexOf(ext) != -1)
						callback(true);
					else
						callback(false);
				}
				else {
					var err = response.errorCode ? response.errorCode : response;
					Utilities.Errors.displayError(err, {
						errCode: err
					}, "PMT_catchAll_default");
				}
			});
		
		}
	},
	
	
});
