﻿ //Redimensiona a div "conteudo"
function ResizeDivConteudo()
{
	//Altura da viewport sem o topo
	var alt_viewport = $(window).height() - $("#topo").height();
	
	//Define a altura do conteudo de acordo com a viewport
	$("#conteudo").css("height", alt_viewport);

}

//Define a altura da div "conteudo" quando a página é carregada ou redimensionada
window.onload = window.onresize = function()
{
	ResizeDivConteudo();
}

// chama atalhos dentro do form
function InvocarAtalhos(evento)
{
    var target = (evento.target)? evento.target : evento.srcElement;
       
    var tecla;
    if ("which" in evento) // NN4 & FF &amp; Opera    
        tecla=evento.which; 
    else if ("keyCode" in evento) // Safari & IE4+    
        tecla=evento.keyCode;
    else if ("keyCode" in window.event) // IE4+    
        tecla=window.event.keyCode; 
    else if ("which" in window.event)
        tecla=evento.which;
        
    //Inicio rotina de verificação das teclas de atalho
    switch(tecla)
    {
        //Código tecla F2
        case 113:
            var botaoAtalhoF2 = $get('ctl00_btnAtalhoF2');
            if(botaoAtalhoF2 != undefined)
                botaoAtalhoF2.click();
            return true;
        //Código tecla F8
        case 119:
            var botaoAtalhoF8 = $get('ctl00_btnAtalhoF8');
            if(botaoAtalhoF8 != undefined)
                botaoAtalhoF8.click();
            return true;
        //Código tecla F9
        case 120:
            var atalhoF9 = $get('ctl00_btnAtalhoF9');
            if (atalhoF9 && atalhoF9.value) {
                var btnF9 = $get(atalhoF9.value);
                btnF9.focus();
            }
            return true;
        //Código tecla F12
        case 123:
            var atalhoF12 = $get('ctl00_hfIDBtnF12');
            if (atalhoF12 && atalhoF12.value) {
                var btnF12 = $get(atalhoF12.value);
                btnF12.click();
            }
            return true;
        //Código tecla 'D'
        case 68:
            // somete se for em conjunto com teclas ALT direita e esqerda
            if(evento.altKey || evento.altLeft)
            {
                var btnAltD = $get('ctl00_hfIDBtnAltD').value;
                var botaoAtalhoAltD;
                if (btnAltD != "") {
                    botaoAtalhoAltD = $get(btnAltD);
                }
                if (botaoAtalhoAltD != undefined) {
                    var response = window.confirm("Tem certeza que deseja excluir?");
                    if (response) {
                        botaoAtalhoAltD.click();
                    }
                }
            }
            return true;
        //Código tecla 'S' (maiúscula)
          case 83:
            // somete se for em conjunto com teclas ALT direita e esqerda
            if (evento.altKey || evento.altLeft) 
            {
                if(searchInvalidValidator('Salvar'))
                {
                    var btnAltS = $get('ctl00_hfIDBtnAltS').value;
                    var botaoAtalhoAltS;
                    if (btnAltS != "") {
                        botaoAtalhoAltS = $get(btnAltS);
                    }
                    if (botaoAtalhoAltS != undefined) {   
                        botaoAtalhoAltS.click();
                    }
                }
                return true;
             }
            return true;
    }
}

function ValidarPagina(validationGroup)
{
    for (i=0; i<Page_Validators.length; i++) 
    {
        if (Page_Validators[i].validationGroup == validationGroup) 
        {
            ValidatorValidate(Page_Validators[i]);
        }
    }
}

function ArmazenarUltimoFoco(campo)
{
    if(campo != null)
    {
        var campoUltimoFoco = $get('ctl00_hfUltimoFoco');
        if(campoUltimoFoco != undefined)
            campoUltimoFoco.value = campo.id;
    }
}

function focusLastElement() {
    /// <summary>
    /// Seta foco no ultimo campo gravado 
    /// </summary>

    var hf = $get('ctl00_hfUltimoFoco');

    if (hf) {
        var e = $get(uf.value);
        if (e) {
            e.focus();
            e.select();
        }
    }
}

function desloca(obj) {
    /// <summary>
    /// automatiza mudança de class FOCUS para elementos TEXT
    /// registra JQUERY.SCROLLTO em elementos do #conteudo
    /// </summary>
    // FINGER : param opcional retira 10px da posição topo para acerto nova posição msg erro //, {offset: {top:-30, left:0} }
    $("#conteudo").scrollTo(obj, 250, { offset:-50, axis:'y', easing:'linear' });
}


/**** MANIPULATE ELEMENTS FUNCTIONS ****/

function isArray(anything) {
    /// <summary>
    /// Verifica se é um array JS
    /// </summary>
    return (typeof(anything.length) == "undefined") ? false : true;
}

function getEvent(event) {
    /// <summary>
    /// Retorna o evento disparador. X-browser compliance.
    /// </summary>

	var e = (!event) ? window.event : event;
	
	return e;
}

function getEventKey(event) {
    /// <summary>
    /// Retorna o keycode da tecla digitada no evento. X-browser compliance.
    /// </summary>

	var e = (!event) ? window.event : event;
	var keycode = (e.keyCode) ? e.keyCode : e.which;
	
	return keycode;
}

function getEventTarget(event) {
    /// <summary>
    /// Retorna o elemento que iniciou o evento. X-browser compliance.
    /// </summary>
    
    var e = (!event) ? window.event : event;
    var target = (e.target) ? e.target : e.srcElement;
    
	if (target.nodeType == 3) {
	    // Safari bug
		target = targ.parentNode;
    }
    
    return target;
}

function isEnabled(element) {
    /// <summary>
    /// metodo verifica se o campo é ativo
    /// 1st param : elemento DOM atual
    /// </summary>
    /// <param name="element" type="object" DomElement="true">
    /// elemento de referencia
    /// </param>
    
    if (!element.disabled && 
         element.type != "hidden" &&
         element.style.display != "none" &&
         element.type != "image") {
         
        // navega os pais para saber se ele esta dentro de um modal escondida.
        var eparent = element.parentNode;
        //eparent && eparent.id && (eparent.id != "conteudo" || eparent.id != "topo") && 
        while (eparent.style.display != "none" && (eparent.id != "conteudo" && eparent.id != "topo")) {
            eparent = eparent.parentNode;
        }

        if (eparent.style.display != "none" ) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function searchInvalidValidator(element, validationGroup) {
    /// <summary>
    /// Método que procura o primeiro validador inválido da página e set o focus para o controle validado.
    /// </summary>
    
    if (!element.isDisabled) {  
        ValidarPagina(validationGroup);
        for (i=0; i<Page_Validators.length; i++) {
            if (!Page_Validators[i].isvalid) {
                document.getElementById(Page_Validators[i].controltovalidate).focus(); 
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}


/**** MANIPULATE DOM ELEMENTS FUNCTIONS ****/

function setElementText(element, text) {
    /// <summary>
    /// atualiza o texto de um element DOM (ex: label)
    /// </summary>

    var olabel;

    if (typeof element == "string") { 
        olabel = $get(element);    
    } else { olabel = element; }
    
    if (!olabel) { alert("[ "+element+" ] NÃO ENCONTRADO!!"); }
    
    // remove o texto antigo
    if (olabel) {
        if (olabel.childNodes[0]) {
            olabel.removeChild(olabel.childNodes[0]);
        }
        var newtext = document.createTextNode(text);
        olabel.appendChild(newtext);
    } 
}

function setMensagemAviso(msg, type){
    /// <summary>
    /// atualiza o texto de um element DOM (ex: label)
    /// type: warning = darkblue | error = red
    /// </summary>

    var label = $get('ctl00_lblAviso');
    var color = 'black';
    
    if (type == 'warning') {
        color = 'darkblue';        
    } else if (type == 'error') {
        color = 'red';
    }
        
    if (label) {
        // remove outras msgs
        if (label && label.childNodes[0]) { label.removeChild(label.childNodes[0]); }
        
        if (msg.length > 0) {
            var style = label.getAttribute("style");
            if (!style) {
                label.setAttribute("style", "color: "+color);
            } else {
                style.color = color;
            }
            var newbold = document.createElement("b");
            var newtext = document.createTextNode(msg);
            
            newbold.appendChild(newtext);
            label.appendChild(newbold);
        }
    } else {
        alert("[ ctl00_lblAviso ] NÃO ENCONTRADO!!");
    }
}


/**** TEXT RELATED FUNCTIONS ****/

function isTextFullySelected(element, size) {
    /// <summary>
    /// Verifica se usuário selecionou todo elemento text ou textarea. X-browser compliance.
    /// </summary>
    
    var value = false;
    var str = "";
    
    if (document.selection) {
        //IE support
        element.focus();
        sel = document.selection.createRange();
                
        if (sel.text != "") {
            str = sel.text;
            if (str.length >= size) {
                value = true;
            }
        }
    } else if (typeof element.selectionStart == 'number') {
        //MOZILLA/NETSCAPE support
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        
        if (startPos == '0' && endPos == size) {
            value = true;
        }
    }
    return value;
}

function isTextNotSelected(element) {
    /// <summary>
    /// Verifica se usuário não selecionou parte do text ou textarea. X-browser compliance.
    /// </summary>
    
    var value = false;
    
    if (document.selection) {
        //IE support
        element.focus();
        sel = document.selection.createRange();

        if (sel.text == "") {
            value = true;
        }
    } else if (typeof element.selectionStart == 'number') {
        //MOZILLA/NETSCAPE support
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        
        if (startPos == endPos) {
            value = true;
        }
    }
    return value;
}

function getSelectionStart(element) {
    /// <summary>
    /// Retorna a posição inicial de seleção do texto em um DOM element.
    /// </summary>
   if (document.selection) {
        var textRange = document.selection.createRange();
        var isCollapsed = textRange.compareEndPoints("StartToEnd", textRange) == 0;
	    if (!isCollapsed) { textRange.collapse(true); }
        var bookmark = textRange.getBookmark();
        return bookmark.charCodeAt(2) - 2;
    } else if (typeof element.selectionStart == 'number') {
        return element.selectionStart;    
    }  
}

function getSelectionEnd(element) {
    /// <summary>
    /// Retorna a posição final de seleção do texto em um DOM element.
    /// </summary>
    if (document.selection) {
        var textRange = document.selection.createRange();
        var isCollapsed = textRange.compareEndPoints("StartToEnd", textRange) == 0;
        if (!isCollapsed) { textRange.collapse(false); }
        var bookmark = textRange.getBookmark();
        return bookmark.charCodeAt(2) - 2;
    } else if (typeof element.selectionEnd == 'number') {
        return element.selectionEnd;
    }
}

function getSelectionSize(element) {
    /// <summary>
    /// Retorna o tamanho da seleção do texto em um DOM element.
    /// </summary>
    if (document.selection) {
        var textRange = document.selection.createRange();
        return textRange.text.length;        
    } else if (typeof element.selectionStart == 'number') {
        return element.selectionEnd - element.selectionStart;
    }
}


/**** KEY RELATED FUNCTIONS ****/

function isModifierKey(key) {
    /// <summary>
    /// Verifica se é uma tecla modificadora. X-browser compliance.
    /// SHIFT CTRL ALT 16-18    
    /// </summary>

    if (key >= 16 && key <= 18) {
        return true;
    } else {
        return false;
    }
}

function hasModifierKeyPressed(event) {
    /// <summary>
    /// Verifica se existe uma tecla modificadora em conjunto com a tecla digitada. X-browser compliance.
    /// </summary>
    
    var e = (!event) ? window.event : event;
    if (e.ctrlKey || e.altKey || e.shiftKey) {
        return true;
    } else {
        return false;
    }
}

function filterKeys(event) {
    /// <summary>
    /// impede teclas especificas de serem digitadas
    /// </summary>
    
    var target = getEventTarget(event);
    var tecla = getEventKey(event);
  
    if (tecla == 9) { // TAB
        return false;
    } else if (tecla == 13) { // ENTER
        if (target.tagName == "INPUT" && target.type == "submit") {
            target.click();
        } else if (target.tagName.toLowerCase() == "textarea") {
            return true;
        } else {
            if (target.tagName == "INPUT" && target.id == "ctl00_txtFiltroPesquisa_txtValor") {
                $get("ctl00_btiPesquisar").click();
            }
        }
        return false;
    } else {
        return true;
    }
}


/**** WEBFOPAG NAVEGATION FUNCTIONS ****/

function TabEnter(evento, p, f) {
    /// <summary>
    /// captura eventos do form, está anexado ao onkeyup
    /// 1st param : event
    /// 2nd param : primeiro campo do form
    /// 3rd param : ultimo campo do form

    var target = getEventTarget(evento);
    var tecla = getEventKey(evento);
    
    var campo;
    var proximoCampo;
    var formNavegacao;
    var tabParent;
    
    var listBehavior = Sys.UI.Behavior.getBehaviors(target);
    var hasBehaviorAutoComplete = false;
    var hasBehaviorFlyout = false;
    
    // verifica se o element chamador é um AutoComplete e força tecla SETA DOWN caso ENTER
    if (listBehavior.length > 0) {
        for (var i = 0; i < listBehavior.length; i++) {
            if (listBehavior[i]._name == "AutoCompleteBehavior") { 
                hasBehaviorAutoComplete = true;
                if (listBehavior[i]._completionListElement.childNodes.length > 0) {
                    hasBehaviorFlyout = true;
                }
                break;
            }
        }
    }
        
    var campoUltimaTeclaPressionada = $get('ctl00_hfUltimaTeclaPressionada');
    if (campoUltimaTeclaPressionada != undefined) campoUltimaTeclaPressionada.value = tecla;    
    
    var tamanhoP = p.length;
    var tamanhoF = f.length;
    
    // FINGER: naveção somente a partir de campos INPUT TEXT
    if (target && (target.tagName == "INPUT" || target.tagName == "TEXTAREA")) {

        // verifica se é uma modal     
        tabParent = target.parentNode;
        
        if (tabParent != null) {
        
            while (tabParent.id != "conteudo" && tabParent.id != "topo") {
                var tabClassName = tabParent.className;
                if (tabParent.tagName == "DIV" && (tabClassName.match("(^modal_.*)+(.*_padrao$)+") || tabClassName == "uc_cep")) { break; }
                tabParent = tabParent.parentNode;
            }

            // seta form para navegação 
            var container;
            if (typeof tabParent.id == 'string' && tabParent.id) {
                container = "#"+tabParent.id;
            }

            formNavegacao = $(container).find(":input:visible");             
            
            // comportamentos específicos para teclas
            switch(tecla){
                // DOWN = 40
                case 40:
                    if (hasBehaviorFlyout == false) {        
                        focusNextValid(formNavegacao, target);
                        // prevent default event
                        if (evento.preventDefault) { evento.preventDefault();
                        } else {  evento.returnValue = false; }
                        return false;
                    } else {
                        return true;
                    }
                // UP = 38
                case 38:
                    if (hasBehaviorFlyout == false) {        
                        focusPreviousValid(formNavegacao, target);
                        // prevent default event
                        if (evento.preventDefault) { evento.preventDefault();
                        } else { evento.returnValue = false; }
                        // move previous element
                        return false;
                    } else {
                        return true;
                    }
                // ENTER = 13
                case 13:
                    //alert($get('ctl00_hfUltimoFoco').value);
                    if (hasBehaviorAutoComplete == true || se_isCamposPesquisa(target)) {
                        focusNextValid(formNavegacao, target);
                    }                       
                    if (evento.preventDefault) { evento.preventDefault();
                    } else {  evento.returnValue = false; }
                    return false;
                // TAB = 9
                case 9:
                    //alert($get('ctl00_hfUltimoFoco').value);
                    if (hasBehaviorFlyout == false) {                       
                        if (hasModifierKeyPressed(evento)) {
                            focusPreviousValid(formNavegacao, target);
                        } else {
                            focusNextValid(formNavegacao, target);
                        }
                    }
                    if (evento.preventDefault) { evento.preventDefault();
                    } else {  evento.returnValue = false; }
                    return false;
                default:
                    if (evento.preventDefault) { evento.preventDefault();
                    } else {  evento.returnValue = false; }
                    return false;
            }
        }    
    }
}

function focusNextValid(form, element) {
    /// <summary>
    /// metodo traz foco para o proximo elemento ativo do formulario
    /// 1st param : document.getElementsBy
    /// </summary>
    /// <param name="element" type="object" DomElement="true">
    /// elemento de referencia
    /// </param>

    var eform = (!form) ? document.forms[0] : form;
    var foundActElem = false;
    var foundNextActElem = false;
    var fnCountElements = 0;
    
    element.blur();
    if (checkValidatorFocusOnError(element)) { 
        for (var i = 0; i < eform.length; i++) {
            // set true caso já passou pelo elemento

            if (eform[i].type && isEnabled(eform[i])) {
                fnCountElements++;
                if (eform[i] == element) {
                    foundActElem = true;
                }
                
                // verifica se o proximo elemento está ativo e traz foco e seleciona
                if (foundActElem && !isInvalidElement(eform[i]) && eform[i] != element && eform[i].focus){                
                    if (eform[i].focus) {
                        //ArmazenarUltimoFoco(eform[i]);
                        eform[i].focus();
                        if (eform[i].select) {
                            eform[i].select();
                        }
                        foundNextActElem = true;
                        break;
                   }
                }
            }
        }        
    }
    if (!foundNextActElem) {
        element.focus();
        if (element.select) {
            element.select();
        }
    }    
}

function focusPreviousValid(form, element) {
    /// <summary>
    /// metodo traz foco para o proximo elemento ativo do formulario
    /// 1st param : document.getElementsBy
    /// </summary>
    /// <param name="element" type="object" DomElement="true">
    /// elemento de referencia
    /// </param>

    var eform = (!form) ? document.forms[0] : form;
    var foundActElem = false;
    var foundNextActElem = false;
    var fpCountElements = 0;

    element.blur();
    if (checkValidatorFocusOnError(element)) {
        for (var i = eform.length-1; i >= 0; i--) {
            if (eform[i].type && isEnabled(form[i])) {
                fpCountElements++;
                if (eform[i] == element) {
                    // set true caso já passou pelo elemento
                    foundActElem = true;
                }
                
                // verifica se o proximo elemento está ativo e traz foco e seleciona
                if (foundActElem && !isInvalidElement(eform[i]) && eform[i] != element && eform[i].focus) { 
                    if (eform[i].focus) {
                        //ArmazenarUltimoFoco(eform[i]);
                        eform[i].focus();
                        if (eform[i].select) {
                            eform[i].select();
                        }
                        foundNextActElem = true;                    
                        break;
                    }
                }
            }
        }        
    }
    if (!foundNextActElem) {
        element.focus();
        if (element.select) {
            element.select();
        }
    }    
}

function checkValidatorFocusOnError(element) {
    /// <summary>
    /// verifica se os validadores do componente permite a ida para o proximo campo
    /// retorna TRUE caso possa ir
    /// retorna FALSE caso não possa ir
    /// </summary>

    // validadores do elemento
    var validator = element.getAttribute("Validators");
    var pattern = /(\d|[a-z]|[A-Z]|[_])+(([_][r][e])|([_][c][v])|([_][r][v]))(\d|[A-Z]|[a-z])+$/; 
    
    if (typeof(validator) == 'object' && validator) {
    
        for (var i = 0; i < validator.length; i++) {
            if (pattern.exec(validator[i].id)) {
            
                var focusOnError = validator[i].getAttribute("focusOnError");
                var isValid = validator[i].getAttribute("isValid");
            
                if ((typeof(isValid) == "boolean" && isValid == false) && (typeof(focusOnError) == "string" && focusOnError === "t")) {
                    return false;
                }
            }     
        }        
    }
    return true;    
}

function isInvalidElement(element){
    /// <summary>
    /// Função para ignorar padrões de nomenclatura de elementes na navegação
    /// Pattern1:   compontentes iniciados com "*_ign*" | tela "lançamento folha lote"
    /// </summary>

    if (element.id.match(".*_ign.*")) {
        return true;
    } else {
        return false;
    }
}


/**** WORK IN PROGRESS ****/

function pageLoad(sender, args){
    /// <summary>
    /// DOTNET infra
    /// executa apos carregar a tela (DOM READY)
    /// </summary>
    
    // seta classe de foco no focus dos elementos
    $(":input").bind("focus", function (event) {
        Sys.UI.DomElement.addCssClass(this, 'focus');
    });
    // remove classe de foco no blur dos elementos
    $(":input").bind("blur", function (event) {
        Sys.UI.DomElement.removeCssClass(this, 'focus');
    });
    
    // guarda o ultimo campo que obteve foco
    $(":input").bind("focus", function () {
        ArmazenarUltimoFoco(this);
    });
}


/**** SINDEMPREGOS ****/

function se_isCamposPesquisa(target) {
    /// <summary>
    /// verifica se o target é um campo de pesquisa do sindempregados
    /// </summary>

    var is = false;
    
    if (typeof target == 'string') {
        target = $get(target);
    }

    if (target.id == 'ctl00_conteudo_txtSalarioInicial_txtValor') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtSalarioFinal_txtValor') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtExperiencia_txtValor') {
        is = true;    
    } else if (target.id == 'ctl00_conteudo_txtIdadeMinima_txtValor') {
        is = true;    
    } else if (target.id == 'ctl00_conteudo_txtIdadeMaxima_txtValor') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtBairro') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtEmpresa') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtRamo') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtNome') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtPretensaoSalarial_txtValor') {
        is = true;
    } else if (target.id == 'ctl00_conteudo_txtUltimosDias_txtValor') {
        is = true;
    }
    return is;
}


function hasBehaviorAutoComplete(element) {
    /// <summary>
    /// Verifica se é um componente AJAX autocomplete
    /// </summary>

    var listBehavior = Sys.UI.Behavior.getBehaviors(element);
    var hasAutoComplete = false;
    var hasFlyout = false;

  // verifica se o element chamador é um AutoComplete e força tecla SETA DOWN caso ENTER
    if (listBehavior.length > 0) {
        for (var i = 0; i < listBehavior.length; i++) {
            if (listBehavior[i]._name == "AutoCompleteBehavior") { 
                hasAutoComplete = true;
                if (listBehavior[i]._completionListElement.childNodes.length > 0) {
                    hasFlyout = true;
                }
                break;
            }
        }
    }
    return [hasAutoComplete, hasFlyout];
}

function getElementNavigationForm(element) {
    /// <summary>
    /// Busca o form de navegação
    /// </summary>

    var tabParent = (element.id == "conteudo" || element.id == "topo") ? element : element.parentNode;

    if (tabParent && typeof tabParent == 'object') {
        while (tabParent.id != "conteudo" && tabParent.id != "topo") {
            var tabClassName = tabParent.className;
            if (tabParent.tagName == "DIV" && (tabClassName.match("(^modal_.*)+(.*_padrao$)+") || tabClassName == "uc_cep")) { break; }
            tabParent = tabParent.parentNode;
        }
    }
    // seta form para navegação        
    return tabParent.getElementsByTagName("INPUT");    
}

function isBotaoSubmit(element) {
    /// <summary>
    /// Verifica se é um botão de submit
    /// </summary>
    
    var tagname = element.tagName.toLowerCase();
    var type = element.type.toLowerCase();
    
    return (typeof tagname != "undefined" && tagname == "input" && typeof type != "undefined" && type == "submit") ? true : false;
}

function stringToNumber(string) {
    /// <summary>
    /// Remove letras e caracteres, remove '.', troca ',' por '.' para casas decimais.
    /// </summary>
   
    var temp = string.replace(/\./g, '');
    temp = temp.replace(/,/g, '.');
    temp = temp.replace(/[^0-9.]/g, '');
    return (+temp);
}

function wfp_isFocusable(element) {
    /// <summary>
    /// verifica se é um elemento válido para foco
    /// </summary>
    var tagname = element.tagName.toLowerCase();
    var type = element.type.toLowerCase();
    if (typeof tagname != "undefined") {
         if (tagname == "textarea") { return true; } 
         else if (typeof type != "undefined" && (tagname == "input" && (type == "text" || type == "password" || type == "submit"))) { return true;}
         else { return false; }
    } else { return false; }
}

function wfp_isVisible(element) {
    /// <summary>
    /// verifica se um elemento é visivel ou se os pais são visiveis.
    /// </summary>
    var e = element;
    while (typeof e != "undefined" && e != null) {
        if (e.disabled || (typeof e.style != "undefined" && 
            (typeof e.style.display != "undefined" && e.style.display == "none") || 
            (typeof e.style.visibility != "undefined" && e.style.visibility == "hidden"))) { return false; }
        // caso alcance o container maximo de campos            
        if (e.id.toLowerCase() == "conteudo" || e.id.toLowerCase() == "topo" || e.tagName.toLowerCase() == "body") { return true; }
        e = e.parentNode;
    }
    return true;
}


document.onkeydown = disableKeys; // IE, Firefox, Safari
document.onkeypress = disableKeys; // only Opera needs the backspace nullifying in onkeypress 
function disableKeys (event) {
  var k, t, ty;
  if (window.event) {
    k = window.event.keyCode;
    t = window.event.srcElement.nodeName;
    ty = window.event.srcElement.type;
  } else if (event.which) {
    k = event.which;
    t = event.target.nodeName;
    ty = event.target.type;
  }
  if (k == 8 && (t !== 'INPUT' && t !== 'TEXTAREA')) {
    return false;
  } else if (k == 13 && (t !== 'TEXTAREA' && ty !== 'submit')) {
    return false;
  }
} 
