﻿Type.registerNamespace("LocaPag.Validacao");

//---------------------------------
// Config
//---------------------------------
LocaPag.Validacao.Config = function(id, controleId, requerido)
{
    var controle = $get(controleId);

    if (controle == null){
        setErro("Não existe um objeto com o ID informado.     \nParâmetro: controleId - Valor: " + controleId);
        return;
    }
    
    if (id == null || id.toString() == ""){
        setErro("ID de configuração não informado.     \nParâmetro: id");
        return;
    }
    
    this.id = id.toString();
    this.controle = controle;
    this.estaValido = true;
    this.validadorInvalido = "";
    this.validadores = new Array();
    
    if (requerido == undefined){
        this.requerido = true;
    }else{
        this.requerido = requerido;
    }
}


//---------------------------------
// Validador
//---------------------------------
LocaPag.Validacao.Validador = function(configs, funcaoFoco, funcaoValido)
{
    if (configs == null || configs.length == 0){
        setErro("Array de controles não possui nenhum item.     \nParâmetro: configs");
        return;
    }
    
    if (funcaoFoco == null || typeof(funcaoFoco) != "function"){
        setErro("Objeto não é uma function válida.     \nParâmetro: funcaoFoco");
        return;
    }

    if (funcaoValido == null || typeof(funcaoValido) != "function"){
        setErro("Objeto não é uma function válida.     \nParâmetro: funcaoValido");
        return;
    }

    if (typeof(Page_Validators) == "undefined"){
        setErro("Não há validadores ASP.NET registrados na página.     ");
        return;
	}
	
	this.configs = configs;
    this.funcaoFoco = funcaoFoco;
    this.funcaoValido = funcaoValido;
    
    for (var i = 0; i < this.configs.length; i++){ //for configs
        var config = this.configs[i];

        for (var j = 0; j < Page_Validators.length; j++){
	        var validator = Page_Validators[j];

	        if (typeof(validator.enabled) == "undefined" || validator.enabled != false){
	            if (validator.controltovalidate == config.controle.id){
	                config.validadores[config.validadores.length] = validator;
	            }
	        }
        }    

        var handler = null;
  
        handler = Function.createDelegate(this, this.onFocus);
        $addHandler(config.controle, "focus", handler);        
        
        handler = Function.createDelegate(this, this.onValidate);
        $addHandler(config.controle, "blur", handler);        
        
        if (config.controle.tagName.toLowerCase() == "select"){
            //Manipula onActivate para funcionar corretamente no IE.
            handler = Function.createDelegate(this, this.onFocus);
            $addHandler(config.controle, "activate", handler);

            handler = Function.createDelegate(this, this.onValidate);
            $addHandler(config.controle, "change", handler);
        }
    } //for configs
}

LocaPag.Validacao.Validador.prototype = {
    onValidate : function(event)
    {
        var config = this.getConfig(event);
       
        if (config == null){
            setErro("Configuração não encontrada para o controle \"" + event.target.id + "\".     ");
            return;
        }
        
        config = this.validarConfig(config);
        
        this.funcaoValido(config);
    }
    
    ,    
    
    onFocus : function(event)
    {
        var config = this.getConfig(event);
       
        if (config == null){
            setErro("Configuração não encontrada para o controle \"" + event.target.id + "\".     ");
            return;
        }    
    
	    for (var i = 0; i < config.validadores.length; i++){
	        var validator = config.validadores[i];
            
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);
	    }

        this.funcaoFoco(config);
    }
    
    ,
    
    validar : function()
    {
        var estaValido = true;
        
        for (var i = 0; i < this.configs.length; i++){ //for configs
            var config = this.validarConfig(this.configs[i]);

            this.funcaoValido(config); 
            estaValido = (estaValido && config.estaValido);
        } //for configs
        
        return estaValido;
    }
    
    ,
    
    validarConfig : function(config)
    {
        var validadorInvalido = "";
        
        config.estaValido = true;

	    for (var i = 0; i < config.validadores.length; i++){ //for validadores
	        var valido = true;
	        var validator = config.validadores[i];
	        if(validator.enabled != undefined && validator.enabled.toString().toLowerCase() == "false")
	            continue;

            if (typeof(validator.evaluationfunction) == "function"){
                valido = validator.evaluationfunction(validator);
            }else if (typeof(validator.evaluationfunction) == "string") {
                eval("valido = " + validator.evaluationfunction + "(" + validator.id + ")");
            }
            
            validator.isvalid = valido;
            ValidatorUpdateDisplay(validator);
            
            if (!valido && validadorInvalido == ""){
                validadorInvalido = validator.id;
            }
            
            config.estaValido = (config.estaValido && valido);
	    } //for validadores
	    
	    config.validadorInvalido = validadorInvalido;
	    
	    return config;
    }
    
    ,
    
    getConfig : function(event)
    {
       var config = null;
        
        for (var i = 0; i < this.configs.length; i++){
//            if (this.configs[i].controle.id == event.target.id){
            if (this.configs[i].controle == event.target){
                config = this.configs[i];
                break;
            }
        }
        
        return config;
    }
}

function setErro(mensagem)
{
    alert("LocaPag.Validacao.Erro: " + mensagem);
}

LocaPag.Validacao.Config.registerClass("LocaPag.Validacao.Config", null);
LocaPag.Validacao.Validador.registerClass("LocaPag.Validacao.Validador", null);


//---------------------------------
// Validação de CPF
//---------------------------------
function validarCpf(cpf)
{  
    var numeros, digitos, soma, i, resultado, digitosIguais;

    cpf = trim(removerFormatacao(cpf));

    if (cpf.length == 0 || cpf.length > 11){
	    return false;
    }

    while (cpf.length < 11){
	    cpf = "0".concat(cpf);
    }

    digitosIguais = true;

    for (i = 0; i < cpf.length - 1; i++){
        if (cpf.charAt(i) != cpf.charAt(i + 1)){
            digitosIguais = false;
            break;
        }
    }

    if (digitosIguais){
        return false;
    }

    numeros = cpf.substring(0, 9);
    digitos = cpf.substring(9);
    soma = 0;

    for (i = 10; i > 1; i--){
        soma += numeros.charAt(10 - i) * i;
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(0)){
	    return false;
    }

    numeros = cpf.substring(0, 10);
    soma = 0;

    for (i = 11; i > 1; i--){
        soma += numeros.charAt(11 - i) * i;
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(1)){
	    return false;
    }

    return true;
}


//---------------------------------
// Validação de CNPJ
//---------------------------------
function validarCnpj(cnpj)
{
    var numeros, digitos, soma, i, resultado, pos, tamanho, digitosIguais;

    cnpj = trim(removerFormatacao(cnpj));
    
    if (cnpj.length == 0 || cnpj.length > 14){
	    return false;
    }    
    
    while (cnpj.length < 14){
	    cnpj = "0".concat(cnpj);
    }
    
    digitosIguais = true;

    for (i = 0; i < cnpj.length - 1; i++){
	    if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
		    digitosIguais = false;
		    break;  
	    }
    }

    if (digitosIguais){
	    return false;
    }

    tamanho = cnpj.length - 2;
    numeros = cnpj.substring(0, tamanho);
    digitos = cnpj.substring(tamanho);
    soma = 0;
    pos = tamanho - 7;

    for (i = tamanho; i >= 1; i--){
        soma += numeros.charAt(tamanho - i) * pos--;

        if (pos < 2){
            pos = 9;
        }
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(0)){
	    return false;
    }

    tamanho = tamanho + 1;
    numeros = cnpj.substring(0, tamanho);
    soma = 0;
    pos = tamanho - 7;

    for (i = tamanho; i >= 1; i--){
        soma += numeros.charAt(tamanho - i) * pos--;

        if (pos < 2){
            pos = 9;
        }
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(1)){
	    return false;
    }

    return true;
}

function removerFormatacao(texto)
{
	var regExp = new Array(4);
	regExp[0] = /\b,\b/g;
	regExp[1] = /\b.\b/g;
	regExp[2] = /\b\/\b/g;
	regExp[3] = /\b-\b/g;
	
	for (var i = 0; i < regExp.length; i++){
		texto = texto.replace(regExp[i], "");
	}
	
	return texto;
}

function trim(text)
{
	text = text.toString();
	
	var textSize = text.length;

	// Retira espaços do começo da string
	var begin = text.indexOf(" ");
	while (begin == 0){
		text = text.substr(begin + 1);
		begin = text.indexOf(" ");
		textSize = textSize - 1;
	}
	
	// Retira espaços do fim da string
	var end = text.lastIndexOf(" ");
	while (end == textSize - 1){
		text = text.substring(0, textSize - 1);
		end = text.lastIndexOf(" ");
		textSize = textSize - 1;
	}
	
	return text;
}
