﻿// ATENÇÃO!
// Em caso de Atualização/Modificação:
// Utilizar http://jscompress.com/ com o método 'Packer' para comprimir e atualizar o arquivo geral-pkd.js!


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").animate({height: "40px", opacity: 1}, 1000);
//    to = setTimeout("OcultarAviso()",30000);
//}
//function OcultarAviso() {
//    //NÃO UTILIZAR, POIS NO CASO DE 2 MSG CONSECUTIVAS NÃO EXIBE (JUCA)
//    //$(".painel_avisos").animate({ opacity: 0 }, 500);
//    //to = setTimeout($(".painel_avisos").css("display", "none"), 500);
//    $(".painel_avisos").css("display", "none");
//    clearTimeout(to);
//}
//$(".painel_avisos").click(function() {
//    OcultarAviso();
//});
///* FIM: Painel de Avisos */

/* Painel de Avisos */
var to;
function ExibirAviso() {
    clearTimeout(to);
    $(".painel_avisos").css("display", "block");
    $(".painel_avisos").css("opacity", "1");
    //$(".painel_avisos").animate({ opacity: 1 }, 1);
    to = setTimeout("OcultarAviso()", 30000);
}
function OcultarAviso() {
    //NÃO UTILIZAR, POIS NO CASO DE 2 MSG CONSECUTIVAS NÃO EXIBE (JUCA)
    //$(".painel_avisos").animate({ opacity: 0 }, 500);
    //to = setTimeout($(".painel_avisos").css("display", "none"), 500);
    $(".painel_avisos").css("display", "none");
    clearTimeout(to);
}
$(".painel_avisos").click(function() {
    OcultarAviso();
}); 
/* FIM: Painel de Avisos */

/**** 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"});
        swfobject.embedSWF("swf/ico_avisos.swf", "icoavisos_img_container", "44", "44", "7.0.0", false, false, { wmode: "transparent" });
        swfobject.embedSWF("swf/progress_template.swf", "progress_img_container", "214", "40", "7.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", employer.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 = employer.key.disableKeys; // IE, Firefox, Safari
    document.onkeypress = employer.key.disableKeys; // only Opera needs the backspace nullifying in onkeypress
    //document.onkeypress = employer.key.disableCapsLock; 
    
    // atalhos de teclado
    $("#conteudo").bind("keydown", employer.key.shortcuts);
    // atalhos de teclado para o campo de busca (TOPO)
    $("#ctl00_txtFiltroPesquisa_txtValor").bind("keydown", employer.key.shortcuts);
    $("#ctl00_cphConteudo_txtFiltroPesquisa_txtValor").bind("keydown", employer.key.shortcuts);

    
   
    // vincula a navegação de teclado ao keydown
    $(":input:not(:image)").bind("keydown", employer.form.nav);
    
    // remove caracteres maiores que a propriedade MaxLength ou cols * rows
    $(":input:not(:image):not(:submit):not(:reset):not(:button)").bind("paste", employer.form.util.truncate); 
    
    // testa e chama um pageload local caso exista
    if (typeof LocalPageLoad == 'function') {
        LocalPageLoad();
    }
    
    // correção setar foco no primeiro
    /* Testes
    var firstElement = employer.form.getFirstElement();
    if (firstElement != undefined) {
        if (employer.form.util.canHaveFocus(firstElement))
            employer.controles.setFocus(employer.form.getFirstElement().id);
        else
            employer.form.next(firstElement);
    }
    */
    if (employer.form.util.focusid != false) {
        var e = $get(employer.form.util.focusid);
        if (employer.form.util.canHaveFocus(e)) {
            e.focus();
        } else {
            employer.form.next(e);
        }
        employer.form.util.focusid = false;
    }
}

/**** SINDEMPREGOS SINGLETON OBJ ****/
/***Comentado: Código não usado***/
//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'
//};