/**
 * Clase que centraliza las funcionalidades de la vista de recuperar usuario
 * @returns
 */


function RecoveryPasswordView(options) {
	var self = this;
	if(options.userServiceFacade) {
		self.userServiceFacade = options.userServiceFacade;
	} else {
		self.userServiceFacade = userServiceFacade;
	}
	if(options.inet) {
		self.inet = options.inet;
	} else {
		self.inet = inet;
	}
	if(options.i18n) {
		self.i18n = options.i18n;
	} else {
		self.i18n = i18n;
	}
	if(options.messageHandler) {
		self.messageHandler = options.messageHandler;
	} else {
		self.messageHandler = messageHandler;
	}
	
	self.idRecaptcha = '';
	self.scrollbar = null;
	self.sessionToken = null;
	self.countryCode = null;
	self.fullName = '';
	self.deliveryType = null;
	if (options.login) {		
		$('body').loader('show');
		self.userServiceFacade.getDeliveryType(options.login, {}, self._onSuccessGetDeliveryTypeFromRecoverUser, self._onErrorGetDeliveryTypeFromRecoveryUser, this);
	} else {
		self._init();
	}
};



/***
 * Método de inicialización en la creación de la vista
 */
RecoveryPasswordView.prototype._init = function() {
	
	var self = this;
	var action="recoveryPasswordStep1";
	var params = {i18n: self.i18n};
	self.fullName = '';
	self._loadStep(action, params, 'recoveryPassword');
	
	self.inet.getCountries();
	$('#recoveryPassCountrySelect').selectpicker({
		width: '300px',
		height: '37px',
		dropupAuto: false,
		size: 7
	});
	$('body').loader('show');
	this.loadCaptcha();
	
	self._initHandlers();
};


/**
 * Carga el paso 1
 */
RecoveryPasswordView.prototype._loadStep = function(action, params, module) {
	
	var self = this;
	
	captcha.hide();
	
	if(!module && module != '') {
	module = 'recoveryPassword';
	}
	self.inet.loadStep(action, params, module);
	$('[data-toggle="popover"]').popover({
        placement : 'right'
    });
	
};

/**
 * Resetea el captcha.
 */
RecoveryPasswordView.prototype.resetCaptcha = function() {
	var self = this;
	captcha.resetDiv();
};

/**
 * Comprueba si es necesario renderizar un captcha y lo renderiza si es necesario.
 */
RecoveryPasswordView.prototype.loadCaptcha = function() {
	var self = this;

	var countryCode = {'countryCode': inet.countryCode};
	self.userServiceFacade.checkCaptcha(countryCode, self._onSuccessCheckCaptcha, self._onErrorCheckCaptcha, self);
};

RecoveryPasswordView.prototype._onSuccessCheckCaptcha = function(data) {
	captcha.render(data);
};

RecoveryPasswordView.prototype._onErrorCheckCaptcha = function(response, textStatus, errorThrown) {
	var self = this;
	$('body').loader('hide');
	self.messageHandler.showMessage(self.messageHandler.MESSAGE_TYPE_ERROR, self.i18n.msg('error.internal'), 'messageArea');
};

/***
 * Método de inicialización en la creación de la vista
 */
RecoveryPasswordView.prototype._initHandlers = function() {
	var self = this;
	
	$(document).off('submit', '#formRecoveryPassFirstStep').on('submit', '#formRecoveryPassFirstStep', function(event) {
		event.preventDefault();
		self._submitFormFirstStep();
		
	});
	
	$(document).off('focus', '#recoveryPasswordFormLogin').on('focus', '#recoveryPasswordFormLogin', function(event) {
		if($('#recoveryPasswordFormLogin').val() == self.i18n.msg('num.employee.user.office.info')) {
			$('#recoveryPasswordFormLogin').val('');
		}
	});
	
	$(document).off('blur', '#recoveryPasswordFormLogin').on('blur', '#recoveryPasswordFormLogin', function(event) {
		if($('#recoveryPasswordFormLogin').val() == '') {
			$('#recoveryPasswordFormLogin').val(self.i18n.msg('num.employee.user.office.info'));
		}
	});
	
	$(document).off('submit', '#formRestorePassSecondStep').on('submit', '#formRestorePassSecondStep', function(event) {
		event.preventDefault();
		self._submitFormSecondStep();
		
	});
	
	$(document).off('submit', '#formRestorePassThirdStep').on('submit', '#formRestorePassThirdStep', function(event) {
		event.preventDefault();
		self._submitFormThirdStep();
		
	});
	
	$(document).off('submit', '#formRestorePassFourthStep').on('submit', '#formRestorePassFourthStep', function(event) {
		event.preventDefault();
		self._submitFormFourthStep();
		
	});
	
	$(document).off('keypress', '#recoveryPasswordFormLogin').on('keypress', '#recoveryPasswordFormLogin', function(event) {
		self._processMaxLength(event);
		
	});
	
	$(document).off('keyup', '#recoveryPasswordFormLogin').on('keyup', '#recoveryPasswordFormLogin', function(event) {
		self._processChangeInputUserLogin();
		
	});
	
	$(document).off('focus', '#recoveryPassInputPin').on('focus', '#recoveryPassInputPin', function(event) {
		if($('#recoveryPassInputPin').val() == self.i18n.msg('single.use.code')) {
			$('#recoveryPassInputPin').val('');
		}
	});
	
	$(document).off('blur', '#recoveryPassInputPin').on('blur', '#recoveryPassInputPin', function(event) {
		if($('#recoveryPassInputPin').val() == '') {
			$('#recoveryPassInputPin').val(self.i18n.msg('single.use.code'));
		}
	});
	
	$(document).off('focus', '#recoveryPassInputPass_fake').on('focus', '#recoveryPassInputPass_fake', function(event) {
		self._onFocusFakePassword('recoveryPassInputPass');
		
	});
	
	$(document).off('focus', '#recoveryPassInputPassRepeat_fake').on('focus', '#recoveryPassInputPassRepeat_fake', function(event) {
		self._onFocusFakePassword('recoveryPassInputPassRepeat');
		
	});
	
	$(document).off('focus', '#recoveryPassInputPass').on('focus', '#recoveryPassInputPass', function(event) {
		self._onFocusSetPassword('recoveryPassWarningPass', event.target);
//		self._openPopOverHelper(event.target.id);
		
	});
	
	$(document).off('blur', '#recoveryPassInputPass').on('blur', '#recoveryPassInputPass', function(event) {
		self._onBlurSetPassword('recoveryPassWarningPass', event.target);
		
	});
	
	$(document).off('focus', '#recoveryPassInputPassRepeat').on('focus', '#recoveryPassInputPassRepeat', function(event) {
		self._onFocusSetPassword('recoveryPassWarningRepeatPass', event.target);
		
	});
	
	$(document).off('blur', '#recoveryPassInputPassRepeat').on('blur', '#recoveryPassInputPassRepeat', function(event) {
		self._onBlurSetPassword('recoveryPassWarningRepeatPass', event.target);
		
	});
};

RecoveryPasswordView.prototype._onFocusFakePassword = function(idPassword) {
	$('#' + idPassword + '_fake').addClass('hide');
	$('#' + idPassword).removeClass('hide');
	$('#' + idPassword).focus();
};

RecoveryPasswordView.prototype._onFocusSetPassword = function(idWarning, elem) {

	var self = this;
	 
	if(!$(elem).hasClass('repeatPassword')) {
		$('#'+idWarning).removeClass('hide');
	}
};

RecoveryPasswordView.prototype._onBlurSetPassword = function(idWarning, elem) {

	var self = this;
	var defaultValue = self.i18n.msg('password.repeat');
	if(!$(elem).hasClass('repeatPassword')) {
		defaultValue = self.i18n.msg('password');
		$('#'+idWarning).addClass('hide'); 
	}
	
	if($(elem).val()==''){
		$(elem).addClass('hide');
		$('#'+ elem.id + '_fake').removeClass('hide');
	}; 
};
// First Step

RecoveryPasswordView.prototype._submitFormFirstStep = function(data) {
	var self = this;
	var login = $.trim($('#recoveryPasswordFormLogin').val());
	var hasEmptyFields = false;
	var captchaToken = '';
	if($.isNumeric(login)) {
		if(null != $('#recoveryPassCountrySelect').val() && $('#recoveryPassCountrySelect').val() != -1) {
			while(login.length < 7) {
				login = '0' + login;
			}
			login = $('#recoveryPassCountrySelect').val() + login;
			self._removeValidationWarning('recoveryPassCountryDiv', hasEmptyFields);
		}else {
			hasEmptyFields = true;
			self._addValidationWarning('recoveryPassCountryDiv');
		}		
	}
	if(login == '' || login == self.i18n.msg('num.employee.user.office.info')) {
		hasEmptyFields = true;
		self._addValidationWarning('recoveryPasswordFormLogin');
	} else {
		self._removeValidationWarning('recoveryPasswordFormLogin', hasEmptyFields);
	}
	
	var data = captcha.val();
	if(captcha.isRequired() && $.isEmptyObject(data)) {
		hasEmptyFields = true;
		self._addValidationCaptchaWarning();
	} else {
		self._removeValidationCaptchaWarning(hasEmptyFields);
	}
	
	if(!hasEmptyFields) {
		$('body').loader('show');
		self.userServiceFacade.getDeliveryType(login, data, self._onSuccessGetDeliveryType, self._onErrorGetDeliveryType, this);
	} 
};

RecoveryPasswordView.prototype._onSuccessGetDeliveryType = function(data) {
	var self = this;
	if(data.userValid == true) {
		self.fullName = data.name + ' ' + data.lastName;
		self.deliveryType = data;
		self._renderSecondStep(data);
	} else {
		if(data.code == '98') {
			self.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, data.message, 'messageArea');
		} else {
			self.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, self.i18n.msg('error.user.not.valid'), 'messageArea');
		}
		this.loadCaptcha();
	}
};


RecoveryPasswordView.prototype._onErrorGetDeliveryType = function(response, textStatus, errorThrown) {
	this.loadCaptcha();
	$('body').loader('hide');
	this.messageHandler.handleErrors(response, 'messageArea');	
};

RecoveryPasswordView.prototype._onSuccessGetDeliveryTypeFromRecoverUser = function(data) {
	var self = this;
	self._onSuccessGetDeliveryType(data);
	self._initHandlers();
}


RecoveryPasswordView.prototype._onErrorGetDeliveryTypeFromRecoveryUser = function(response, textStatus, errorThrown) {
	var self = this;
	self._init();
	$('body').loader('hide');
	self.messageHandler.handleErrors(response, 'messageArea');
};


RecoveryPasswordView.prototype._renderSecondStep = function(data) {
	var action = 'recoveryPasswordStep2';
	var params = {
			mail: data.mail,
			login: data.login,
			i18n: this.i18n,
			mobile: data.mobile,
	}
	this._loadStep(action, params, 'recoveryPassword');
	if(i18n.msg('msg.info.noSendData.' + data.country) != 'msg.info.noSendData.'+ data.country) {
		$('#textoNoSendData').html(i18n.msg('msg.info.noSendData.' + data.country));
		$('#textoSendDataNoCorrect').html(i18n.msg('msg.info.noSendData.' + data.country));
	} else {
		$('#textoNoSendData').html(i18n.msg('msg.info.noSendData'));
		$('#textoSendDataNoCorrect').html(i18n.msg('msg.info.sendDataNoCorrect'));
		
	}
	this.resetCaptcha();
	this.loadCaptcha();
};

// Second Step

RecoveryPasswordView.prototype._submitFormSecondStep = function() {
	var self = this;
	var checked = $("input.radioButtonSendPin:checked").val();
	var login = $('#loginFormStep2').val();
	var captchaToken = '';
	var hasEmptyFields = false;
	
	if(checked) {
		
		var data = captcha.val();
		if(captcha.isRequired() && $.isEmptyObject(data)) {
			hasEmptyFields = true;
			self._addValidationCaptchaWarning();
		} else {
			self._removeValidationCaptchaWarning(hasEmptyFields);
		}
		$('body').loader('show');
		data.deliveryType = checked;
		self.userServiceFacade.sendPIN(login, data, self._onSuccessSendPIN, self._onErrorSendPIN, this);
	} else {
		self.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, self.i18n.msg('msg.info.selectWhereToSend'), 'messageArea');
	}
};


RecoveryPasswordView.prototype._onSuccessSendPIN = function(data) {
	var login = $('#loginFormStep2').val();
	var params = {
			login: login,
	}
	if(data && data.sent == 'true') {
		this._renderThirdStep(params);
	} else {
		if(data && data.code == '98') {
			this.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, data.message, 'messageArea');
		} else {
			this.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, this.i18n.msg('error.internal'), 'messageArea');
		}
		this.loadCaptcha();
	}

	
};

RecoveryPasswordView.prototype._onErrorSendPIN = function(response, textStatus, errorThrown) {
	this.loadCaptcha();
	this.messageHandler.handleErrors(response, 'messageArea');
};


// Third Step

RecoveryPasswordView.prototype._renderThirdStep = function(params) {
	var action = 'recoveryPasswordStep3';
	this._loadStep(action, params, 'recoveryPassword');
	this.resetCaptcha();
	this.loadCaptcha();
	
	var minSize = 8;
	
	if(this.deliveryType != null && this.deliveryType.cpType == 1) {
		minSize = 12;
	}
	
	var textWarning = i18n.msg('msg.info.password.secure');
	textWarning = textWarning.replace('<size>', minSize);
	$('#recoveryPassWarningPassTextoAviso').html(textWarning);
	
	var passwordValidation = $('#recoveryPassInputPass').passwordValidation({
		'lowerCaseRequired' : true,
		'upperCaseRequired' : true,
		'minSize' : minSize,
		'simbolRequired' : false,
		'numberRequired' : true,
		'acceptInvalidCaracters' : true,
		'verifyName' : this.fullName
	});
	
	$('body').click(function(event) {
		if(event.target.id != 'recoveryPassInputPass' && event.target.id != 'recoveryPassInputPass_fake') {
			passwordValidation.passwordValidation('hide');
		}
		
	});
	
	$('#recoveryPassInputPin').focus(function() {
		passwordValidation.passwordValidation('hide');
	});
	
	$('#recoveryPassInputPassRepeat').focus(function() {
		passwordValidation.passwordValidation('hide');
	});
	
	 $('.mCSB_container').attrchange({
			trackValues: true, /* Default to false, if set to true the event object is 
			updated with old and new value.*/
			callback: function (event) { 
				if($('.popover').prop('style')) {
					var top = event.target.style.top.replace('px', '');
					var oldValueStr = event.oldValue;
					var oldValueNormal = '';
					
					
					var oldTopValue = (inet.parseStringToObject(event.oldValue).top != undefined && inet.parseStringToObject(event.oldValue).top != null) ? inet.parseStringToObject(event.oldValue).top.replace('px', '') : '';
					var newTopValue = (inet.parseStringToObject(event.newValue).top != undefined && inet.parseStringToObject(event.newValue).top != null) ? inet.parseStringToObject(event.newValue).top.replace('px', '') : '';
					
					if(oldTopValue == '' || newTopValue == '') {
						return;
					}
					var newTop = Number($('.popover').prop('style').top.replace('px', '')) + Number((newTopValue - oldTopValue));
					
					$('.popover').prop('style').top = newTop + 'px';
				}
	    }
	 });
};

RecoveryPasswordView.prototype._submitFormThirdStep = function() {
	var self = this;
	var pin = $('#recoveryPassInputPin').val();
	var pass = $('#recoveryPassInputPass').val();
	var passRepeat = $('#recoveryPassInputPassRepeat').val();
	var login = $('#loginFormStep3').val();
	var hasEmptyFields = false;
	var captchaToken = '';
	
	if(pin != '' && pin != self.i18n.msg('single.use.code')) {
		self._removeValidationWarning('recoveryPassInputPin', hasEmptyFields);
	} else {
		self._addValidationWarning('recoveryPassInputPin');
		hasEmptyFields = true;
	}
	
	if(pass != '' && pass != self.i18n.msg('')) {
		self._removeValidationWarning('recoveryPassInputPass_fake', hasEmptyFields);
		self._removeValidationWarning('recoveryPassInputPass', hasEmptyFields);
	} else {
		self._addValidationWarning('recoveryPassInputPass_fake');
		self._addValidationWarning('recoveryPassInputPass');
		hasEmptyFields = true;
	}
	
	if(passRepeat != '' && passRepeat != self.i18n.msg('')) {
		self._removeValidationWarning('recoveryPassInputPassRepeat_fake', hasEmptyFields);
		self._removeValidationWarning('recoveryPassInputPassRepeat', hasEmptyFields);
	} else {
		self._addValidationWarning('recoveryPassInputPassRepeat_fake');
		self._addValidationWarning('recoveryPassInputPassRepeat');
		hasEmptyFields = true;
	}
	
	var data = captcha.val();
	if(captcha.isRequired() && $.isEmptyObject(data)) {
		hasEmptyFields = true;
		self._addValidationCaptchaWarning();
	} else {
		self._removeValidationCaptchaWarning(hasEmptyFields);
	}
	
	if(hasEmptyFields == false) {
		if(pass != passRepeat) {
			
			self.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, self.i18n.msg('error.password.repeat'), 'messageArea');
			
		} else {
			if($('#recoveryPassInputPass').attr('valid') != 'true') {
				self.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, self.i18n.msg('pwd.validator.invalidPassMsg'), 'messageArea');
			} else {
				var g_recaptcha_response = (data['g-recaptcha-response']) ? data['g-recaptcha-response'] : null;
				var recaptcha_response_field = (data.recaptcha_response_field) ? data.recaptcha_response_field : null;
				var uid = (data.uid) ? data.uid : null;
				var passwordPinDto = {
					'password' : pass,
					'pin': pin,
					'countryCode' : (data.countryCode) ? data.countryCode : null			
				}
				if(g_recaptcha_response != null) {
					passwordPinDto['g-recaptcha-response'] = g_recaptcha_response;
				}
				if(recaptcha_response_field != null) {
					passwordPinDto['recaptcha_response_field'] = recaptcha_response_field;
				}
				if(uid != null) {
					passwordPinDto['uid'] = uid;
				}
				$('body').loader('show');
				self.userServiceFacade.changePassword(login, passwordPinDto, self._onSuccessChangePassword, self._onErrorChangePassword, this);
			}
		}
	}
	
};

RecoveryPasswordView.prototype._onSuccessChangePassword = function(data) {
	var self = this;
	if(data.changed == 'true') {
		var action = 'recoveryPasswordFinalStep';
		var params = {
				'login' : $('#loginFormStep3').val()
				}
		self._loadStep(action, params, 'recoveryPassword');
		$('body').loader('hide');
	} else {
		this.loadCaptcha();
		self.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_ERROR, self.i18n.msg('error.password.notChanged'), 'messageArea');
	}
};

RecoveryPasswordView.prototype._onErrorChangePassword = function(response, textStatus, errorThrown) {
	this.loadCaptcha();
	this.messageHandler.handleErrors(response, 'messageArea');
};

//Fourth Step

RecoveryPasswordView.prototype._submitFormFourthStep = function(event) {
	
	var login = $('#loginFormStepFinal').val();
	if(login) {
		$('#userLogin').val(login);
	}
	$('#recoveryView').modal('hide');
	$('#real_pass').focus();
	
};


RecoveryPasswordView.prototype._processChangeInputUserLogin = function() {
	if($.isNumeric($('#recoveryPasswordFormLogin').val())) {
		$('#recoveryPassCountryDiv').removeClass('hide');
		$('#recoveryPassCountryValidationDiv').removeClass('hide');
	} else {
		$('#recoveryPassCountryValidationDiv').addClass('hide');
		$('#recoveryPasswordFormLogin').focus();
	}
};

RecoveryPasswordView.prototype._addValidationWarning = function(idDiv) {
	var self = this;
	$('#' + idDiv).addClass('rojo');
	this.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_REQUIRED_FIELD, this.i18n.msg('error.required.field'), 'messageArea');
};

RecoveryPasswordView.prototype._removeValidationWarning = function(idDiv, hasEmptyFields) {
	$('#' + idDiv).removeClass('rojo');
	if(!hasEmptyFields) {
		$('#texto_alerta').removeClass('texto_alerta_rojo');
	}
};

RecoveryPasswordView.prototype._addValidationCaptchaWarning = function() {
	var self = this;
	captcha.addBorderValidation();
	this.messageHandler.showMessage(this.messageHandler.MESSAGE_TYPE_REQUIRED_FIELD, this.i18n.msg('error.required.field'), 'messageArea');
};

RecoveryPasswordView.prototype._removeValidationCaptchaWarning = function(hasEmptyFields) {
	captcha.removeBorderValidation();
	
	if(!hasEmptyFields) {
		$('#texto_alerta').removeClass('texto_alerta_rojo');
	}
};

RecoveryPasswordView.prototype._processMaxLength = function(event) {
	if(event.target.value.length >= 30) {
		event.preventDefault();
	}
};

/**
 * Actualiza la imagen del captcha
 */
RecoveryPasswordView.prototype.refreshCaptcha = function(countryCode) {
	var self = this;
	
	var data = {'countryCode': countryCode};
	
	self.userServiceFacade.refreshCaptchaImg(data, self._onSuccessRefreshCaptchaImg, self._onErrorRefreshCaptchaImg)
};

RecoveryPasswordView.prototype._onSuccessRefreshCaptchaImg = function(data) {
	var self = this;
	if(data.image) {
		$('#jCaptchaImg').attr('src', 'data:image/png;base64,' + data.image);
		$('#jCaptchaInput').val('');
		if($('#jCaptchaDiv').hasClass('hide')) {
			$('#jCaptchaDiv').removeClass('hide');
		}
		self.sessionToken = data.uid;
	}  else {
		$('#jCaptchaDiv').removeClass('hide');
	}
};

RecoveryPasswordView.prototype._onErrorRefreshCaptchaImg = function(response, textStatus, errorThrown) {
	this.messageHandler.handleErrors(response, 'messageArea');
	
};