$(document).ready(function(){
    //Preloading image ;D
    var img = $('<img />').attr('src', '../image/bot_acessar02.png');

	$('#user').focus();

    $('form').submit(function(){
        return false;
    });

	$('#user').keypress(function(e){
		$('#type').hide();
        if (e.keyCode == 13)
        {
            $(this).blur();
            $('#passwd').focus();
        }
	});
	
	$('#passwd').keypress(function(e){
		if (e.keyCode == 13)
        {
            var uType = $('#access');

            if (uType.is(':visible'))
            {
                uType.focus();
            }
            else
            {
                processLogin();
            }
        }
	});

    $('#access').keypress(function(e){
        if (e.keyCode == 13)
        {
            processLogin();
        }
    });

    $("#forgetpasswd").click(forgetPassword);

	$('#user').blur(function()
        {
            $('#type').hide();

            $('#access').empty();
            carregaTipoUser();
        if ($(this).val().length != 0)
        {
    		$.post(
    			'../php/usuario_controle.php',
    			{
    				usuario: $(this).val()
    			},
    			function(r){
    				if (r.length > 1)
    				{
    					$('#type').show();
    					options = "";
    					for(i = 0;i < r.length; i++)
    					{
    						options += '<option value="'+ r[i].value +'">' + r[i].text + '</option>' + "\n";
    					}
    					$('#access').append(options);
    				}
    				else
    				{
    					$('#type').hide();
    				}
    			},
    			'json'
    		);
        }
	});

	$('#login').click(processLogin);
});

function forgetPassword()
{
    var user = $('#user');

    if(user.val().length == 0)
    {
        alert('Por favor informe o usuário!');
        user.focus();
    }
    else
    {
        $.post(
            '../php/recuperarSenha.php',
            {
                login : $('#user').val()
            },
            function(r)
            {
                alert('Atenção!\n' + r);
            },
            'json'
        );
    }
}

function processLogin(sender)
{
    $('#textfields').hide();
    $('#loading').show();

    $.post(
        "../php/login.php",
        $('input, select').serialize(),
        function(r)
        {
            //alert(r);
            r = parseInt(r);

            switch(r)
            {
                case 1:
                        window.location.replace("./?Main");
                        break;
                case 2:
                        window.location.replace("./?Main");
                        break;
                case 3:
                        window.location.replace("./?Main");
                        break;
                case 4:
                        window.location.replace("./?Main");
                        break;
                case 5:
                        alert(unescape("Dados do Período Letivo ainda não foram disponibilizados."));
                        $('#user').val("");
                        $('#passwd').val("");
                        $('#user').focus();
                        break;
                case 6:
                        window.location.replace("tela_pre_acesso.php");
                        break;
                case 7:
                        alert(unescape("O seu acesso foi desabilitado. Contate o administrador do sistema para mais informações."));
                        loading();
                        break;
                case 8:

                        break;
                case 9:
                        window.location = "./?Manutencao";
                        break;
                case 10:
                        window.location.replace("./?Main");
                        break;
                default:
                        alert("Senha e/ou Usuário incorreto!\nDigite novamente!");
                        loading();
            }
        },
        'json'
    );
}

function loading()
{
    $('#loading').hide();
    $('#textfields').show();
    $('#passwd').val("");
    $('#passwd').focus();
}

function carregaTipoUser()
{
    $('#carregandoTipoUser').ajaxStart(function()
    {
        var el = $(this);
        el.show();
        el.text('Aguarde, carregando permissões.');

        loadingPermissions();
    }).ajaxStop(function()
    {
        $(this).hide();
        i = '';
    });
}

var i = '';
function loadingPermissions()
{
    var el = $('#carregandoTipoUser');
    if(el.is(':visible'))
    {
        if(i.length == 3)
        {
            i = '';
        }
        else
        {
            i += '.';
        }
        el.text('Aguarde, carregando permissões.' + i);
        setTimeout(loadingPermissions, 500);
    }
}