/** 
 * Retorna o número de casas válidas antes da vírgula.
 */
function CN_getFormatoInt(formato) {
    formatoInt = formato.replace("," , ".").replace("$","");
    nPosPonto = formatoInt.indexOf(".");
    if (nPosPonto < 0) {
        return Math.abs(new Number(formatoInt));
    } else {
        return Math.abs(new Number(formatoInt.substr(0, nPosPonto)));
    }
}

/** 
 * Retorna o número de casas válidas depois da vírgula.
 */
function CN_getFormatoDec(formato) {
    formatoDec = formato.replace("," , ".");
    nPosPonto = formatoDec.indexOf(".");
    if (nPosPonto < 0) {
        return 0;
    } else {
        return Math.abs(new Number(formatoDec.substr(nPosPonto+1)));
    }
}
    
/** 
 * Retorna o valor máximo que pode ser digitado.
 */
function CN_getValorMaximoPermitido(max) {
    max = new Number(max);
    if (isNaN(max)) {
        max = 0;
    }
    return max;
}
    
/** 
 * Retorna uma flag que indica se pode aceitar valores negativos.
 */
function CN_getPermiteNegativo(formato) {
    return (formato.indexOf("-") == 0);
}

/** 
 * Retorna uma flag que indica se o formato é de moeda.
 */
function CN_getFormatarComoMoeda(formato) {
    posDolar = formato.indexOf("$");
    return (posDolar == 0 || posDolar == 1);
}

/** 
 * Retorna o texto do campo sem formato.
 */
function CN_getValorDesformatado(texto) {
    return texto.replace(/\./g,"");
}

/** 
 * Retorna o texto do campo formatado.
 */
function CN_getValorFormatado(formato, texto) {
    //Pega o texto sem formatação
    texto = CN_getValorDesformatado(texto);
    if (texto == "" || texto == ",") {
        return "";
    }
    //Pega o formato do campo
    nuDec = CN_getFormatoDec(formato);
    //Formata como moeda
    if (CN_getFormatarComoMoeda(formato)) {
        if (texto.indexOf(",") >= 0) {
            posVirg = texto.indexOf(",");
            nuAntesVirg = texto.substr(0, posVirg);
            nuTamTextoAntesVirg = String(nuAntesVirg).length;
            nuDepoisVirg = texto.substr(posVirg);
        } else {
            nuAntesVirg = texto;
            nuTamTextoAntesVirg = String(nuAntesVirg).length;
            nuDepoisVirg = "";
        }
        textoComPonto = "";
        for (nPosTextoPonto=nuTamTextoAntesVirg-1; nPosTextoPonto >=0 ; nPosTextoPonto--) {
            textoComPonto = nuAntesVirg.charAt(nPosTextoPonto) + textoComPonto;
            posPonto = nuTamTextoAntesVirg-nPosTextoPonto; 
            if ((posPonto < nuTamTextoAntesVirg) && (posPonto % 3 == 0)) {
                textoComPonto = "." + textoComPonto;
            }
        }
        textoComPonto = textoComPonto.replace("-.","-");
        texto = textoComPonto + nuDepoisVirg;
    }
    //Completa as virgulas       
    if (nuDec > 0) {
        posVirg = texto.indexOf(",");
        if (posVirg < 0) {
            texto = texto + ",";
            nuCasasComp = nuDec;
        } else {
            nuCasasComp = nuDec - String(texto.substr(posVirg+1)).length;
        }
        for (nCasa=0;nCasa < nuCasasComp;nCasa++) {
            texto = texto + "0";
        }
    }
    return texto;
}
    
/** 
 * Retorna uma mensagem de erro caso o formato do campo não for válido.
 */
function CN_isFormatoValido(formato, max, allowZero, textoDigitado) {
    //Pega o texto sem formatação
    textoDigitado = CN_getValorDesformatado(textoDigitado);
    if (textoDigitado == "") {
        return "";
    }
    //tira o sinal de negativo para verificar os tamanhos
    if (textoDigitado.indexOf("-") == 0) {
        textoDigitado = textoDigitado.substr(1);
    }
    // se for só vírgula considera como número válido
    if(textoDigitado == ","){
        textoDigitado = "0" + textoDigitado;
    }
    
    //Verifica se é um número válido
    valor = Number(textoDigitado.replace(",","."));
    if (isNaN(valor)) {
        return "O valor digitado não é um número válido.";
    }        
    //Pega o formato do campo
    nuInt = CN_getFormatoInt(formato);
    nuDec = CN_getFormatoDec(formato);

    //pega a posição da virgura e o tamanho do texto
    posVirg = textoDigitado.indexOf(",") + 1;
    tamTexto = String(textoDigitado).length;
    if ((nuDec == 0) && (posVirg > 0)) {
        return "O número não pode conter casas decimais";
    }
    //valida as casas decimais
    if ((nuDec > 0) && (posVirg > 0) && ((tamTexto - posVirg) > nuDec)) {
        return "O número de casas decimais é invalido. O número pode conter apenas " + nuDec + 
          " casas decimais.";            
    }
    //valida a parte inteira
    if ((nuInt > 0) && ( ((posVirg <= 0) && (tamTexto >  nuInt)) || ((posVirg > 0) && (posVirg-1 > nuInt)) )) {
        return "O número de digitos inteiros é inválido. O número pode conter apenas " + nuInt + 
          " digitos inteiros.";            
    }
    //Pega o valor máximo
    valorMaximoPermitido = CN_getValorMaximoPermitido(max);
    //Verifica se o valor do campo não é maior que o máximo permitido
    if ((valorMaximoPermitido > 0) && (valor > valorMaximoPermitido)) {
        return "O n?mero digitado n?o pode ser maior que \"" + valorMaximoPermitido + "\".";
    }
    //Verifica se pode valor = 0
    if (allowZero != null && allowZero.toUpperCase() == "False".toUpperCase() && valor == 0) {
        return "O n?mero digitado deve ser diferente de zero.";
    }
    return "";
}

function CN_verificaValor(ctrl) {
    //verifica se o texto ? v?lido
    formato = ctrl.getAttribute("formato");
    max = ctrl.getAttribute("max");
    allowZero = ctrl.getAttribute("allowZero");
    msgformato = CN_isFormatoValido(formato, max, allowZero, ctrl.value);
    valordigitado = ctrl.value;
    //se n?o for v?lido, limpa o campo e mostra uma mensagem
    if (msgformato != "") {
        //alert (msgformato + msgKey("label.js.valorDigitado", "") + valordigitado + "\".");
        //ctrl.focus();
        if(ctrl.className.indexOf('erro')==-1){
        	ctrl.className=ctrl.className+' erro';
        }
        return false;
    } else {
    //Sen?o, formata o campo
        ctrl.value = CN_getValorFormatado(formato, ctrl.value);
        if(ctrl.className.indexOf('erro')!=-1){
      		ctrl.className=ctrl.className.substring(0,ctrl.className.indexOf('erro'));
    	}
    }
    return true;
}
    
/** Tratamento de digita??o no componente **/
function CN_KPS(ctrl, event) {
    //Nas situações abaixo não deve fazer validação não faz nada
    if (C_NaoPodeProcessarOnKeyPress(ctrl, event)) {
        return;
    }
    //inicializa as vari?veis de controle
    tecla = C_TeclaDigitada(event);
    formato = ctrl.getAttribute("formato");
    permiteNegativo = CN_getPermiteNegativo(formato);
    max = ctrl.getAttribute("max");
    //aceita numeros e virgula
    if (!((tecla >= 48 && tecla <= 57) || tecla == 44 || tecla == 45)) {       
        C_CancelaEvento(event);
        return;            
    }
    var virgulaInSel = false;
    if (F_isIExplorer()) {
        range = document.selection.createRange();
        virgulaInSel = range.text.indexOf(",") >= 0;
    } else {
        if(ctrl.selectionEnd > ctrl.selectionStart){ 
		    var pos = ctrl.selectionStart;
		    var len = ctrl.selectionEnd - ctrl.selectionStart;
		    var sel = new String(ctrl.value).substr(pos, len);
		    virgulaInSel = sel.indexOf(",") >= 0;
		}
	}
    
    
    //se permitido, deixa teclar somente uma virgula
    if ((tecla == 44) && (ctrl.value.indexOf(",") >= 0) && !virgulaInSel) {
        C_CancelaEvento(event);
        return;            
    }
    //se permitido, deixa teclar somente um sinal de negativo
    if ( (tecla == 45) && ((ctrl.value.indexOf("-") >= 0) || !(permiteNegativo)) ) {
        C_CancelaEvento(event);
        return;            
    }
    //pega o texto que está sendo digitado
    textoDigitado = C_getTextoDigitado(ctrl, String.fromCharCode(tecla));
    //sinal de negativo só no começo
    if ((tecla == 45) && (textoDigitado.indexOf("-") > 0)) {
        C_CancelaEvento(event);
        return;            
    }
    //Passa "true" para o allowZero para que seja possível digitar "0.XXX"
    msgformato = CN_isFormatoValido(formato, max, "true", textoDigitado);
    if (msgformato != "") {
        C_CancelaEvento(event);
        return;            
    }
}

/** Trata a saída do campo para não permitir que o campo fique com valores inv?lidos **/
function CN_BLR(ctrl) {
	if(ctrl.selectionEnd != ctrl.selectionStart){
		ctrl.selectionStart = ctrl.selectionEnd;
	}
    //verifica se o texto existente no campo é válido
    CN_verificaValor(ctrl);
}

function CN_MOV(ctrl, e){
	if(ctrl.className.indexOf('erro')!= -1){
		C_mostraHint(e, msgKey('label.js.valorInvalido',ctrl.value));
	}
}

function CN_MMOV(ctrl, event){
	if(ctrl.className.indexOf('erro')!= -1){
		C_moveHint(event);
	}
}

function CN_MOUT(ctrl, event){
	if(ctrl.className.indexOf('erro')!= -1){
		C_escondeHint();
	}
}

function CN_OFC(ctrl, event){
	C_OFC(ctrl, event);
	ctrl.select();
}