function Captcha() {
	var self = this;
	self._init();
};

Captcha.prototype._init = function() {
	var self = this;
	
	self.idRecaptcha = null;
	self.jCaptcha = '<div class="captchaImgDiv"><img id="jCaptchaImg" src=""></div><div id="jCaptchaRefresh" class="captchaRefresh rotate"></div><div><input id="jCaptchaInput" class="textCaptcha" type="text" value="<% print(i18n.msg(\'enter.captcha\')) %>"></div>';
	self.uid = null;
	self.div = null;
	self.grecaptchaLoaded = false;
	self.waitForLoad = null;
	self.data = null;
	
};

/**
 * Renderiza el captcha en base a la localizacion del usuario.
 */
Captcha.prototype.render = function(data, div) {
	var self = this;
	if(!div) {
		div = 'captchaDiv';
	}
	self.div = div;
	self.data = data;
	if(inet.countryCode == undefined) {
		self.waitForLoad = true;
		return;
	}
	// si se han excedido los intentos, se renderiza el captcha
	if(data.exceeds == 'true') {
		// si el usuario no accede desde china se renderiza el captcha de google
		if(inet.countryCode && inet.countryCode.toUpperCase() != 'CN') {
			// si se ha cargado la libreria de google se renderiza el captcha
			if(self.grecaptchaLoaded) {
				self.waitForLoad = false;
				var captchaDiv = document.getElementById(div);
				if(self.idRecaptcha != null && self.idRecaptcha != undefined) {
					grecaptcha.reset(self.idRecaptcha);
				} else {
					
					self.idRecaptcha = grecaptcha.render(captchaDiv, {
						'sitekey' : inet.siteKey
					});
					$('#'+div).addClass('recoveryPassCaptcha validatorCaptcha inlineBlock');
				}
			} else {
				// si no, se espera a que se termine de cargar la librería
				self.waitForLoad = true;
			}
		} else {
			// si el usuario accede desde china o no se conoce su procedencia se renderiza jcaptcha
			$('#' + div).html(self.jCaptcha);
			$('#jCaptchaImg').attr('src', 'data:image/png;base64,' + data.image);
			$('#jCaptchaInput').val(i18n.msg('enter.captcha'));
			$('#' + div).removeClass('hide');
			self.uid = data.uid;
			
			// se inicializan los eventos
			$(document).off('click', '#jCaptchaRefresh').on('click', '#jCaptchaRefresh', function(event){
				self.reset();
			});
			
			$(document).off('focus', '#jCaptchaInput').on('focus', '#jCaptchaInput', function(event){
				self._changePlaceHolder(event, i18n.msg('enter.captcha'));
			});
			
			$(document).off('blur', '#jCaptchaInput').on('blur', '#jCaptchaInput', function(event){
				self._changePlaceHolder(event, i18n.msg('enter.captcha'));
			});
		}
		$('#'+div).removeClass('hide');
	} else {
		self.hide();
	}
	$('body').loader('hide');
	inet._setFirstFieldFormFocus();
	inet.updateScrollbar();
};

/**
 * Recupera una nueva imagen y la renderiza
 */
Captcha.prototype.reset = function(image) {
	var self = this;
	if(inet.countryCode && inet.countryCode.toUpperCase() != 'CN') {
		grecaptcha.reset(self.idRecaptcha);
	} else {
		if(image) {
			$('#jCaptchaImg').attr('src', 'data:image/png;base64,' + image);
		} else {
			var data = {
				'countryCode': inet.countryCode
			}
			userServiceFacade.refreshCaptchaImg(data, self._onSuccessRefreshCaptchaImg, self._onErrorRefreshCaptchaImg, self);
		}
	}
};

/**
 * Reinicia el div
 */
Captcha.prototype.resetDiv = function() {
	var self = this;
	self.div = null;
};

Captcha.prototype._onSuccessRefreshCaptchaImg = function(data) {
	var self = this;
	$('#jCaptchaImg').attr('src', 'data:image/png;base64,' + data.image);
	self.uid = data.uid;
};

Captcha.prototype._onErrorRefreshCaptchaImg = function(response, textStatus, errorThrown) {
	messageHandler.handleErrors(response, 'messageArea');
};

/**
 * Devuelve el objeto del captcha que se debe enviar al servicio
 */
Captcha.prototype.val = function() {
	var self = this;
	var value = {};
	if(inet.countryCode && inet.countryCode.toUpperCase() != 'CN') {
		var captchaToken = $('.g-recaptcha-response').val();
		if(captchaToken != '') {
			value = {
				'g-recaptcha-response': captchaToken,
				'countryCode' : inet.countryCode
			}
		}
	} else {
		var captchaText = $('#jCaptchaInput').val();
		if(captchaText != '' && captchaText != i18n.msg('enter.captcha')) {
			value = {
				'recaptcha_response_field': captchaText, 
				'uid': self.uid, 
				'countryCode' : inet.countryCode
			};
		}
	}
	return value;
};

/**
 * Comprueba si es necesario cubrir el captcha
 */
Captcha.prototype.isRequired = function() {
	var self = this;
	var required = false;
	if(self.div) {
		required = !$('#'+self.div).hasClass('hide');
	}
	return required;
	
};

/**
 * Establece un borde rojo al captcha
 */
Captcha.prototype.addBorderValidation = function() {
	var self = this;
	if(inet.countryCode && inet.countryCode.toUpperCase() != 'CN') {
		$('#'+self.div).addClass('rojo');
	} else {
		$('#jCaptchaInput').addClass('rojo');
	}
	
};

/**
 * Elimina el borde rojo del captcha
 */
Captcha.prototype.removeBorderValidation = function() {
	var self = this;
	if(inet.countryCode && inet.countryCode.toUpperCase() != 'CN') {
		$('#'+self.div).removeClass('rojo');
	} else {
		$('#jCaptchaInput').removeClass('rojo');
	}
	
};

/**
 * Elimina el captcha de la pantalla
 */
Captcha.prototype.hide = function() {
	var self =  this;
	
	$('#'+ self.div).html('');
	$('#'+ self.div).addClass('hide');
	
	if($('.gc-bubbleDefault').parent()) {
		$('.gc-bubbleDefault').parent().remove();
		$('ins').remove();
	}
	
	self.captchaDiv=$('#' + self.div);
	if(self.captchaDiv){var parentCaptcha=$(self.captchaDiv).parent();
		$(self.captchaDiv).remove();
		parentCaptcha.append('<div id="'+self.div+'" class="hide"></div>');
	}
	self.div=null;
	self.idRecaptcha=null;
};

Captcha.prototype._changePlaceHolder = function(event, placeHolder) {
	var self = this;
	
	var target = $('#'+event.target.id);
	
	if(event.type == 'focusin') {
		// Se comprueba el texto, si es igual al placeHolder, se establece el valor a '' y si es distinto se mantiene
		if(target.val() == placeHolder) {
			target.val('');
		}
	} else if(event.type == 'focusout') {
		// Se comprueba el texto introducido, si es igual a '' se vuelve a poner el placeHolder, si no, se mantiene.
		if(target.val() == '') {
			target.val(placeHolder);
		}
	}
	
};

Captcha.prototype.onLoadGRecaptcha = function() {
	var self = this;
	self.grecaptchaLoaded = true;
	if(self.waitForLoad) {
		self.render(self.data, self.div);
	}
}

Captcha.prototype.onLoadCaptcha = function() {
	var self = this;
	if(self.waitForLoad) {
		self.render(self.data, self.div);
	}
}

var captcha = new Captcha();