$(function () {	
    
    $('#content-error-senha').hide();
    $('#change-password').on('click', function() {
       if ($("#content-error-senha").text().length > 0) {
            $('#content-error-senha').show();
        } 
    });
    
    /*$(window).load(function(){
        $('.back').show();
    })*/
	
	$.ajaxSetup({cache: false});
	
	var widgetId1 = null;
	var send = null;

	var lmsg = $('#login-message');
	
	$(window).on('load',function(){
	    
	    $('.back').show();
		
		var target = $(this).attr('action');
		
		// Request
		var data1 = {
			login: ''
		};
		
		$.ajax({
			url: base_url + 'auth/consulta_captcha',
			dataType: 'json',
			type: 'POST',
			cache: false,
			data: data1,
			success: function(success)
			{	
				if(success.result == true){
					$(this).start_captcha();
				}
			}
		})
	})
	
	$.fn.start_captcha = function()
	{
		$('.captcha').fadeIn();
		widgetId1 = grecaptcha.render('gcaptcha', {
            'sitekey' : sitekey,
            'theme' : 'light'
		});
	}
	
	$('#login_form input[name=username]').keyup(function(){
		if(event.keyCode != 13)
		{
			$('.message').remove();
		}
	});

	$('#login_form input[name=password]').keyup(function(event){
		if(event.keyCode != 13)
		{
			$('.message').remove();
		}				
	});
	
	$.fn.ini_login = function() 
	{		
		$("body").css("cursor", "wait");
		var str = '<div class="gif-message login-waiting alert alert-warning">Estamos validando as suas credenciais.</div>';
		lmsg.find('.message').remove();
		lmsg.html(str);
		
		$('input[name=data-send]').attr('value','1').trigger('change');
	}
	
	$('input[name=data-send]').change(function(){
		var send = $(this).val();
		if(send == '1')
		{
			$(this).val(0)
			setTimeout(function(){
				$(this).send_login();
			},1);
		}
	})
	
	$.fn.send_login = function()
	{		
		var form = $('#login_form');
		var login = form.find('input[name=username]').val();
		var senha = form.find('input[name=password]').val();
				
		if(login == '' && senha == '')
		{
			$('.message').remove()
			lmsg.html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Por favor preencher Login e Senha.</div>');
			if(widgetId1 != null)
			{
				grecaptcha.reset(widgetId1)
			}
			$("body").css("cursor", "auto");
			return false
		}
		else if(login == ''){
			$('.message').remove()
			lmsg.html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Por favor preencher o campo Login.</div>');
			if(widgetId1 != null)
			{
				grecaptcha.reset(widgetId1)
			}
			$("body").css("cursor", "auto");
			return false
		}else if (senha == '') {
			$('.message').remove()
			lmsg.html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Por favor preencher o campo Senha.</div>');
			if(widgetId1 != null)
			{
				grecaptcha.reset(widgetId1)
			}
			$("body").css("cursor", "auto");
			return false
		}		
		if(widgetId1 != null)
		{
			var captcha = form.find('textarea[name=g-recaptcha-response]').val();
			if(captcha == '')
			{
				$('.message').remove()
				lmsg.html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Por favor preencher o captcha.</div>');
				$("body").css("cursor", "auto");
				return false
			}
			else
			{
				var valid = $(this).valida_captcha(captcha);
				if(valid != true)
				{
					$('.message').remove()
					lmsg.html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Captcha incorreto, favor tentar novamente.</div>');
					if(widgetId1 != null)
					{
						grecaptcha.reset(widgetId1)
					}					
					$("body").css("cursor", "auto");
					return false
				}
			}
		}
		
		var target = form.attr('action');
		
		encrypt_form(form,function(value) {
			 var str = value;
			 
			 $(this).ajax_form_action(login,str,target);
		});
		
		
	}
	
	$.fn.ajax_form_action = function(login,str,target)
	{
		// Request
		var data = {
			 str: str
		};
		
		$.ajax({
			url: target,
			dataType: 'json',
			type: 'POST',
			cache: false,
			data: data,
			async: true,
			success: function(success)
			{					
					if (success.valid)
					{
						$('.message').remove()
						lmsg.html('<div class="message login-success alert alert-success"><i class="fa fa-check fa-lg mr-2"></i>Login efetuado com sucesso.</div>');
						
						setTimeout(function() {
							$("body").css("cursor", "auto");
							document.location.href = success.redirect;
						}, 1000);							
					}
					else
					{ 
						$.post( base_url + 'auth/consulta_captcha',{ login: login }, function(resposta){	
							obj = jQuery.parseJSON( resposta );
							if(obj.result == true && widgetId1 == null){
								$(this).start_captcha();
							}
						})
						
						$('.message').remove()
						lmsg.html('<div class="message login-error alert alert-danger"><i class="fa fa-remove fa-lg mr-2"></i>'+success.error+'</div>');
						
						$("body").css("cursor", "auto");
						
						if(widgetId1 != null)
						{
							grecaptcha.reset(widgetId1)
						}
						
						// setTimeout(function() {	}, 2000); // wait 2 seconds
					}
			},
			error: function(error)
			{
				if(widgetId1 != null)
				{
					grecaptcha.reset(widgetId1)
				}
				$("body").css("cursor", "auto");
				$('.message').remove()
				lmsg.html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Falha de Comunicação com o Servidor.</div>');
			}
		});
	}
	
	$( "#login_form" ).on( "submit", function( event ) {
		
		event.preventDefault();
		
		$(this).ini_login();
	})
	
	$.fn.valida_captcha = function(captcha)
	{
		// Request
		var data = {
			response: captcha
		};
		
		var retorno = '';
		
		$.ajax({
			url: base_url+'auth/check_google_captcha', 
			dataType: 'json',
			type: 'POST',
			data: data,
			async: false,
			success: function(result)
			{			
				obj = jQuery.parseJSON( result );
				if (obj.success == true)
				{
					retorno = true;							
				}
				else
				{ 
					retorno = false;
				}
			},
			error: function(error)
			{
				retorno = false;
			}
		});
		
		return retorno;
	}
	
	$('#password-recovery').submit(function(event){	
		
		$("body").css("cursor", "progress");
		
		var email = $('#password-recovery input[name=email]').val()

		var target =  base_url +"auth/auth/esqueci_a_senha";
		
		// Request
		var data = {
			email: email
		}
			
		$.ajax({
			url: target,
			dataType: 'json',
			type: 'POST',
			data: data,
			success: function(success)
			{					
				$("body").css("cursor", "default");
				$('fieldset').addClass('collapsed');
				$('#password-recovery input[name=mail]').val('');
				
				if(success.valid == true)
				{
                    showModal('Sucesso!', success.msg, 'success');
				}
				else
				{
                    showModal('Erro!', success.msg, 'danger');
				}
			},
			error: function(error)
			{
				$("body").css("cursor", "default");
				console.log(error)
			}
		})
		
		return false;	
		
	});
	
	$('#change-password').click(function()
	{	
		var nova_senha       = $('#form_nova_senha input[name=password]').val()
		var conf_nova_senha  = $('#form_nova_senha input[name=password-conf]').val()
		
		var target = base_url +"auth/auth/atualizar_senha";
		
		var data = {
				nova_senha: nova_senha,
				conf_nova_senha: conf_nova_senha
			}
		
		$.ajax({
			url: target,
			dataType: 'json',
			type: 'POST',
			data: data,
			success: function(retorno)
			{		
				if (retorno.valid === true)
				{
			        $('#myModal').modal('hide')
                    showModal('Sucesso!', retorno.msg, 'success');
				}
				else
				{
					$("input[id=nova_senha]").val("");
					$("input[id=conf_nova_senha]").val("");		           
			        
			        $('#content-error-senha').removeClass('hide');
			        $('#content-error-senha').html(retorno.msg);
				}
			},
			error: function(error)
			{
				$("input[id=nova_senha]").val("");
				$("input[id=conf_nova_senha]").val("");
				
				$('#content-error-senha').show();
			    $('#content-error-senha').html('<label class="error-login text-danger">Não foi possível atualizar a senha. Tente novamente mais tarde.</label>');
			}
		});
		return false;
	}); 
	
	$("#card").flip({
		trigger: 'manual'
	});
	
	$('.click-change-view').click(function(e){
		e.preventDefault();
		
		$("#card").flip(true);
		var visible = $('.back').css( "display" );
		if(visible == 'none') {
		    setTimeout( function(){ 
                 $('.back').show();
            }  , 350 );
		}
		
		$("#passeye-toggle-0").addClass('hide-on-flip');
		$(".captcha").addClass('hide-on-flip');
	})
	
	$('.click-change-view2').click(function(e){
		e.preventDefault();
		
        $(".captcha").removeClass('hide-on-flip');
        $("#passeye-toggle-0").removeClass('hide-on-flip');
        
		$("#card").flip(false);
	})
	
	/*$(window).on('resize',function(){
    	
    	var larguraTela = $(window).width();
    	//console.log('largura da tela:'+ larguraTela);
    	if(larguraTela > 1320 && larguraTela <= 1709)
    	{
    		$('.content_login').removeClass('col-md-offset-2').addClass('col-md-offset-1')    		
    	}
    	elseif(larguraTela <= 1320)
    	{
    		$('.content_login').removeClass('col-md-offset-2').removeClass('col-md-offset-1')
    	}
    });*/
    
    $("input[type='password'][data-eye]").each(function(i) {
		var $this = $(this),
			id = 'eye-password-' + i,
			el = $('#' + id);

		$this.wrap($("<div/>", {
			style: 'position:relative',
			id: id
		}));

		$this.css({
			paddingRight: 60
		});
		$this.after($("<div/>", {
			html: 'Mostrar',
			class: 'btn btn-primary btn-sm',
			id: 'passeye-toggle-'+i,
		}).css({
				position: 'absolute',
				right: 10,
				top: ($this.outerHeight() / 2) - 12,
				padding: '2px 7px',
				fontSize: 12,
				cursor: 'pointer',
		}));

		$this.after($("<input/>", {
			type: 'hidden',
			id: 'passeye-' + i
		}));

		var invalid_feedback = $this.parent().parent().find('.invalid-feedback');

		if(invalid_feedback.length) {
			$this.after(invalid_feedback.clone());
		}

		$this.on("keyup paste", function() {
			$("#passeye-"+i).val($(this).val());
		});
		$("#passeye-toggle-"+i).on("click", function() {
			if($this.hasClass("show")) {
				$this.attr('type', 'password');
				$this.removeClass("show");
				$(this).removeClass("btn-outline-primary");
			}else{
				$this.attr('type', 'text');
				$this.val($("#passeye-"+i).val());				
				$this.addClass("show");
				$(this).addClass("btn-outline-primary");
			}
		});
	});
});