﻿// JScript File
function IniciaVerificacao()
{    
    setTimeout('VerificaEstado()', 1000); //javascript trabalha com milesimos
}

function VerificaEstado() {
	if (PopUpTeste!=null && PopUpTeste.closed)
    {
        document.getElementById('ctl00_ContentMasterPage_popUpFechada').value = 'true';        
    }
    else
        setTimeout('VerificaEstado()', 1000); //javascript trabalha com milesimos
}

function AdicionaTecla(textbox, botao)
{
    textbox = document.getElementById(textbox);
    
    if(textbox != null)
    {
        textbox.botao = botao;
        if(textbox.onkeydown == null)
            textbox.onkeydown = PressionadoTecla;
        else
        {
            var func = textbox.onkeydown;
            textbox.onkeydown = function(evt)
                {
                    if(!PressionadoTecla(evt))
                        return false;
                    else
                    {
                        return func(evt);
                    }
                };
            }
     }
}

function AdicionaTeclaFoco(textbox, textboxDestino)
{    
    textbox = document.getElementById(textbox);        
    
    if(textbox != null)
    {
        textbox.textboxDestino = textboxDestino;
        if(textbox.onkeydown == null)
            textbox.onkeydown = PressionadoTeclaFoco;
        else
        {
            var func = textbox.onkeydown;
            textbox.onkeydown = function(evt)
                {
                    if(!PressionadoTeclaFoco(evt))
                        return false;
                    else
                    {
                        return func(evt);
                    }
                };
            }
     }
}

/*function Confirm(evt, mensagem){

	var oEvent = (window.event) ? window.event : evt;
	if(!confirm(mensagem))
	{
		CancelEvent(oEvent);
		return false;
	}
	else
		return true;
}*/

function CancelEvent(oEvent)
{
    try
    {
        oEvent.returnValue = false;
        oEvent.cancelBubble = true;               

        if(document.all) //IE
        {            
            oEvent.keyCode = 0;
        }
        else //NS
        {            
            oEvent.preventDefault();
            oEvent.stopPropagation();            
        }
    }
    catch(ex)
    {
        alert(ex);
    }        
}

function PressionadoAtalhoTela(evt, botao, tecla, utilizaAlt)
{
    var oEvent = (window.event) ? window.event : evt;
    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode :
            oEvent.which ? oEvent.which : 
            void 0;

    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
   
    var ret = false;
    
    if(nKeyCode == tecla && bAltPressed == utilizaAlt && !bShiftPressed && !bCtrlPressed)
    {
        ret = false;
    }
    else
        ret = true;
    
    if(!ret)
    {
        CancelEvent(oEvent);
    }
    
    if(!ret)
    {
        var botao = document.getElementById(botao);
        // Link
        if(botao.tagName == "A")
            window.setTimeout(function () { window.location = botao.href }, 0);
        else
            window.setTimeout(function () { botao.click() }, 0);
    }
    return ret;
}

function PressionadoTecla(evt)
{
    var oEvent = (window.event) ? window.event : evt;
    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode :
            oEvent.which ? oEvent.which : 
            void 0;

    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
   
    var ret = false;
    
    var campo = (oEvent.srcElement)?oEvent.srcElement:oEvent.target;
    var tecla = (campo.tecla)? campo.tecla:campo.attributes["tecla"].value;
    
    if(nKeyCode == tecla && !bAltPressed && !bShiftPressed && !bCtrlPressed)
    {
        ret = false;
    }
    else
        ret = true;
    
    if(!ret)
    {
        CancelEvent(oEvent);
    }
    
    if(!ret)
    {
        var botao = document.getElementById(campo.botao);
        // Link
        if(botao.tagName == "A")
            window.setTimeout(function () { window.location = botao.href }, 0);
        else
            window.setTimeout(function () { botao.click() }, 0);
    }
    return ret;
 }
 
function PressionadoTeclaFoco(evt)
{
    var oEvent = (window.event) ? window.event : evt;
    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode :
            oEvent.which ? oEvent.which : 
            void 0;

    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
   
    var ret = false;
    
    var campo = (oEvent.srcElement)?oEvent.srcElement:oEvent.target;
    var tecla = (campo.teclaFoco)? campo.teclaFoco:campo.attributes["teclaFoco"].value;
    
    if(nKeyCode == tecla && !bAltPressed && !bShiftPressed && !bCtrlPressed)
    {
        ret = false;
    }
    else
        ret = true;
    
    if(!ret)
    {
        CancelEvent(oEvent);
    }
    
    if(!ret)
    {
        var textboxDestino = document.getElementById(campo.textboxDestino);
        // Link
        //if(botao.tagName == "A")
        //    window.setTimeout(function () { window.location = botao.href }, 0);
        //else
            window.setTimeout(function () { textboxDestino.focus() }, 0);
    }
    return ret;
 }
 
function AdicionaAtalhoTela(botao, tecla, utilizaCtrl)
{
    if(document.body.onkeydown == null)
        document.body.onkeydown = function (evt) { return PressionadoAtalhoTela(evt, botao, tecla, utilizaCtrl); };
    else
    {
        var func = document.body.onkeydown;
        document.body.onkeydown = function(evt)
            {
                if(!PressionadoAtalhoTela(evt, botao, tecla, utilizaCtrl))
                    return false;
                else
                {
                    return func(evt);
                }
            };
     }
}


function AdicionaF3(textbox, botao)
{
    textbox = document.getElementById(textbox);
    textbox.botao = botao;
    if(textbox.onkeydown == null)
        textbox.onkeydown = PressionadoF3;
    else
    {
        var func = textbox.onkeydown;
        textbox.onkeydown = function(evt)
            {
                if(!PressionadoF3(evt))
                    return false;
                else
                {
                    return func(evt);
                }
            };
     }
}

function PressionadoF3(evt)
{
    var oEvent = (window.event) ? window.event : evt;
    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode :
            oEvent.which ? oEvent.which : 
            void 0;

    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
   
    var ret = false;
    
    // F3
    if(nKeyCode == 114 && !bAltPressed && !bShiftPressed && !bCtrlPressed)
    {
        ret = false;
    }
    else
        ret = true;
    
    if(!ret)
    {
        CancelEvent(oEvent);
    }
    
    if(!ret)
    {
        var botao = document.getElementById(((oEvent.srcElement)?oEvent.srcElement:oEvent.target).botao);
        // Link
        if(botao.tagName == "A")
            window.setTimeout(function () { window.location = botao.href }, 0);
        else
            window.setTimeout(function () { botao.click() }, 0);
    }
    return ret;
 }
 
function ConfirmacaoMessageBox(url,msg)
{
	var agree=confirm(msg);
	if (agree){
            window.location = url; 
        }else{
            return false;
        }
}

function ValidateForm()
{
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }

//exemplo utilização: txtCdCondicaoAdquirenteOrigem.Attributes.Add("onkeypress", "return text_onkeypress(event)");
function text_onkeypress() 
{
	if (!(event.keyCode >= 48 && event.keyCode <= 57))
		return false;
}
 
function window_onload() {
 text1.focus();
}
 
function ValidarVazio(txt)
{
	if (document.getElementById(txt).value == ""){
	document.getElementById(txt).style.borderColor = "#FF0000";
	alert('invalido');
	return false;
	}else{
	document.getElementById(txt).style.borderColor = "";
	alert('Valido');
	}
	return true;
}

function FormClickBotao_onkeypress(txt) 
{
    if (window.event.keyCode==13) 
    {
	    __doPostBack(txt,''); //presionaron enter
        return true;
    }
}

//------------ Scripts Validação e Máscaras em expressões regulares --------- RICARDO SOUSA RODRIGUES

function Mascarar(evt, o,f)
{
    var oEvent = (window.event) ? window.event : evt;
    if(oEvent.type != "blur")
    {
        var nKeyCode =  oEvent.keyCode ? oEvent.keyCode : oEvent.which ? oEvent.which : void 0;
        
        var ret = false;
        
        if(nKeyCode >= 48 && nKeyCode <= 57)
            ret = true;
        if(nKeyCode == 8 || nKeyCode == 46 || nKeyCode == 13 || nKeyCode == 9)
            ret = true;

        if(!ret)
        {
            CancelEvent(oEvent);
        }
        else if(nKeyCode != 13 && nKeyCode != 9)
            setTimeout(function() { execmascara(o, f); }, 0);
    }
    else
    {
        execmascara(o, f);
        var valorOriginal = ((o.valorOriginal)?o.valorOriginal:o.attributes["valorOriginal"].value);
        if(o.value != valorOriginal && o.onchange)
        {
            if(navigator.appName == "Microsoft Internet Explorer")
                o.onchange();
        }
    }
}

function execmascara(v_obj, v_fun)
{
    v_obj.value=v_fun(v_obj.value);
}

//--------------------

function MascararSomenteNumero(valor)
{
    if(valor.length < 10)
	    return valor.replace(/\D/g,"");
	else
	    return valor.substring(0,9);
}



function MascararTelefone(valor)
{
        if(valor.length > 14)
        	valor = valor.substring(0,14);
    
        valor=valor.replace(/\D/g,"");
        valor=valor.replace(/^(\d\d)(\d)/g,"($1) $2");
        valor=valor.replace(/(\d{4})(\d)/,"$1-$2");
        return valor;
}

function MascararCep(valor)
{
    if(valor.length > 9)
    	valor = valor.substring(0,9);
    
        valor=valor.replace(/\D/g,"");
        valor=valor.replace(/^(\d{5})(\d)/,"$1-$2");
        return valor;
}

function isEmail(evt, obj) 
{
	var email = obj.value;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
    var oEvent = (window.event) ? window.event : evt;	
    
	if (email != null && email != "") 
	{
	    if (!filter.test(email))
	    {	        
	        obj.value= '';
		    CancelEvent(oEvent);
		    alert('E-mail incorreto!');
		    //setTimeout(function () {obj.focus()},100);
		    window.setTimeout(function () { try { document.getElementById(obj.id).focus(); } catch (ex) {} }, 100);
		    return false;
	    }
	}
	else
	    return true;
}

function isDate(obj)
	{
		var data = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
		var valor = obj.value;

		if (valor != null && valor != "") 
		{
			if (!data.test(valor))
			{
				obj.value= '';
				alert("Por favor entre com a data válida! (dd/mm/yyyy)");
				setTimeout(function () {obj.focus()},0);
				return false;
			} 
		}
		return true;
	}

	function MascararData(valor)
	{
	    if(valor.length > 10)
            valor = valor.substring(0,10);
	    
		    valor=valor.replace(/\D/g,"");
		    valor=valor.replace(/(\d{2})(\d)/,"$1/$2");
		    valor=valor.replace(/(\d{2})(\d)/,"$1/$2");
		    valor=valor.replace(/^((0[1-9]|[12]\d)\-(0[1-9]|1[0-2])|30\-(0[13-9]|1[0-2])|31\-(0[13578]|1[02]))\-\d{4}/);
		    return valor;
	}

	function isHour(obj)
	{
		var valor = obj.value;
		var valTime = new RegExp("^([0-1][0-9]|[2][0-3]):([0-5][0-9])$");

        if (valor != null && valor != "") 
		{
		    if (valor.match(valTime) == null) 
		    {
		       obj.value = '';
		       alert("Por favor entre com a hora válida! (hh:mm)");
               setTimeout(function () {obj.focus()},0);
		       return false;
		    }
    	}
    	return true;
	}


	function MascararHora(valor)
	{
	    if(valor.length > 5)
            valor = valor.substring(0,5);
            
		valor = valor.replace(/\D/g,"")
		valor = valor.replace(/[0-9]{5}/,"")
		valor = valor.replace(/(\d{2})(\d{1})/,"$1:$2")
		return valor;
	}
		
		
//------ CPF e CNPJ -------------------------------------------------------

function MascararCpf(valor)
{
    if(valor.length > 14)
        valor = valor.substring(0,14);
    	
	valor=valor.replace(/\D/g,"");
	valor=valor.replace(/(\d{3})(\d)/,"$1.$2");
	valor=valor.replace(/(\d{3})(\d)/,"$1.$2");
	valor=valor.replace(/(\d{3})(\d{1,2})$/,"$1-$2");
	return valor;
}

function MascararCnpj(valor)
{
    if(valor.length > 18)
        valor = valor.substring(0,18);
    	
	valor=valor.replace(/\D/g,"");
	valor=valor.replace(/^(\d{2})(\d)/,"$1.$2");
	valor=valor.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3");
	valor=valor.replace(/\.(\d{3})(\d)/,".$1/$2");
	valor=valor.replace(/(\d{4})(\d)/,"$1-$2");
    return valor;
}


function ValidarCnpj(obj)
{
    execmascara(obj, MascararCnpj);

    var valor = obj.value;

	if (valor != null && valor != "") 
	{
		if (isCnpj(valor))
		{
			return true;
		}
		else
		{
			obj.value = '';
			alert('Cnpj inválido!');
			setTimeout(function () {obj.focus()},0);
			return false;
		}
	}

    if(obj.value != obj.valorOriginal && obj.onchange)
        obj.onchange();

	return true;
}

function ValidarCpf(obj)
{
    execmascara(obj, MascararCpf);

	var valor = obj.value;

	if (valor != null && valor != "") 
	{		
		if (isCpf(valor))
		{
			return true;
		}
		else
		{
			obj.value = '';
			alert('Cpf inválido!');
			setTimeout(function () {obj.focus()},0);
			return false;
		}
	}

    if(obj.value != obj.valorOriginal && obj.onchange)
        obj.onchange();

	return true;
}


//------------------ Complemento de Validações CPF e CNPJ

NUM_DIGITOS_CPF  = 11;
NUM_DIGITOS_CNPJ = 14;
NUM_DGT_CNPJ_BASE = 8;


/**
 * Adiciona método lpad() à classe String.
 * Preenche a String à esquerda com o caractere fornecido,
 * até que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona método trim() à classe String.
 * Elimina brancos no início e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formatação e zeros à esquerda da string
 * de número fornecida.
 * @param String pNum
 * 	String de número fornecida para ser desformatada.
 * @return String de número desformatada.
 */
function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * à esquerda se necessário e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 * 	String fornecida para ser formatada.
 * @param boolean pUseSepar
 * 	Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida é um CNPJ.
 * 	Caso contrário, é CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


/**
 * Calcula os 2 dígitos verificadores para o número-efetivo pEfetivo de
 * CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
 * informa se o número-efetivo fornecido é CNPJ (default = false).
 * @param String pEfetivo
 * 	String do número-efetivo (SEM dígitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida é de um CNPJ.
 * 	Caso contrário, é CPF. Default = false (CPF).
 * @return String com os dois dígitos verificadores.
 */
function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida é um CPF válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpf
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF válido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != base + digitos) return false;

	/* Não serão considerados válidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (i=1; algUnico && i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


/**
 * Testa se a String pCnpj fornecida é um CNPJ válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCnpj
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ válido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; algUnico && i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	/* Não será considerado válido CNPJ com número de ORDEM igual a 0000.
	 * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
	 * e com as três primeiras posições do número BÁSICO com 000 (zeros).
	 * Esta crítica não será feita quando o no BÁSICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") return false;
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj




var modificado = false;
function AdicionaOnChange(botoes)
{
    modificado = false;
    var func = function (){ if(modificado) return confirm('Deseja sair sem salvar?'); };
    var botao = null;
    for(var i=0; i<botoes.length; i++)
    {
        botao = document.getElementById(botoes[i]);
        if(botao != null)
        {
            if(botao.onclick == null)
                botao.onclick = func;
            else
            {
                var click = botao.onclick;
                botao.onclick = function (evt)
                {
                    if(!func(evt))
                        return false;
                    else
                    {
                        return click(evt);
                    }
                }
            }
        }
    }
    
    AdicionaOnChangeControles(document);
}

function AdicionaOnChangeControles(control)
{
    if((control.tagName == "INPUT" && (control.type == "text" || control.type == "pass"))
        || control.tagName == "SELECT"
        || control.tagName == "TEXTAREA")
    {
        if(control.onchange == null)
            control.onchange = function () { modificado = true; };
        else
        {
            var change = control.onchange;
            control.onchange = function (evt)
            {
                modificado = true;
                return change(evt);
            }
        }
        
        if(control.tagName != "TEXTAREA")
        {
            if(control.onkeydown == null)
                control.onkeydown = EnterOnKeyDown;
            else
            {
                var keydown = control.onkeydown;
                control.onkeydown = function (evt)
                {
                    if(!EnterOnKeyDown(evt))
                        return false;
                    else
                        return keydown(evt);
                }
            }
        }
    }
    
    for(var i=0; i<control.childNodes.length; i++)
    {
        AdicionaOnChangeControles(control.childNodes[i]);
    }
}

function TrocaTabControles(control)
{
    if((control.tagName == "INPUT" && (control.type == "text" || control.type == "pass"))
        || control.tagName == "SELECT")
    {
        if(control.onkeydown == null)
            control.onkeydown = EnterOnKeyDown;
        else
        {
            var keydown = control.onkeydown;
            control.onkeydown = function (evt)
            {
                if(!EnterOnKeyDown(evt))
                    return false;
                else
                    return keydown(evt);
            }
        }
    }
    
    for(var i=0; i<control.childNodes.length; i++)
    {
        TrocaTabControles(control.childNodes[i]);
    }
}

function EnterOnKeyDown(evt)
{
    var oEvent = (window.event) ? window.event : evt;
    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode :
            oEvent.which ? oEvent.which : 
            void 0;

    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
   
    var ret = false;
    
    //Enter
    if(nKeyCode == 13 && !bAltPressed && !bShiftPressed && !bCtrlPressed)
    {
        ret = false;
    }
    else
        ret = true;
    
    if(!ret)
    {
        var campo = (oEvent.srcElement)?oEvent.srcElement:oEvent.target;
        var elem = document.forms[0].elements;
        for(var i=0; i<elem.length; i++)
        {
            if(campo.tabIndex <= elem[i].tabIndex && campo.sourceIndex < elem[i].sourceIndex && elem[i].tagName != "FIELDSET" && (elem[i].tagName != "INPUT" || elem[i].type != "image" || campo.sourceIndex != elem[i].sourceIndex - 1))
            {
                if(!elem[i].disabled)
                {
                    if(elem[i].tagName != "INPUT" || (elem[i].type != "text" && elem[i].type != "pass") || !elem[i].readOnly)
                    {
                        if(elem[i].tagName != "INPUT" || elem[i].type != "hidden")
                        {
                            //alert(elem[i].id);
                            try
                            {
                                elem[i].focus();
                            }
                            catch(ex)
                            {
                                //alert(ex);
                            }
                            
                            CancelEvent(oEvent);
                            return false;
                        }
                    }
                }
            }
        }
    }
    return true;
}
//------------------------------------ VALOR MONETÁRIO -------------------------------------------
   
	function FormatarValorDecimal(pValor, pCasasDecimais, pEvento)
	{
	
         String.prototype.replaceAll = function(a, b)
        {
            var s = this;
            while(s.indexOf(a) > -1) s = s.replace(a, b);
            return s;
        }
        String.prototype.trimStart = function(a)
        {
            var s = this;
            while(s.indexOf(a) == 0) s = s.replace(a, '');
            return s;
        }
	
		var valor = pValor;
		var valorDec;
		valor = valor.replaceAll('.', '');
		valor = valor.replaceAll(',', '');
		valor = valor.trimStart('0');
		if (valor.length <= pCasasDecimais)
		{
			valorDec = valor;
			valor = '0';
		}
		else
		{
			valorDec = valor.slice(valor.length - pCasasDecimais, valor.length)
			valor = valor.slice(0, valor.length - pCasasDecimais);
		}
		while(valorDec.length < pCasasDecimais) valorDec = '0' + valorDec;
		var aux = '';
		for(var i = valor.length - 1, j = 3; i > -1; i--, j--)
		{
			if(j > 0)
			{
				aux = valor.charAt(i) + aux;
			}
			else
			{
				aux = valor.charAt(i) + '.' + aux;
				j = 3;
			}
		}
		valor = aux;
		valor = valor + ',' + valorDec
		return valor;
	}
	function MascararDecimal(pEvento, pCasasDecimais, maxLength)
	{
	   if(maxLength == 0)	
	        maxLength = 9;
	
	    //var pEvento = (window.event) ? window.event : pEvento;
        var pElemento = (pEvento.srcElement)?pEvento.srcElement:pEvento.target;
        
		if(pEvento.preventDefault == null)
		{
			pEvento.preventDefault = function() { this.returnValue = false; }
			pEvento.which = pEvento.keyCode;
		}
		switch(pEvento.which)
		{
			case 9: case 13: case 27: return;
		}
		//pEvento.preventDefault();
		    
		if(pEvento.which == 8)
		{
			//pElemento.value = FormatarValorDecimal(pElemento.value.slice(0, pElemento.value.length - 1), pCasasDecimais, pEvento);
			pElemento.value = "";
			pEvento.preventDefault();
		}
		else
		if(pEvento.which > 95 && pEvento.which < 106)
		{
		    if(pElemento.value.length >= maxLength)
		        pElemento.value = pElemento.value.substring(0,pElemento.value.length -1);
		    else
		    {
			    pElemento.value = FormatarValorDecimal(pElemento.value + (pEvento.which - 96).toString(), pCasasDecimais, pEvento);
			    pElemento.value = pElemento.value.substring(0,pElemento.value.length -1);
			}
		}
		else
		if(pEvento.which > 47 && pEvento.which < 58)
		{
		    if(pElemento.value.length >= maxLength)
		        pElemento.value = pElemento.value.substring(0,pElemento.value.length -1);
		    else
		    {
			    pElemento.value = FormatarValorDecimal(pElemento.value + (pEvento.which - 48).toString(), pCasasDecimais);
			    pElemento.value = pElemento.value.substring(0,pElemento.value.length -1);
			}
		}
		else
		pEvento.preventDefault();
	}
	//marcos
   function MascaraCriacaoMascara(pEvento)
	{
	    var pEvento = (window.event) ? window.event : pEvento;
        var pElemento = (pEvento.srcElement)?pEvento.srcElement:pEvento.target;
     
       if(pEvento.keyCode == 8)
		{
			pElemento.value =  pElemento.value.substring(0,pElemento.value.length);
			return;
		}
		else 
		if(pElemento.value.length < 16)
        {
          if((pElemento.value.length == 0) && ((pEvento.keyCode == 194) || (pEvento.keyCode == 190)) ) 
            {
               CancelEvent(pEvento);
               return;
            }
            
            if((pElemento.value.length == 15) && ((pEvento.keyCode == 194) || (pEvento.keyCode == 190)) ) 
            {
               CancelEvent(pEvento);
               return;
            }
            
          if((pEvento.keyCode == 194) || (pEvento.keyCode == 190) || ((pEvento.keyCode == 105) || pEvento.keyCode == 57)) 
            { 
              if(((pEvento.keyCode == 194) || (pEvento.keyCode == 190)) && (pElemento.value.substring(pElemento.value.length -1, pElemento.value.length) == '.'))
               { 
                 pElemento.value =  pElemento.value.substring(0,pElemento.value.length -1) ;
                 return;
               }
             } 
          else 
           { 
               CancelEvent(pEvento);
               return;
	       }     
         }
         else 
          { 
            CancelEvent(pEvento);
            return;
	      }
   }
   //marcos
   function MascararValida(obj)
    {
	        if(obj.value.substring(obj.value.length -1,obj.value.length) == '.')
	          {
	            obj.value= '';
				alert("A mascara não pode terminar com ponto (.)");
				setTimeout(function () {obj.focus()},0);
				return false;
	          }  
    }
    
    function ForcaChange(obj)
    {
        var valorOriginal = ((obj.valorOriginal)?obj.valorOriginal:obj.attributes["valorOriginal"].value);
        if(obj.value != valorOriginal && obj.onchange)
        {
            if(obj.value == "")
                obj.onchange();
        }
    }
