﻿//
// 17/05/2010 12:30
//

$(document).ready(function() {

    //
    // para os casos em que for o CRC/PR precisa carregar um mecanismo
    // de máscara para o campo Nº do CRC
    var tipo = QueryString('type').toLowerCase();

    if (tipo == 'crcpr') {
        $("#ctl00_conteudo_txtLogin").keyup(function(e) {
            maiuscula($("#ctl00_conteudo_txtLogin")[0], e);
        });

        $("#ctl00_conteudo_txtLogin").keypress(function(e) {
            maskCRC($("#ctl00_conteudo_txtLogin")[0], e);
        });
    }

    $("#ctl00_conteudo_trButton").click(function() {
        //
        // obtém um validador para o contexto de login, ou seja, dependendo
        // do valor no campo 'type' da querystring ele escolhe um
        var validador = new ValidadorFactory().ObterValidador();

        if (validador)
        //
        // valida o formulário conforme as regras do validador
            return validador.Validar();
        else
        //
        // you ... shall not .... pass (LOR: Gandalf stopping the Balrog in Minas Tirinth)
            return false;
    });

});

////
//// ======== ValidatorFactory ===============================================
////

//
// Factory que escolhe um modelo de validação para ser utilizado pelo
// formulário de login levando em conta o valor no campo 'type' que é
// passado na query string
function ValidadorFactory() {
    //
    // Método que obtém o tipo do contexto
    function ObterType() {
        return QueryString('type').toLowerCase();
    }

    //
    // Método que devolve um validador baseando-se no contexto
    // Caso não exista um vinculado, devolve 'undefined'
    this.ObterValidador = function() {
        var tipo = ObterType();

        if (tipo == "comercial")
            return new Validador_Comercial();

        if (tipo == "crcpe")
            return new Validador_CRCPE();

        if (tipo == "crcpr")
            return new Validador_CRCPR();

        if (tipo == "" || tipo == "default")
            return new Validador_Default();

        return undefined;
    }
}

////
//// ======== ValidadorAbstrato ==============================================
////

function ValidadorAbstrato() {

    //
    // Valida que o campo está preenchido
    this.ValidarRequerido = function(campo, nome) {
        if (campo.value == '') {
            alert('O campo ' + nome + ' é obrigatório.');
            campo.focus();
            return false;
        }
        return true;
    }

    //
    // Verifica se um valor dá match contra uma expressão regular
    this.IsMatch = function(regular, valor) {
        return new RegExp(regular, 'gi').exec(valor) != null;
    }

    //
    // Getters para os campos do formulário
    //

    this.CampoRegistro = function() {
        return theForm.ctl00_conteudo_txtLogin;
    }

    this.CampoNome = function() {
        return theForm.ctl00_conteudo_txtName;
    }

    this.CampoSenha = function() {
        return theForm.ctl00_conteudo_txtPassword;
    }

    this.CampoEmail = function() {
        return theForm.ctl00_conteudo_txtEmail;
    }

    this.CampoTelefone = function() {
        return theForm.ctl00_conteudo_txtPhone;
    }

    this.CampoCidade = function() {
        return theForm.ctl00_conteudo_txtCidade;
    }

    this.CampoUF = function() {
        return theForm.ctl00_conteudo_ddlUF;
    }

    this.CampoTipoParametro = function() {
        return theForm.ctl00_conteudo_txtParamType;
    }

    //
    // Validadores padrão para os campos
    //

    this.ValidarRegistro = function() {
        if (this.ValidarRequerido(this.CampoRegistro(), "Nº Registro"))
            return true;

        return false;
    }

    this.ValidarNome = function() {
        if (this.ValidarRequerido(this.CampoNome(), "Nome"))
            return true;

        return false;
    }

    this.ValidarSenha = function() {
        if (this.ValidarRequerido(this.CampoSenha(), "Senha"))
            return true;

        return false;
    }

    this.ValidarEmail = function() {
        if (this.IsMatch("^\\S+@\\S+$", this.CampoEmail().value))
            return true;

        alert("Informe um endereço de E-mail válido");
        this.CampoEmail().focus();
        return false;
    }

    this.ValidarTelefone = function() {
        if (this.ValidarRequerido(this.CampoTelefone(), "Telefone"))
            return true;

        return false;
    }

    this.ValidarCidade = function() {
        if (this.ValidarRequerido(this.CampoCidade(), "Cidade"))
            return true;

        return false;
    }

    this.ValidarEstado = function() {
        if (this.ValidarRequerido(this.CampoUF(), "Estado"))
            return true;

        return false;
    }
}

////
//// ======== Validador_Default ==============================================
////

function Validador_Default() {

    //
    // pega o toolkit de validação
    this.prototype = new ValidadorAbstrato();

    this.Validar = function() {
        //
        // número do registro
        if (!this.prototype.ValidarRegistro())
            return false;

        //
        // nome do cliente
        if (!this.prototype.ValidarNome())
            return false;

        //
        // senha não pode estar vazia
        if (!this.prototype.ValidarSenha())
            return false;

        return true;
    }
}

////
//// ======== Validador_Comercial ============================================
////

function Validador_Comercial() {
    //
    // pega o toolkit de validação
    this.prototype = new ValidadorAbstrato();

    this.Validar = function() {
        if (!this.prototype.ValidarNome())
            return false;

        if (!this.prototype.ValidarEmail())
            return false;

        if (!this.prototype.ValidarTelefone())
            return false;

        if (!this.prototype.ValidarCidade())
            return false;

        if (!this.prototype.ValidarEstado())
            return false;

        return true;
    }
}

////
//// ======== Validador_CRCPE ================================================
////

function Validador_CRCPE() {
    //
    // pega o toolkit de validação
    this.prototype = new ValidadorAbstrato();

    this.Validar = function() {
        if (!this.prototype.ValidarNome())
            return false;

        if (!this.prototype.ValidarEmail())
            return false;

        if (!this.prototype.ValidarTelefone())
            return false;

        if (!this.prototype.ValidarCidade())
            return false;

        if (!this.prototype.ValidarEstado())
            return false;

        return true;
    }
}

////
//// ======== Validador_CRCPR ================================================
////

function Validador_CRCPR() {

    //
    // pega o toolkit de validação
    this.prototype = new ValidadorAbstrato();

    this.Validar = function() {
        //
        // número de inscricao
        if (!this.ValidarNrCRCPR(this.prototype.CampoRegistro()))
            return false;

        //
        // campo randômico do CRC
        if (!this.ValidarCampoRandomico(this.prototype.CampoSenha()))
            return false;

        //
        // valida o endereço de e-mail
        if (!this.prototype.ValidarEmail())
            return false;

        if (!this.prototype.ValidarTelefone())
            return false;

        if (!this.prototype.ValidarCidade())
            return false;

        if (!this.prototype.ValidarEstado())
            return false;

        return true;
    }

    this.ValidarNrCRCPR = function(campo) {
        var regular = '^(AC|AL|AP|AM|BA|CE|DF|ES|GO|MA|MT|MS|MG|PA|PB|PR|PE|PI|RR|RO|RJ|RN|RS|SC|SP|SE|TO)-?(\\d{6})/?(O|P)$';

        if (this.prototype.IsMatch(regular, campo.value))
            return true;

        alert('Número inválido do CRC/PR. O número do CRC/PR precisa estar composto de:\r\n\r\n* Silga do Estado\r\n* Inscrição com 6 números\r\n* Terminador com o valor O ou P');
        campo.focus();
        return false;
    }

    this.ValidarCampoRandomico = function(campo) {
        var tipoCampo = this.prototype.CampoTipoParametro().value;

        if (tipoCampo == "ANO")
            return this.ValidarAno(campo);

        if (tipoCampo == "MES")
            return this.ValidarMes(campo);

        if (tipoCampo == "DIA")
            return this.ValidarDia(campo);
    }

    this.ValidarDia = function(campo) {
        if (this.prototype.IsMatch("^(0[1-9]|[12][0-9]|3[01])$", campo.value))
            return true;

        alert("Informe o Dia do Nascimento com dois dígitos (DD)");
        campo.focus();
        return false;
    }

    this.ValidarMes = function(campo) {
        if (this.prototype.IsMatch("^(0[1-9]|1[012])$", campo.value))
            return true;

        alert("Informe o Mês do Nascimento com dois dígitos (MM)");
        campo.focus();
        return false;
    }

    this.ValidarAno = function(campo) {
        if (this.prototype.IsMatch("(19|20)\\d\\d", campo.value))
            return true;

        alert("Informe o Ano do Nascimento com quatro dígitos (AAAA)");
        campo.focus();
        return false;
    }
}

