﻿function ValidarPagina(validationGroup)
{
    for (vpi=0; vpi<Page_Validators.length; vpi++) 
    {
        if (Page_Validators[vpi].validationGroup == validationGroup) 
        {
            ValidatorValidate(Page_Validators[vpi]);
        }
    }
}

/* Painel de Avisos */
var to;
function ExibirAviso() {
    clearTimeout(to);
    $(".painel_avisos").css("display", "block");
    $(".painel_avisos").css("opacity", "1");
    to = setTimeout("OcultarAviso()", 3000);
}
function OcultarAviso() {
    $(".painel_avisos").css("display", "none");
    clearTimeout(to);
}
$(".painel_avisos").click(function() {
    OcultarAviso();
});
/* FIM: Painel de Avisos */

//Abre popup do atendimento on-line no centro da tela
function PopupAtendimentoOnline(url, win, w, h)
{
    center_x = (screen.width - w)/2;
    center_y = (screen.height - w)/2;
    
    window.open(url, win, 'width=' + w + ',height=' + h + ',top=' + center_y + ',left=' + center_x + ',scrollbars=2,location=0');
}

/**** MANIPULATE ELEMENTS FUNCTIONS ****/

function getEvent(event) {
    /// <summary>
    /// Retorna o evento disparador. X-browser compliance.
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
	var e = (!event) ? window.event : event;
	return e;
}

function getEventKey(event) {
    /// <summary>
    /// Retorna o keycode/charcode da tecla digitada no evento. X-browser compliance.
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
	var e = getEvent(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.
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
    var e = getEvent(event);
    var t = (e.target) ? e.target : e.srcElement;
	if (t.nodeType == 3) {
	    // Safari bug
		t = t.parentNode;
    }
    return t;
}

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.
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
    window.setTimeout(function () {
        if (!element.isDisabled) {  
            ValidarPagina(validationGroup);
            for (var siv=0; siv<Page_Validators.length; siv++) {
                if (typeof Page_Validators[siv].isvalid == 'boolean' && !Page_Validators[siv].isvalid) {
                    document.getElementById(Page_Validators[siv].controltovalidate).focus(); 
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }, 75); 
}


/**** MANIPULATE DOM ELEMENTS FUNCTIONS ****/

function setElementText(element, text) {
    /// <summary>
    /// atualiza o texto de um element DOM (ex: label)
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
    var olabel;
    if (typeof element == "string") { 
        olabel = $get(element);    
    } else { olabel = element; }
    // remove o texto antigo
    if (olabel) {
        if (olabel.childNodes[0]) {
            olabel.removeChild(olabel.childNodes[0]);
        }
        var newtext = document.createTextNode(text);
        olabel.appendChild(newtext);
    } 
}

function getElementText(element) {
    /// <summary>
    /// retorna o texto de um element DOM (ex: label)
    /// TODO: criar recursividade com filhos (nodetype == 1)
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
    var olabel;
    var text;
    if (typeof element == "string") { 
        olabel = $get(element);    
    } else { olabel = element; }
    if (!olabel) { 
        return;
    } else {
        for (var i = 0; i < olabel.childNodes.length; i++) {
            if (olabel.childNodes[i].nodeType == 3) {
                text = olabel.childNodes[i].nodeValue;
                break;
            }
        }
        return text;
    }
}

function setMensagemAviso(msg, type){
    /// <summary>
    /// atualiza o texto de um element DOM (ex: label)
    /// type: warning = darkblue | error = red
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </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);
            ExibirAviso();
        }
    }
}

function stringToNumber(string) {
    /// <summary>
    /// Remove letras e caracteres, remove '.', troca ',' por '.' para casas decimais.
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
    var i = 0;
    var negativo = false;
    while (string.charAt(i) == ' ') {
        i++;
    }
    if (string.charAt(i) == '-') {
        negativo = true;
    }
    var temp = string.replace(/\./g, '');
    temp = temp.replace(/,/g, '.');
    temp = temp.replace(/[^0-9.]/g, '');
    if (negativo) {
        return -(+temp);    
    } else {
        return (+temp);
    }
}

function formataMoeda(num) {
       x = 0;
       if(num<0) {
          num = Math.abs(num);
          x = 1;
       }
       if(isNaN(num)) num = "0";
            cents = Math.floor((num*100+0.5)%100);
            num = Math.floor((num*100+0.5)/100).toString();
       if(cents < 10) cents = "0" + cents;
          for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
             num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
             ret = num + ',' + cents;
       if (x == 1) ret = ' - ' + ret;return ret;
    }

function maskNumber(val, mask) {
    /// <summary>
    /// R$ ###.###.###.##0,00
    /// #-##.#-##.#-##.##000
    /// 12
    /// 12.3
    /// 12.33
    /// 12.33555678
    /// DEPRICATED -> Usuar funções do namespace de cada app.
    /// </summary>
    var prefix;
    var rad;
    var sufix;
    var negative = false;
    if (val < 0) {
        negative = true;
    }
    if (typeof val == 'number') {
        val = String(val);
        val = val.replace(/\./g, ',');
        prefix = mask.substring(0, mask.indexOf('#'));
        sufix = mask.substring(mask.lastIndexOf('#')+1, mask.length);
        mask = mask.substring(mask.indexOf('#'), mask.length);
        //mask = mask.substring(mask.indexOf('#'), mask.lastIndexOf('#')+1);
        // normaliza o value caso haja 
        if (sufix) {
            if (sufix.indexOf(',') > -1) {
                ts = sufix.split(',');
                tv = val.split(',');
                // ambos possuem decimal
                if (ts.length == tv.length) {
                    // decimal do sufixo maior q decimal do valor
                    if (tv[1].length < ts[1].length) {
                        for (var i = 0; i < ts[1].length; i++) {
                            if (tv[1].charAt(i) == '') {
                                tv[1] += ts[i].charAt(i);
                            }
                        }
                    // remove caracteres qndo o decimal do valor é maior q o decimal do sufixo
                    } else if (tv[1].length > ts[1].length) { 
                        val = val.substring(0, val.length-(tv[1].length-ts[1].length));
                    }
                // adiciona o decima do sufixo ao valor
                } else if (tv.length < ts.length) {
                    val += ","+ts[1];
                }
            }
        } 
        var im = 0;
        if (val.length - sufix.length > 0) {
            for (var j = val.length - sufix.length - 1; j > -1; j--) {
                if (val.charAt(j) != '') {
                    if (mask.charAt(mask.length - sufix.length - 1 - im) != '#') {
                        val = val.substring(0, j + 1) + mask.charAt(mask.length - sufix.length - 1 - im) + val.substring(j + 1, val.length);
                    }
                }
                im++;
            }
        }
    }
    if (typeof val == 'string') {
        if (negative) {
            return "( " + prefix + val + " )";
        } else {
            return prefix + val;
        }
    } else {
        return null;
    }
}


function pageLoad(sender, args){
    /// <summary>
    /// DOTNET infra
    /// executa apos carregar a tela (DOM READY)
    /// </summary>

    // checa versao do flash player para definicao do conteudo
    // do progress template
    if (typeof swfobject != 'undefined')
    {
        swfobject.embedSWF( "swf/progress_template.swf" , "progress_img_container", "130", "40", "5.0.0", false, false, {wmode:"transparent"});
    }
    
    // seta classe css FOCUS no event focus dos elementos
    $(":input:not(:image):not(:submit):not(:reset):not(:button)").bind("focus", function () {
        Sys.UI.DomElement.addCssClass(this, 'focus');
    });
    // remove classe css FOCUS no event blur dos elementos
    $(":input:not(:image):not(:submit):not(:reset):not(:button)").bind("blur", function () {
        Sys.UI.DomElement.removeCssClass(this, 'focus');
    });
    
    // guarda o ultimo campo que obteve foco
    $(":input:not(:hidden):not(:image):not(:submit):not(:reset):not(:button)").bind("blur", wfp.form.setLastFocus);

    // caso haja o plugin SCROLLTO do JQUERY traz campo em foco para o topo da pagina
    $(":input:not(:image):not(:submit):not(:reset):not(:button)").bind("focus", function () {
            if ($.scrollTo) { $.scrollTo(this, { offset:-150, axis:'y', easing:'linear' }); }   
    });

    // tratamento ENTER BACKSPACE
    document.onkeydown = wfp.key.disableKeys; // IE, Firefox, Safari
    document.onkeypress = wfp.key.disableKeys; // only Opera needs the backspace nullifying in onkeypress
       
    // atalhos de teclado
    $("#conteudo").bind("keydown", wfp.key.shortcuts);
    // atalhos de teclado para o campo de busca (TOPO)
    $("#ctl00_txtFiltroPesquisa_txtValor").bind("keydown", wfp.key.shortcuts);
   
    // vincula a navegação de teclado ao keydown
    $(":input:not(:image)").bind("keydown", wfp.form.nav);
    
    // remove caracteres maiores que a propriedade MaxLength ou cols * rows
    $(":input:not(:image):not(:submit):not(:reset):not(:button)").bind("paste", wfp.form.util.truncate); 
    
    // testa e chama um pageload local caso exista
    if (typeof LocalPageLoad == 'function') {
        LocalPageLoad();
    }
    
    // correção setar foco no primeiro
    if (wfp.form.util.focusid != false) {
        var e = $get(wfp.form.util.focusid);
        if (wfp.form.util.canHaveFocus(e)) {
            e.focus();
        } else {
            wfp.form.next(e);
        }
        wfp.form.util.focusid = false;
    }
}

/**** SINDEMPREGOS SINGLETON OBJ ****/

var se = {};

se.enter = {
    isExcept : function (e) {
        var is = false;
        var list = se.enter._except;
        for(var property in list) {
            if (list[property] == e.id) { return true; }
        }
        return is;
    }
};

se.enter._except = {
    // pesquisa bne
    salarioInicial : 'ctl00_conteudo_txtSalarioInicial_txtValor',  
    salarioFinal : 'ctl00_conteudo_txtSalarioFinal_txtValor', 
    experiencia : 'ctl00_conteudo_txtExperiencia_txtValor',
    idadeMinima : 'ctl00_conteudo_txtIdadeMinima_txtValor',
    idadeMaxima : 'ctl00_conteudo_txtIdadeMaxima_txtValor',
    bairro : 'ctl00_conteudo_txtBairro',
    empresa : 'ctl00_conteudo_txtEmpresa',
    ramo : 'ctl00_conteudo_txtRamo',
    nome : 'ctl00_conteudo_txtNome',
    // outras telas
    pretensaoSalarial : 'ctl00_conteudo_txtPretensaoSalarial_txtValor',
    ultimosDias : 'ctl00_conteudo_txtUltimosDias_txtValor'
};


/**** WEBFOPAG SINGLETON OBJ ****/
// var cultureObject = Sys.CultureInfo.CurrentCulture;
// Sys.CultureInfo.CurrentCulture.numberFormat.NumberNegativePattern


var wfp = {
    // {vars}
    // constants
    VERSION : function () {
        return 1.2;
    },
    // MMDDYYYY
    VERSION_DATE : function () {
        return new Date("11-7-2008");
    }
    // private vars
    // public vars
    // {methods}
    // private methods
    // public methods
};

wfp.util = {
    acf : false,
    isArray : function (e) {
        /// <summary>
        /// Verifica se o elemento é um array.
        /// </summary>
        return (typeof(e.length) == "undefined") ? false : true;
    },
    fixBugModal : function () {
        var ovf = $get('conteudo').style.overflow;
        if (!ovf || ovf == "" || ovf == "auto") {
            $get('conteudo').style.overflow = "visible";
        } else {
            $get('conteudo').style.overflow = "auto";
        }
    },
    getSelectionSize : function (e) {
        /// <summary>
        /// Retorna o tamanho da seleção do texto em um element DOM.
        /// </summary>
        if (document.selection) {
            var textRange = document.selection.createRange();
            return textRange.text.length;        
        } else if (typeof e.selectionStart == 'number') {
            return e.selectionEnd - e.selectionStart;
        }
    },
    validPwd : function (source, args) {
        /// <summary>
        /// Valida string para ter no mínimo 4 letras e 4 numeros.
        /// </summary>
        var txt = args.Value;
        var c_num = 0;
        var c_str = 0;
        for (var i = 0; i < txt.length; i++) {
            if (isNaN(+(txt.charAt(i)))) {
                if (txt.charCodeAt(i) >= 65 && txt.charCodeAt(i) <= 90) {
                    c_str++;
                } else if (txt.charCodeAt(i) >= 97 && txt.charCodeAt(i) <= 122) {
                    c_str++;
                }
            } else if (typeof +(txt.charAt(i)) == "number") {
                c_num++;
            }
        }
        if (c_num == 4 && c_str == 4) {
            args.IsValid = true;
        } else {
            args.IsValid = false;
        }        
    }
};

wfp.util.string = {
    toNumber : function (string) {
        /// <summary>
        /// Remove letras e caracteres, remove '.', troca ',' por '.' para casas decimais.
        /// </summary>
        var i = 0;
        var negativo = false;
        while (string.charAt(i) == ' ') {
            i++;
        }
        if (string.charAt(i) == '-') {
            negativo = true;
        }
        var temp = string.replace(/\./g, '');
        temp = temp.replace(/,/g, '.');
        temp = temp.replace(/[^0-9.]/g, '');
        if (negativo) {
            return -(+temp);    
        } else {
            return (+temp);
        }
    },
    trim : function (str) {
        /// <summary>
        /// Remove espaços brancos a direita e a esquerda.
        /// </summary>
       return str.replace(/^\s+|\s+$/g, '');
    },
    shortTrim : function (str) {
        /// <summary>
        /// Remove espaços brancos a direita e a esquerda usando regex, implementação otimizada
        /// para strings curtas.
        /// </summary>
       return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    },
    longTrim : function (str) {
        /// <summary>
        /// Remove espaços brancos a direita e a esquerda, usando uma implementação hibrida
        /// de regex e com procura normal.
        /// </summary>
	    var	str = str.replace(/^\s\s*/, ''),ws = /\s/,i = str.length;
	    while (ws.test(str.charAt(--i)));
	    return str.slice(0, i + 1);
    },
    replace : function (p, t) {
        /// <summary>
        /// Substitui uma lista de valores em um contexto informado.
        /// pattern (p) é uma string que será procurada no contexto. ex: "%%"
        /// contexto (t). ex: "Meu pai se chama %%."
        /// a lista de parametros ou string com parametro é dinâmica, qualquer quantidade é válida (array ou string).
        /// </summary>
        var _p; // regex
        var _pg; // regex
        var _tt = t; // temp text
        var _ocur = []; // array de inicios das patterns, ocorrência no context 
        var _val = []; // valores a serem substituidos
        if (typeof p == "string") {
            _p = new RegExp(p);
            _pg = new RegExp(p, "g");
        }
        if (t.match(_p)) {
            // parse da lista de argumentos, tranforma tudo em um array de valores (_val)
            for (var i = 2; i < arguments.length; i++) {
                if (i == 2) {
                    if (typeof arguments[2] == "string") {
                        _val.push(arguments[2]);
                    } else {
                        _val = arguments[2]; 
                    }
                } else {
                    if (typeof arguments[i] == "object" && wfp.util.isArray(arguments[i])) {   
                        for (var j = 0; j < arguments[i].length; j++) {
                            _val.push(arguments[i][j]);  
                        }
                    } else {
                        _val.push(arguments[i]);
                    }
                }
            }
            // acha tds as ocorrências
            var _tmp_s = 0;
            while (t.indexOf(p, _tmp_s) > -1) {
                _ocur.push(t.indexOf(p, _tmp_s));
                _tmp_s = t.indexOf(p, _tmp_s)+p.length;
            }
            // verifica se se as ocorrências são na mesma quantidade dos valores informados.
            if (_ocur.length != _val.length) {
                return "Lista de valores informados ("+ _val.length +") diferente da quantidade de ocorrência ("+ _ocur.length +") no contexto informado.";
            }            
            for (var k = 0; k < _val.length; k++) {
                _tt = _tt.replace(_p, _val[k]);
            }
            return _tt;
        }
    }
};

wfp.util.number = {
    mask : function (val, mask) {
        /// <summary>
        /// Insere uma mascara em um nro.
        /// 'R$ ###.###.###.##0,00'
        /// '#-###-###-##.##000'
        /// 12
        /// 12.3
        /// 12.33
        /// 12.33555678
        /// </summary>
        var prefix;
        var rad;
        var sufix;
        var negative = false;
        if (val < 0) {
            negative = true;
        }
        if (typeof val == 'number') {
            val = String(val);
            val = val.replace(/\./g, ',');
            prefix = mask.substring(0, mask.indexOf('#'));
            sufix = mask.substring(mask.lastIndexOf('#')+1, mask.length);
            mask = mask.substring(mask.indexOf('#'), mask.length);
            //mask = mask.substring(mask.indexOf('#'), mask.lastIndexOf('#')+1);
            // normaliza o value caso haja 
            if (sufix) {
                if (sufix.indexOf(',') > -1) {
                    ts = sufix.split(',');
                    tv = val.split(',');
                    // ambos possuem decimal
                    if (ts.length == tv.length) {
                        // decimal do sufixo maior q decimal do valor
                        if (tv[1].length < ts[1].length) {
                            for (var i = 0; i < ts[1].length; i++) {
                                if (tv[1].charAt(i) == '') {
                                    tv[1] += ts[i].charAt(i);
                                }
                            }
                            val = tv[0] + "," + tv[1];
                        // remove caracteres qndo o decimal do valor é maior q o decimal do sufixo
                        } else if (tv[1].length > ts[1].length) { 
                            val = val.substring(0, val.length-(tv[1].length-ts[1].length));
                        }
                    // adiciona o decima do sufixo ao valor
                    } else if (tv.length < ts.length) {
                        val += ","+ts[1];
                    }
                }
            } 
            var im = 0;
            if (val.length - sufix.length > 0) {
                for (var j = val.length - sufix.length - 1; j > -1; j--) {
                    if (val.charAt(j) != '') {
                        if (mask.charAt(mask.length - sufix.length - 1 - im) != '#') {
                            val = val.substring(0, j + 1) + mask.charAt(mask.length - sufix.length - 1 - im) + val.substring(j + 1, val.length);
                        }
                    }
                    im++;
                }
            }
            if (typeof val == 'string') {
                if (negative) {
                    return "( " + prefix + val + " )";
                } else {
                    return prefix + val;
                }
            } else {
                return null;
            }            
        } else {
            return null;
        }
    }
};

wfp.util.date = {
    isEarlier : function (arg1, arg2) {
        /// <summary>
        /// Verifica se a primeira data é anterior a segunda.
        /// </summary>
        var dt1, dt2;
        if (typeof arg1 == "string" && typeof arg2 == "string") {
            var splitter;
            for (var i = 0; i < arg1.length; i++) {
                if (arg1.charCodeAt(i) < 48 || arg1.charCodeAt(i) > 57) {
                    splitter = arg1.charAt(i);
                    break;
                }
            }
            if (splitter) {
                var t1 = arg1.split(splitter);
                dt1 = new Date(t1[2], t1[1]-1, t1[0]);
                var t2 = arg2.split(splitter);
                dt2 = new Date(t2[2], t2[1]-1, t2[0]);
            } else {
                return false;
            }
        } else {
            dt1 = arg1;
            dt2 = arg2;
        }
        
        if (dt1.getTime() < dt2.getTime()) {
            return true;
        } else {
            return false;
        }
    },
    isEqual : function (arg1, arg2) {
        /// <summary>
        /// Verifica se a primeira data é igual a segunda.
        /// </summary>
        var dt1, dt2;
        if (typeof arg1 == "string" && typeof arg2 == "string") {
            var splitter;
            for (var i = 0; i < arg1.length; i++) {
                if (arg1.charCodeAt(i) < 48 || arg1.charCodeAt(i) > 57) {
                    splitter = arg1.charAt(i);
                    break;
                }
            }
            var t1 = arg1.split(splitter);
            dt1 = new Date(t1[2], t1[1]-1, t1[0]);
            var t2 = arg2.split(splitter);
            dt2 = new Date(t2[2], t2[1]-1, t2[0]);
        } else {
            dt1 = arg1;
            dt2 = arg2;
        }
        
        if (dt1.getTime() == dt2.getTime()) {
            return true;
        } else {
            return false;
        }
    }
};

/**** EVENTS ****/

wfp.event = {
    cancel : function (evt) {
    /// <summary>
    /// Cancela o evento.
    /// </summary>
        if (window.event) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        } else {
            evt.preventDefault();
            evt.stopPropagation();
        }
        if (evt.originalEvent) {
            evt.preventDefault();
            evt.stopPropagation();
        }
    },
    getTarget : function (evt) {
    /// <summary>
    /// Retorna o elemento que iniciou o evento.
    /// </summary>
        if (window.event) {
            return window.event.srcElement;
        } else if (evt.srcElement) {
            return evt.srcElement;
        } else {
            return (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;
        }
    },
    getEvent : function (evt) {
    /// <summary>
    /// Retorna o evento disparador. X-browser compliance.
    /// </summary>
	    return (window.event) ? window.event : evt;
    },
    getKey : function (evt) {
    /// <summary>
    /// k = não faz diferença entre maiúscula e minúscula = NON CHAR.
    /// c = faz diferença entre maiúscula e minúscula (tabela ascii) = CHAR
    /// </summary>
        var k, c;
        if (window.event) {
            k = (window.event.keyCode) ? window.event.keyCode : null; // RETORNA NON CHAR
            //c = (window.event.charCode) ? window.event.charCode : null; // RETORNA CHAR
            if (window.event.type == 'keypress') {
                c = k;
                k = 0;            
            }
        } else {        
            k = (evt.keyCode) ? evt.keyCode : null; // RETORNA NON CHAR
            c = (evt.charCode) ? evt.charCode : null; // RETORNA CHAR
        }
	    return [k, c];    
    }
};

/**** FORM NAVEGATION ****/

wfp.form = {
    nav : function (evt) {
    /// <summary>
    /// Inicializa a captura das teclas de navegação do formulario.
    /// </summary>
        var k = wfp.event.getKey(evt)[0];
        var t = wfp.event.getTarget(evt);
        var ac = wfp.form.util.hasBehaviorAutoComplete(t);
        var selectok = true;
        var tag = String(t.nodeName).toLowerCase();
        var type = String(t.type).toLowerCase();                
        var id = t.id;
        var mod = wfp.key.hasModifierKeyPressed(evt); 
        if (wfp.key.isArrow(k) && k == wfp.key._arrows.UP_ARROW) {
            wfp.event.cancel(evt);
            if (t.tagName.toLowerCase() == 'select') {
                if (!wfp.form.util.isSelectedIndexAtMinMaxRange(t, 'min')) {
                    selectok = false;
                    t.selectedIndex--;
                }
            }
            // só deve mudar de campo se não estiver navegando dentro da lista de um autocomplete
            // caso select (combobox) so muda para próximo campo se estiver no indice min
            if (ac[0] && !ac[1] && selectok){
                t.blur();
                window.setTimeout(function () {
                    wfp.form.previous(t);
                }, 300);
            } else if (!ac[0] && selectok) {
                t.blur();
                window.setTimeout(function () {
                    wfp.form.previous(t);
                }, 200);
            }
        } else if (wfp.key.isArrow(k) && k == wfp.key._arrows.DOWN_ARROW) {
           wfp.event.cancel(evt);
            if (t.tagName.toLowerCase() == 'select') {
                if (!wfp.form.util.isSelectedIndexAtMinMaxRange(t, 'max')) {
                    selectok = false;
                    t.selectedIndex++;
                }
            }
           // só deve mudar de campo se não estiver navegando dentro da lista de um autocomplete
           // caso select-one (combobox) so muda para próximo campo se estiver no indice max
           // campos com autocomplete estão com um delay de meio segundo
           if (ac[0] && !ac[1] && selectok){
                t.blur();
                window.setTimeout(function () {
                    wfp.form.next(t);
                }, 300);
           } else if (!ac[0] && selectok){
                t.blur();
                window.setTimeout(function () {
                    wfp.form.next(t);
                }, 200);
            }
        } else if (k == wfp.key._commands.TAB) {
            wfp.event.cancel(evt);
            if (!evt.shiftKey && !evt.shiftLeft) {
                if (t.tagName.toLowerCase() == 'select') {
                    if (!wfp.form.util.isSelectedIndexAtMinMaxRange(t, 'max')) {
                        selectok = false;
                        t.selectedIndex++;
                    }
                }
                if (ac[0] && !ac[1] && selectok){
                    t.blur();
                    window.setTimeout(function () {
                        wfp.form.next(t);
                    }, 300);
                } else if (!ac[0] && selectok){
                    t.blur();
                    window.setTimeout(function () {
                        wfp.form.next(t);
                  }, 200);
                }
            } else if (evt.shiftKey || evt.shiftLeft) {
                if (t.tagName.toLowerCase() == 'select') {
                    if (!wfp.form.util.isSelectedIndexAtMinMaxRange(t, 'min')) {
                        selectok = false;
                        t.selectedIndex--;
                    }
                }
                if (ac[0] && !ac[1] && selectok){
                    t.blur();
                    window.setTimeout(function () {
                        wfp.form.previous(t);
                    }, 300);
                } else if (!ac[0] && selectok){
                    t.blur();
                    window.setTimeout(function () {
                        wfp.form.previous(t);
                    }, 200);
                }
            }
        }
    },
    getNavigationListFromElement : function (e) {
    /// <summary>
    /// Retorna a lista de campos do formulário ativos para navegação por teclado.
    /// </summary>
        var parent = e.parentNode;
        // navega em até o pai máximo
        while (parent != null && parent.id != "conteudo" && parent.id != "topo") {
            var pClass = parent.className;
            // verifica se é uma modal     
            if (pClass.match("painel_resultado_padrao") || pClass == "uc_cep") { 
                break;
            }
            parent = parent.parentNode;
        }
        // seta form para navegação 
        var container;
        if (parent == null) {
            container = "#conteudo";
        } else if (typeof parent.id == 'string' && parent.id) {
            container = "#"+parent.id;
        } else {
            container = "."+parent.className;
        }
        // busca todos os campos (input, textarea, select and button elements) menos (input image)
        return $(container).find(":input:visible:not(:image)");
    },
    getNavigationList : function () {
    /// <summary>
    /// Retorna a lista de campos do formulário ativos para navegação por teclado.
    /// </summary>
        // busca todos os campos (input, textarea, select and button elements) menos (input image)
        return $("#conteudo").find(":input:visible:not(:image)");
    },    
    getFirstElement : function () {
    /// <summary>
    /// Retorna o primeiro campo possivel de foco do formulário.
    /// </summary>
        var list = wfp.form.getNavigationList();
        for (var i = 0; i < list.length; i++) {
            if (wfp.form.util.canHaveFocus(list[i])) {
                return list[i];
                break;
            }
        }
    },
    getLastElement : function () {
    /// <summary>
    /// Retorna o ultimo campo possivel de foco do formulário.
    /// </summary>
        var list = wfp.form.getNavigationList();
        for (var i = list.length-1; i >= 0; i--) {
            if (wfp.form.util.canHaveFocus(list[i])) {
                return list[i];
                break;
            }
        }
    },
    getLastFocus : function () {
    /// <summary>
    /// Retorna o ultimo campo com foco guardado no campo HIDDEN do form (caso exista).
    /// </summary>
        var temp = $get('ctl00_hfUltimoFoco');
        if (temp != null) {
            if (temp.value != "") {
                var lastFocus = $get(temp.value);
                if (lastFocus != null) {
                    return lastFocus;
                }                
            }
        }
        return null;
    },
    setLastFocus : function (event) {
    /// <summary>
    /// Atualiza campo HIDDEN do form (caso exista) com o id do ultimo campo com foco.
    /// </summary>
        var t = wfp.event.getTarget(event);
        if (t != null) {
            var lastFocus = $get('ctl00_hfUltimoFoco');    
            if (lastFocus != null) {
                lastFocus.value = t.id;
            }
        }
    },
   next : function (e) {
    /// <summary>
    /// Retorna o proximo campo possivel de foco, ou ele mesmo caso não haja próximo campo ou algum validator obrigue o foco.
    /// </summary>
        if (e == $get(e.id)) {
            var eform = wfp.form.getNavigationListFromElement(e);
            var foundElement = false;
            var nextElement;
            var n;
            if (!wfp.form.util.validateFocusOnError(e)) { 
                for (var i = 0; i < eform.length; i++) {
                    if (eform[i].id == e.id) {
                        foundElement = true;
                    }
                    // prox element pos target ativo que não seja ignorado
                    if (foundElement && eform[i].id != e.id &&  wfp.form.util.canHaveFocus(eform[i])){
                        nextElement = eform[i];
                        break;
                    }
                }        
            }
            if (typeof nextElement == "object") { 
                p = nextElement;
            } else { 
                p = e;
            }
            p.focus();
            if ((p.type && p.type != 'button' && p.type != 'reset' && p.type != 'submit') && p.select) {
                p.select();
            }        
        }
    },
    previous : function (e) {
    /// <summary>
    /// Retorna o campo anterior possivel de foco, ou ele mesmo caso não haja campo anterior ou algum validator obrigue o foco.
    /// ELEMENT OBJECT
    /// </summary>
        if (e == $get(e.id)) {
            var eform = wfp.form.getNavigationListFromElement(e);
            var foundElement = false;
            var previousElement;
            var p;
            if (!wfp.form.util.validateFocusOnError(e)) { 
                for (var i = eform.length-1; i >= 0; i--) {
                    if (eform[i].id == e.id) {
                        foundElement = true;
                    }
                    // prox element pos target ativo que não seja ignorado
                    // alterado comparações para ID para evitar erros de comparação quando
                    // há postback ne tela durante
                    if (foundElement && eform[i].id != e.id && wfp.form.util.canHaveFocus(eform[i])) {  //
                        previousElement = eform[i];
                        break;
                    }
                }
            }
            if (typeof previousElement == "object") { 
                p = previousElement;
            } else { 
                p = e;
            }
            p.focus();
            if ((p.type && p.type != 'button' && p.type != 'reset' && p.type != 'submit') && p.select) {
                p.select();
            }        
         }
    }
};

wfp.form.util = {
    truncate : function (evt) {
        /// <summary>
        /// Remove caracteres maiores que o maxlength e espaços em branco.
        /// </summary>
        var fc = function () {
            var e = wfp.event.getTarget(evt);
            e.value = wfp.util.string.trim(e.value);
            var tstart = 0, tend = e.value.length;
            var maxlength = (+e.getAttribute('MaxLength'));
            if (maxlength == 0) {
                maxlength = (+e.getAttribute("rows"))*(+e.getAttribute("cols"));
            }
            if (tend > maxlength) {
                tend = maxlength;
            }
            e.value = e.value.substring(tstart, tend);
            switch (Sys.Browser.agent) {
                case Sys.Browser.InternetExplorer :
                    e.fireEvent("onChange");
                    return;
                default :
                    var newevt = document.createEvent("HTMLEvents");            
                    newevt.initEvent("change", true, true);
                    e.dispatchEvent(newevt);
                    return;
            }            
        };
        window.setTimeout(fc, 300);
    },
    disableComponent : function (c) {
        /// <summary>
        /// Desabilita campos do formulario e seus respectivos validadores.
        /// </summary>
        var e;
        var validators = [];
        if (typeof c == 'string') {
            e  = $get(c);
        } else {
            e  = c;
        }   
        if (e) {
            for (var i = 0; i < e.children.length; i++) {
                // navega nos validadores
                if (e.children[i].id.toLowerCase().indexOf("validador") > -1) {
                    for (var j = 0; j < e.children[i].children.length; j++) {
                        if (e.children[i].children[0].enabled) {
                            ValidatorEnable(e.children[i].children[0], false);
                        }
                    }
                // desabilita os campos de formulario
                } else if (wfp.form.util.isValidFormElement(e.children[i])) {
                    if (!e.children[i].disabled) {
                        e.children[i].disabled = true;
                    }
                }
            }
        }
    },
    enableComponent : function (c) {
        /// <summary>
        /// Habilita campos do formulario e seus respectivos validadores.
        /// </summary>
        var e;
        var validators = [];
        if (typeof c == 'string') {
            e  = $get(c);
        } else {
            e  = c;
        }   
        if (e) {
            for (var i = 0; i < e.children.length; i++) {
                // navega nos validadores
                if (e.children[i].id.toLowerCase().indexOf("validador") > -1) {
                    for (var j = 0; j < e.children[i].children.length; j++) {
                        if (!e.children[i].children[0].enabled) {
                            ValidatorEnable(e.children[i].children[0], true);
                        }
                    }
                // desabilita os campos de formulario
                } else if (wfp.form.util.isValidFormElement(e.children[i])) {
                    if (e.children[i].disabled) {
                        e.children[i].disabled = false;
                    }
                }
            }
        }
    },
    getValidators : function (e) {
        /// <summary>
        /// Retorna os validators do objeto, caso exista.
        /// </summary>
        if (typeof(e.Validators) != "undefined") {
            return e.Validators;
        }
    },
    isBtnPesquisa : function (e) {
        /// <summary>
        /// Verifica se o objeto é o filtro de pesquisa da página.
        /// </summary>
        var idPesquisa = 'ctl00_txtFiltroPesquisa_txtValor';
        if (typeof e == 'string') {
            if (e == idPesquisa) {
                return true;
            }
        } else {
            if (e.id == idPesquisa) {
                return true;
            }
        }
        return false;
    },
    focusid : false,
    ffe : function (e) {
        var id;
        if (typeof e == 'string') {
            if ($get(e).tagName == 'INPUT') {
                id = e;
            } else {
                id = RecuperarComponenteValor($get(e)).id;
            }
        } else if (typeof e == 'object') {
            if (e.tagName == "SPAN") {
                id = RecuperarComponenteValor(e).id;
            } else {
                id = e.id;
            }
        } else {
            id = this.getFirstElement().id;
        }
        wfp.form.util.focusid = id;
    },
    hadFocusBtnPesquisa : "",
    focusBtnPesquisa : function (evt) {
        if (this.hadFocusBtnPesquisa != "") {
            var lf = $get(this.hadFocusBtnPesquisa);
            lf.focus();
            if (lf.select) {
                lf.select();
            }
            this.hadFocusBtnPesquisa = "";
        } else {
            this.hadFocusBtnPesquisa = wfp.event.getTarget(evt).id;
            var bp = $get('ctl00_txtFiltroPesquisa_txtValor');
            bp.focus();
            if (bp.select) {
                bp.select();
            }
        }
    },
    isValidFormElement : function (e) {
        /// <summary>
        /// Valida se o objeto é um componente valido de navegação.
        /// </summary>
        if (String(e.nodeName).toLowerCase() == 'input' && String(e.type).toLowerCase() == 'text') { // caixa texto
            return true;
        } else if (String(e.nodeName).toLowerCase() == 'input' && String(e.type).toLowerCase() == 'submit') { // botoes
           return true;
        } else if (String(e.nodeName).toLowerCase() == 'textarea') { // caixa texto multi linha
           return true;
        } else if (String(e.nodeName).toLowerCase() == 'select') { // dropdown list
            return true;
        } else {
            return false;
        }
    },
    isSelectedIndexAtMinMaxRange : function (e, axis) {
    /// <summary>
    /// Verifica se o componente SELECT está com a menor opção ou maior opção selecionado
    /// axis = min / max
    /// </summary>
        var node = e.nodeName.toLowerCase();
        var type = String(e.type).toLowerCase();
        if (e && node == 'select' && type == 'select-one') {
            if (e.selectedIndex == '0' && axis.toLowerCase() == 'min') {
                return true;
            } else if (e.selectedIndex == e.length-1 && axis.toLowerCase() == 'max') {
                return true;
            } else {
                return false;
            }
        } else {
            // caso não seja um SELECT retorna TRUE
            return true;
        }
    },
    hasBehaviorAutoComplete : function (e) {
    /// <summary>
    /// Verifica se é um componente AJAX autocomplete e se está navegando nas opções.
    /// hasBehavior = se é um componente autocomplete.
    /// hasFlyout = é um componetne autocomplete e a lista de opções está sendo exibida.
    /// </summary>
        var listBehavior = Sys.UI.Behavior.getBehaviors(e);
        var hasAutoComplete = false;
        var hasFlyout = false;
        if (listBehavior.length > 0) {
            for (var i = 0; i < listBehavior.length; i++) {
                if (listBehavior[i].get_name() == "AutoCompleteBehavior") { 
                    hasAutoComplete = true;
                    if (listBehavior[i]._completionListElement.childNodes.length > 0) {
                        hasFlyout = true;
                    }
                    break;
                }
            }
        }
        return [hasAutoComplete, hasFlyout];
    },
    hasVisibleParent : function (e) {
    /// <summary>
    /// Verifica se os pais do elemento estão escondidos
    /// </summary>
        if (!e.disabled && // form element
           (e.type && (e.type != "hidden")) && // form element
           (e.style && e.style.display != "none")) { // other elements
            var eparent = e.parentNode;
            while (eparent.id != "conteudo" && eparent.id != "topo" && 
             (eparent.style && eparent.style.display != "none")) {
                eparent = eparent.parentNode;
            }
            if (eparent.style.display != "none") { return true; } 
            else { return false; }
        } else {
            return false;
        }
    },
    canHaveFocus : function (e) {
    /// <summary>
    /// Verifica se o campo é passivel de foco. Está visível, com os pais visíveis e 
    /// não está na lista de elementos ignorados e não está desabilitado.
    /// </summary>
         if (wfp.form.util.hasVisibleParent(e) && !wfp.form.util.ignoreElement(e) && !e.disabled) {
            return true;
        } else {
            return false
        }
    },
    autoCompleteClientSelected : function (source, eventArgs) {
    /// <summary>
    /// Seleciona o próximo campo possível de foco.
    /// *** Essa func é utilizada somente dentro do AjaxTookit:AutoCompleteExtender ***
    /// *** OnClientItemSelected="wfp.form.util.autoCompleteClientSelected" ***
    /// </summary>
        var t = source.get_element();
        wfp.form.next(t);
    },
    ignoreElement : function (e) {
    /// <summary>
    /// Verifica padrões de nomenclatura de elementos da navegação que deverão ser ignorados
    /// </summary>
        if (typeof e == "object" && e.id && e.id.match(".*_ign.*")) { //tela "lançamento folha lote"
            return true;
        } else if (typeof e == "string" && e.match(".*_ign.*")) {
            return true;
        } else {
            return false;
        }
    },
    validateFocusOnError : function (e) {
    /// <summary>
    /// Verifica se os validadores do componente permitem a ida para o proximo campo
    /// TRUE : campo com erro e o validador obriga o foco.
    /// FALSE : campo com erro e o validator não obriga o foco ou campo sem erro de validação.
    /// </summary>
        var validator = e.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++) {
                // valida os 3 tipos de validadores _re (req field) _rv (req validator) _cv (custom validator)
                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 true;
                    }
                } 
            } 
        } 
        return false;
    },
    searchInvalidValidator : function (e, vg) {
    /// <summary>
    /// Procura o primeiro validador inválido da página e traz o focus para o controle.
    /// </summary>
        if (!e.isDisabled) {  
            wfp.form.util.validarPagina(vg);
            for (var i = 0; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].isvalid) {
                    document.getElementById(Page_Validators[siv].controltovalidate).focus(); 
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    },
    validarPagina : function (vg) {
    /// <summary>
    /// Valida pagina.
    /// </summary>
       for (var i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i].validationGroup == vg) {
                ValidatorValidate(Page_Validators[i]);
            }
        }
    },
    getValueListaSugestao : function (tls, pos) {
    /// <summary>
    /// Retorna um elemento de uma lista de sugestao.
    /// pos: -2 (ultimo elemento da ls) -1 (primeiro elemento da ls)
    /// </summary>
        var _FIRST = -1;
        var _LAST = -2;
        var _ls = wfp.form.util.parseListaSugestaoToArray(tls);
        if (pos == _FIRST && _ls.length > 0) {
            return _ls[0];
        } else if (pos == _LAST && _ls.length > 0) {
            return _ls[_ls.length-1];
        } else if (_ls.length > 0) {
            return _ls[pos];
        } else {
            return false;
        }
    },
    setValueListaSugestao : function (tls, pos) {
    /// <summary>
    /// Seta um elemento de uma lista de sugestao .
    /// pos: -2 (ultimo elemento da ls) -1 (primeiro elemento da ls)
    /// </summary>
        var _FIRST = -1;
        var _LAST = -2;
        var val;
        var _ls = wfp.form.util.parseListaSugestaoToArray(tls);
        if (pos == _FIRST && _ls.length > 0) {
            val = _ls[0];
        } else if (pos == _LAST && _ls.length > 0) {
            val = _ls[_ls.length-1];
        } else if (_ls.length > 0) {
            val = _ls[pos];
        }
        
        var lsgt = tls.parentNode.parentNode;
        for (var i = 0; i < lsgt.children.length; i++) {
            if (lsgt.children[i].id.match("/*txtValor$")) {
                lsgt.children[i].value = val.codigo;
            } else if (lsgt.children[i].id.match("/*lblValor$")) {
                lsgt.children[i].childNodes[0].nodeValue = val.descricao;
            }
        }        
    },
    parseListaSugestaoToArray : function (table) {
    /// <summary>
    /// Retorna um elemento de uma lista de sugestao.
    /// if (i % 2 == 0) MOD
    /// </summary>
        var cells = table.cells;
        var json = "[ ";
        for (var i = 0; i < cells.length; i++) {
            if (cells[i].className) {
                var str_id = cells[i].className;
                var val_id = cells[i].firstChild.data;
                i++;
                var str_desc = cells[i].className;
                var val_desc = cells[i].firstChild.data;
                
                json += "{ "+str_id+" : "+val_id+" , "+str_desc+" : \""+val_desc+"\" }";
                
                if (i+1 != cells.length) {
                    json += ' , ';
                }
            }
        }
        json += ' ]';
        return eval(json);
    }
};


/**** KEYS ****/

// IE reflete charcode somente no keypress

// MOZILLA Firefox

// KeyEvent = http://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent
// event.keyCode = http://developer.mozilla.org/en/DOM/event.keyCode
// event.charCode = http://developer.mozilla.org/en/DOM/event.charCode

// event.charCode = Returns the Unicode value of a non-character key in a keypress event (tab esc bkspc del ins hom end F*)
// event.keyCode = Returns the Unicode value of a character key pressed during a keypress event

// KEYPRESS NÃO DEMONSTRA = capslok shift ctrl alt printscreen scrolllok numlok

wfp.key = {
    isSpecial: function(code) {
        if (wfp.key.isCommand(code)) {
            return true;
        } else if (wfp.key.isArrow(code)) {
            return true;
        } else if (wfp.key.isFunction(code)) {
            return true;
        } else {
            return false;
        }
    },
    isEnter: function(code) {
        if (code == wfp.key._commands.ENTER) {
            return true;
        } else {
            return false;
        }
    },
    isSpace: function(code) {
        if (code == wfp.key._space.SPACE) {
            return true;
        } else {
            return false;
        }
    },
    isArrow: function(code) {
        var is = false;
        var list = wfp.key._arrows;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isNumber: function(code) {
        var is = false;
        var list = wfp.key._numbers;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isUpperCaseLetter: function(code) {
        var is = false;
        var list = wfp.key._upperLetters;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isLowerCaseLetter: function(code) {
        var is = false;
        var list = wfp.key._lowerLetters;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isUpperAccentedCharacter: function(code) {
        var is = false;
        var list = wfp.key._upperAccented;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isLowerAccentedCharacter: function(code) {
        var is = false;
        var list = wfp.key._lowerAccented;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isCommand: function(code) {
        var is = false;
        var list = wfp.key._commands;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isModifier: function(code) {
        var is = false;
        var list = wfp.key._modifier;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isFunction: function(code) {
        var is = false;
        var list = wfp.key._functions;
        for (var property in list) {
            if (list[property] == code) { return true; }
        }
        return is;
    },
    isCtrlV: function(evt) {
        /// <summary>
        /// Valida se é um atalho de um PASTE CONTENT CTRL+V.
        /// </summary>        
        if (window.event) {
            if (window.event.ctrlKey) {
                return true;
            } else {
                return false;
            }
        } else {
            if (evt.ctrlKey) {
                return true;
            } else {
                return false;
            }
        }
    },
    hasModifierKeyPressed: function(e) {
        /// <summary>
        /// Verifica se alguma tecla modificadora está sendo pressionada.
        /// </summary>        
        // verifica se é um evento do jqery
        if (e.originalEvent != null) { e = e.originalEvent; }
        var modifier = null;
        if (e.altKey == true) {
            modifier = 'ALT';
        } else if (e.altLeft == true) {
            modifier = 'ALT';
        } else if (e.ctrlKey == true) {
            modifier = 'CTRL';
        } else if (e.ctrlLeft == true) {
            modifier = 'CTRL';
        } else if (e.shiftKey == true) {
            modifier = 'SHIFT';
        } else if (e.shiftLeft == true) {
            modifier = 'SHIFT';
        }
        return modifier;
    },
    shortcuts: function(evt) {
        /// <summary>
        /// Atalhos da applicação.
        /// </summary>        
        var type = evt.type;
        var k = wfp.event.getKey(evt)[0];
        var mod = wfp.key.hasModifierKeyPressed(evt);
        // IE não possui charcode e só diferencia Maisculo de Minúsculo no keypress
        if (type == 'keydown' || type == 'keyup') {
            if (k == 113) {
                // 113 = F2
                var btnF2 = $get('ctl00_btnAtalhoF2');
                if (btnF2 != null) {
                    wfp.event.cancel(evt);
                    btnF2.click();
                }
            } else if (k == 119) {
                // 119 = F8
                var btnF8 = $get('ctl00_btnAtalhoF8');
                if (btnF8 != null) {
                    wfp.event.cancel(evt);
                    btnF8.click();
                }
            } else if (k == 120) {
                // 120 = F9
                var tempF9 = $get('ctl00_btnAtalhoF9');
                if (tempF9 != null) {
                    wfp.event.cancel(evt);
                    wfp.form.util.focusBtnPesquisa(evt);
                }
            } else if (k == 123) {
                // 123 = F12
                var tempF12 = $get('ctl00_hfIDBtnF12');
                if (tempF12 != null) {
                    if (tempF12.value != '') {
                        var btnF12 = $get(tempF12.value);
                        if (btnF12 != null) {
                            wfp.event.cancel(evt);
                            btnF12.click();
                        }
                    }
                }
            }
            if (mod === 'ALT') {
                if (k == 68) {
                    // ALT + D (68)
                    var tempAltD = $get('ctl00_hfIDBtnAltD');
                    if (tempAltD != null) {
                        if (tempAltD.value != '') {
                            var btnAltD = $get(tempAltD.value);
                            if (btnAltD != null) {
                                var confirm = window.confirm("Tem certeza que deseja excluir?");
                                if (confirm) {
                                    btnAltD.click();
                                    wfp.event.cancel(evt);
                                }
                            }
                        }
                    }
                } else if (k == 83) {
                    // ALT + S (83)
                    if (wfp.form.util.searchInvalidValidator('Salvar')) {
                        var tempAltS = $get('ctl00_hfIDBtnAltS');
                        if (typeof tempAltS == 'object') {
                            if (tempAltS.value != '') {
                                var btnAltS = $get(tempAltS.value);
                                if (typeof btnAltS == 'object') {
                                    btnAltS.click();
                                    wfp.event.cancel(evt);
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    disableKeys: function(evt) {
        var k, t, ty, ro;
        if (window.event) { // eg. IE
            k = window.event.keyCode;
            t = window.event.srcElement.nodeName;
            e = window.event.srcElement;
            id = window.event.srcElement.id;
            ty = window.event.srcElement.type;
            ro = window.event.srcElement.getAttribute("readonly");
        } else if (evt.which) { // eg. Firefox
            k = evt.which;
            t = evt.target.nodeName;
            e = evt.target;
            id = evt.target.id;
            ty = evt.target.type;
            ro = evt.target.getAttribute("readonly");
        }
        if (k == 8 && (!(t == 'INPUT' && (ty == 'text' || ty == 'password')) && t !== 'TEXTAREA') || ro == true) {
            return false;
        } else if (k == 13 && (t !== 'TEXTAREA' && ty !== 'submit') && !se.enter.isExcept(e) && id != 'ctl00_txtFiltroPesquisa_txtValor') {
            return false;
        } else if (k == 13 && id == 'ctl00_txtFiltroPesquisa_txtValor') {
            $get('ctl00_btiPesquisar').click();
        }
    },
    invertToCase: function(evt) {
        /// <summary>
        /// Sobreescreve o evento KEYPRESS invertendo o charCase(upper/lower).
        /// </summary>        
        if (evt.type == 'keypress') {
            var key = wfp.event.getKey(evt)[1];
            var evtMaker = function(newKey) {
                // firefox e outros que usam o Gecko 
                if (evt.which) {
                    var newEvt = document.createEvent("KeyboardEvent");
                    newEvt.initKeyEvent(evt.type, true, true, document.defaultView,
                             evt.ctrlKey, evt.altKey, evt.shiftKey,
                             evt.metaKey, 0, newKey);
                    evt.preventDefault();
                    evt.target.dispatchEvent(newEvt);
                    // IE 
                } else {
                    evt.keyCode = newKey;
                }
            };
            if ((key >= 97 && key <= 122) || (key >= 224 && key <= 255)) {
                // converte de acordo com o valor decimal da tecla na tabela ascii    
                evtMaker(key - 32);
            } else if ((key >= 65 && key <= 90) || (key >= 192 && key <= 223)) {
                // converte de acordo com o valor decimal da tecla na tabela ascii    
                evtMaker(key + 32);
            }
        }
    }
};

wfp.key._numbers = {
    ZERO: 48,
    ONE: 49,
    TWO: 50,
    THREE: 51,
    FOUR: 52,
    FIVE: 53,
    SIX: 54,
    SEVEN: 55,
    EIGHT: 56,
    NINE: 57
};

wfp.key._upperLetters = {
    A: 65,
    B: 66,
    C: 67,
    D: 68,
    E: 69,
    F: 70,
    G: 71,
    H: 72,
    I: 73,
    J: 74,
    K: 75,
    L: 76,
    M: 77,
    N: 78,
    O: 79,
    P: 80,
    Q: 81,
    R: 82,
    S: 83,
    T: 84,
    U: 85,
    V: 86,
    W: 87,
    X: 88,
    Y: 89,
    Z: 90
};

wfp.key._lowerLetters = {
    a: 97,
    b: 98,
    c: 99,
    d: 100,
    e: 101,
    f: 102,
    g: 103,
    h: 104,
    i: 105,
    j: 106,
    k: 107,
    l: 108,
    m: 109,
    n: 110,
    o: 111,
    p: 112,
    q: 113,
    r: 114,
    s: 115,
    t: 116,
    u: 117,
    v: 118,
    w: 119,
    x: 120,
    y: 121,
    z: 122
};

wfp.key._upperAccented = {
    A_GRAVE : 192,
    A_ACUTE : 193,
    A_CIRCUMFLEX : 194,
    A_TILDE : 195, 
    A_DIAERESIS : 196,
    A_ring_above : 197,
    AE : 198,
    C_CEDILLA : 199,
    E_GRAVE : 200,
    E_ACUTE : 201,
    E_CIRCUMFLEX : 202,
    E_DIAERESIS : 203,
    I_GRAVE : 204,
    I_ACUTE : 205,
    I_ACUTE : 206,
    I_DIAERESIS : 207,
    ETH : 208,
    N_tild : 209,
    O_GRAVE : 210, 
    O_ACUTE : 211, 
    O_CIRCUMFLEX : 212, 
    O_TILDE : 213, 
    O_DIAERESIS : 214,
    multiplication : 215,
    O_STROKE : 216, 
    U_GRAVE : 217, 
    U_ACUTE : 218, 
    U_CIRCUMFLEX : 219, 
    U_DIAERESIS : 220, 
    Y_ACUTE : 221, 
    THORN : 222, 
    SHARP_s : 223
};

wfp.key._lowerAccented = {
    a_GRAVE : 192,
    a_ACUTE : 193,
    a_CIRCUMFLEX : 194,
    a_TILDE : 195, 
    a_DIAERESIS : 196,
    a_ring_above : 197,
    ae : 198,
    c_CEDILLA : 199,
    e_GRAVE : 200,
    e_ACUTE : 201,
    e_CIRCUMFLEX : 202,
    e_DIAERESIS : 203,
    i_GRAVE : 204,
    i_ACUTE : 205,
    i_CIRCIMFLEX : 206,
    i_DIAERESIS : 207,
    eth : 208,
    n_tild : 209,
    o_GRAVE : 210, 
    o_ACUTE : 211, 
    o_CIRCUMFLEX : 212, 
    o_TILDE : 213, 
    o_DIAERESIS : 214,
    multiplication : 215,
    o_STROKE : 216, 
    u_GRAVE : 217, 
    u_ACUTE : 218, 
    u_CIRCUMFLEX : 219, 
    u_DIAERESIS : 220, 
    y_ACUTE : 221, 
    thron : 222, 
    y_DIAERESIS : 223
};

wfp.key._space = {
    SPACE : 23
};

wfp.key._modifiers = {
    SHIFT: 16,
    CTRL: 17,
    ALT: 18
};

wfp.key._commands = {
    BACKSPACE: 8,
    TAB: 9,
    ENTER: 13,
    PAUSE_BREAK : 19,
    CAPS_LOCK : 20,
    ESCAPE : 27,
    PAGE_UP : 33,
    PAGE_DOWN : 34, 
    END : 35, 
    HOME : 36, 
    INSERT_KEY : 45,
    DELETE_KEY : 46,
    LEFT_WINDOW_KEY : 91, 
    RIGHT_WINDOW_KEY : 92, 
    SELECT_KEY : 93
};

wfp.key._arrows = {
    LEFT_ARROW : 37, 
    UP_ARROW : 38, 
    RIGHT_ARROW : 39, 
    DOWN_ARROW : 40
};

wfp.key._functions = {
    F1 : 112,
    F2 : 113,
    F3 : 114,
    F4 : 115,
    F5 : 116,
    F6 : 117,
    F7 : 118,
    F8 : 119,
    F9 : 120,
    F10 : 121,
    F11 : 122,
    F12 : 123
};
