$(function () {	
	
	$.ajaxSetup({cache: false});
	
	var widgetId1 = null;
	var send = null;

	var lmsg = $('#login-message');
	
	$(window).load(function(){
	    
		$('.captcha').fadeIn();
		widgetId1 = grecaptcha.render('gcaptcha', {
            'sitekey' : '6Lfu8ygTAAAAABAp2oNd8GL8kBO5IL5WLBLS2-er',
            'theme' : 'light'
		});
	})
	
	
	$.fn.start_captcha = function()
	{
	    $('.captcha').fadeIn();
		widgetId1 = grecaptcha.render('gcaptcha', {
            'sitekey' : '6Lfu8ygTAAAAABAp2oNd8GL8kBO5IL5WLBLS2-er',
            '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="message login-waiting bg-warning"><p>Aguarde enquanto as informações são validadas.</p></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 bg-warning"><p>Por favor preencher Login e Senha.</p></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 bg-warning"><p>Por favor preencher o campo Login.</p></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 bg-warning"><p>Por favor preencher o campo Senha.</p></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 bg-warning"><p>Por favor preencher o captcha.</p></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 bg-warning"><p>Captcha incorreto, favor tentar novamente.</p></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 bg-success"><p>Login efetuado com sucesso.</p></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 bg-danger"><p>'+success.error+'</p></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 bg-warning"><p>Falha de Comunicação com o Servidor.</p></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 val = $('#password-recovery input[name=recovery-mail]').val()

		var target = $(this).attr('action');
		
		// Request
		var data = {
			recoveryMail: val
		}
			
		$.ajax({
			url: target,
			dataType: 'json',
			type: 'POST',
			cache: false,
			data: data,
			success: function(success)
			{					
				$("body").css("cursor", "default");
				$('fieldset').addClass('collapsed');
				$('#password-recovery input[name=recovery-mail]').val('')
				alert(success.message)
			},
			error: function(error)
			{
				$("body").css("cursor", "default");
				alert(error)
			}
		})
		
		return false;	
		
	});
	
	/*$("#card").flip({
		trigger: 'manual'
	});*/
	
	$('.click-change-view').click(function(e){
		e.preventDefault();
		
		$("#card").flip(true);
	})
	
	$('.click-change-view2').click(function(e){
		e.preventDefault();
		
		$("#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')
    	}
    });*/
	
});