/*	JavaScript Document
Autor: Marcos J. Silva
Documento: scripts disponibilizados para toda a aplicaï¿½ï¿½o.	
*/

function Dia(Data_DDMMYYYY) {
    var string_data = Data_DDMMYYYY.toString();
    var posicao_barra = string_data.indexOf("/");
    var dia=0;
    if (posicao_barra!= -1){
        dia = string_data.substring(0,posicao_barra);
        return dia;
    } else {
        return false;
    }
}

function Mes(Data_DDMMYYYY) {
    var string_data = Data_DDMMYYYY.toString();
    var posicao_barra = string_data.indexOf("/");
    var dia=0;
    var string_mes=0;
    var mes=0;
    if (posicao_barra!= -1) {
        dia = string_data.substring(0,posicao_barra);
        string_mes = string_data.substring(posicao_barra+1,string_data.length);
        posicao_barra = string_mes.indexOf("/");
        if (posicao_barra!= -1){
            mes = string_mes.substring(0,posicao_barra);
            mes = Math.floor(mes);
            return mes;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function Ano(Data_DDMMYYYY) {
    var string_data = Data_DDMMYYYY.toString();
    var posicao_barra = string_data.indexOf("/");
    var string_mes=0;
    var mes=0;
    var dia=0;
    var ano=0;
    if (posicao_barra!= -1){
        dia = string_data.substring(0,posicao_barra);
        string_mes = string_data.substring(posicao_barra+1,string_data.length);
        posicao_barra = string_mes.indexOf("/");
        if (posicao_barra!= -1)
        {
            mes = string_mes.substring(0,posicao_barra);
            mes = Math.floor(mes);
            ano = string_mes.substring(posicao_barra+1,string_mes.length);
            return ano;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function diferencaDias(data1_DDMMYYYY,data2_DDMMYYYY){
    var Var_Dia1=Dia(data1_DDMMYYYY);
    var Var_Mes1=Mes(data1_DDMMYYYY);
    Var_Mes1=Math.floor(Var_Mes1)-1;
    var Var_Ano1=Ano(data1_DDMMYYYY);
    var data1 = new Date(Var_Ano1,Var_Mes1,Var_Dia1);

    var Var_Dia2=Dia(data2_DDMMYYYY);
    var Var_Mes2=Mes(data2_DDMMYYYY);
    Var_Mes2=Math.floor(Var_Mes2)-1;
    var Var_Ano2=Ano(data2_DDMMYYYY);
    var data2 = new Date(Var_Ano2,Var_Mes2,Var_Dia2);

    var diferenca = data1.getTime() - data2.getTime();
    diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));
    //alert('Diferença em dias entre '+data1_DDMMYYYY+' e '+data2_DDMMYYYY+' = '+diferenca);
    return diferenca;
}

function formatarData_viaMilisegundos(data_DDMMYYYY){    
    var data = new Date();
    data.setTime(data_DDMMYYYY);    
    return data.getDate() + "/" + (data.getMonth()+1) + "/" + data.getFullYear();
}

function dataAtual(){
    var data = new Date();	
    var dataAgora = data.getDate() + "/" + (data.getMonth()+1) + "/" + data.getFullYear();    
    return dataAgora;
}

function horaAtual(){
    var momentoAtual = new Date();	
    var hora = momentoAtual.getHours();
    var minuto = momentoAtual.getMinutes();
    var segundo = momentoAtual.getSeconds()
    var horaAgora = hora + ":" + minuto + ":" + segundo;
    return horaAgora;
}

function formataHora(tempo){
    var momento = new Date(tempo);	
    var hora = momento.getHours();
    var minuto = momento.getMinutes();
    var segundo = momento.getSeconds();
    var horaAgora = hora + ":" + minuto + ":" + segundo;    
    return horaAgora;
}

function formataHoraSemHora(tempo){ //sem HORA???? TEM QUE ARRUMAR DEPOIS. É para a subtração de hora na fila do chat
    var momento = new Date(tempo);	
    //var teste = new Date(momento);    
    //var hora = momento.getHours();
    var minuto = momento.getMinutes();
    var segundo = momento.getSeconds();
    //var horaAgora = hora + ":" + minuto + ":" + segundo;
    var horaAgora = minuto + " min. e " + segundo + " segundos";
    return horaAgora;
}

function ajaxConteudo(url, log) {
    
    new Ajax(url, {
        method: 'get',
        evalScripts: 'True',
        // evalResponse: 'True',
        update: log,
        onComplete: function() {
            log.removeClass('ajax-loading');
        }
    }).request();		
    
}

function novaTela(){
    
    var tam = screen.availWidth - 10;
    var larg = screen.availHeight - 10;
    var windowProperties="width=" + tam + ",height=" + larg + ", top=0, left=0, toolbar=no, menubar=no, status=no";
    var url='principalAtendimento.jsp';
    //var url='containerPrincipal.jsp';
    window.open(url,"addRecipientsWindow",windowProperties);
    
}

function limparCombo(combo){
    for (var i = combo.options.length - 1; i >= 0; i--){
        combo.options[i] = null;
    }
    combo.selectedIndex = -1;
}

//Removendo as linhas da tabela
function limparTabela(tabela){
    // Total linhas de tabela
    var totLinhas = tabela.rows.length;
    
    // a variável (i) deve começar a partir de (1),    se começar de (0) o cabeçalho é removido
    for(var i=0;i<totLinhas;i++){
        
        // Remove linha
        tabela.deleteRow(0);
    }    
} 

function digitarHora(c, e) { 
    var data = c.value;
    var tam = data.length;
    if (!isTeclaEspecial(e) ){
        if (tam > 4){
            e.stop();
        }
        if (inStr("1234567890:", e.key, 0) == -1){
            e.stop();
        }
        data = cleanStr(data,"0123456789");
        tam = data.length;
        if (tam > 1) {
            if (e.key != ":") data = data.substr(0,2) + ":" + data.substr(2, tam);
        }  
        c.value = data;
    }
}

function digitarNumero(c, e) { 
    var data = c.value;
    if (!isTeclaEspecial(e) ){
        if (inStr("1234567890", e.key, 0) == -1){
            e.stop();
        }
        c.value = data;      
    }
}

function digitarData(c, e) { 
    var data = c.value;
    var tam = data.length;
    if (!isTeclaEspecial(e) ){
        if (tam > 9){
            e.stop();
        }
        if (inStr("1234567890/", e.key, 0) == -1){
            e.stop();
        }
        data = cleanStr(data,"0123456789");
        tam = data.length;
        if (tam > 1) {
            if (e.key != "/") data = data.substr(0,2) + "/" + data.substr(2, tam);
        }    
        if (tam > 3) {
            if (e.key != "/") data = data.substr(0,5) + "/" + data.substr(5, tam);
        }     
        c.value = data;      
    }
}

function validarTamanhoCampo(c, e, tamMax){
    var campo = c.value;
    var tamReal = campo.length;
    if (tamReal > tamMax) {
        if (e.key == "backspace" || e.key == "delete" || e.key == "left" || e.key == "right" || e.key == "tab" || e.key == "home" || e.key == "end"){          
            c.value = campo;
        } else {
            e.stop();
            alert('Você atingiu o tamanho máximo de caracteres para este campo (' + tamMax + ').');
        }                
    }    
    
}

function validarTamanhoCampoNoIframe(c, e, tamMax){
    var campo = c.contentWindow.document.body.innerHTML;
    var tamReal = campo.length;
    if (tamReal > tamMax) {
        if (e.key == "backspace" || e.key == "delete" || e.key == "left" || e.key == "right" || e.key == "tab" || e.key == "home" || e.key == "end"){          
            c.value = campo;
        } else {
            e.stop();
            alert('Você atingiu o tamanho máximo de caracteres para este campo (' + tamMax + ').');
        }                
    }    
    
}
    
// Verifica se qtd de caracteres em determinado campo é menor ou igual ao informado
// no parametro tamMax da função.
function qtdCaracteresCorreta(c, tamMax){
    var campo = c.value;
    var tamReal = campo.length;
    if (tamReal <= tamMax) {
        return true;
    } else {
        return false;
    }
    
}


function qtdCaracteresCorretaNoIframe(c, tamMax){
    var campo = c.contentWindow.document.body.innerHTML;
    var tamReal = campo.length;
    if (tamReal <= tamMax) {
        return true;
    } else {
        return false;
    }//    
}

// valida a data no formato dd/mm/aaaa. Se estiver correta, retorna true.
// Se estiver incorreta, retorna false. Se estiver vazio, retorna false, 
// pois considera como fora do formato dd/mm/aaaa.
function validarData(c){
    if (c.value != ""){
        
        var dia = (c.value.substring(0,2)); 
        var mes = (c.value.substring(3,5)); 
        var ano = (c.value.substring(6,10)); 
        
        var situacao = ""; 
        // verifica o dia valido para cada mes 
        if (dia < 1 || dia > 31){
            //situacao = "falsa"; 
            return false;
        }
        
        if (dia > 30 && ( mes == 4 || mes == 6 || mes == 9 || mes == 11 )){
            //situacao = "falsa"; 
            return false;
        } 
        
        // verifica se o mes e valido 
        if (mes < 1 || mes > 12 ) { 
            //situacao = "falsa"; 
            return false;
        }
        
        // verifica se e ano bissexto 
        if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
            //situacao = "falsa"; 
            return false;
        } 
        
        // verifica se ano possui 4 digitos.
        if ( (ano.length = 4) && (ano > 1900) ){
            situacao = "verdadeira";
        } else {
            //situacao = "falsa"; 
            return false;
        }
        
        if (c.value == "") { 
            //situacao = "falsa"; 
            return false;
        }
        
        if (situacao == "falsa") { 
            return false;            
        } else {
            return true;
        }
    } else {
        return false;
    }
}
//
// valida a hora no formato hh/mm. Se estiver correta, retorna true.
// Se estiver incorreta, retorna false. Se estiver vazio, retorna false,
// pois considera como fora do formato hh:mm.
function validarHora(c){
    if (c.value != ""){
        var hora = (c.value.substring(0,2));
        var minuto = (c.value.substring(3,5));
        if (eval(hora) > 23){
            return false
        }
        if (eval(minuto) > 59){
            return false
        }
        return true;
    } else {
        return false;
    }
}

// A diferença para esta função, é que se o campo informado vier com valor
// em branco, então ele considera que está correto. Esta função está sendo utilizada 
// para validar os campos antes de salvar o Form de Atendimento.
function validarData_DesconsiderarCampoEmBranco(c){
    if (c.value != ""){
        return validarData(c);
    } else {
        return true;
    }
}

function verificaData (c) { 
    
    if (c.value != ""){
        
        var dia = (c.value.substring(0,2)); 
        var mes = (c.value.substring(3,5)); 
        var ano = (c.value.substring(6,10)); 
        
        var situacao = ""; 
        // verifica o dia valido para cada mes 
        if (dia < 1 || dia > 31){
            situacao = "falsa"; 
        }
        
        if (dia > 30 && ( mes == 4 || mes == 6 || mes == 9 || mes == 11 )){
            situacao = "falsa"; 
        } 
        
        // verifica se o mes e valido 
        if (mes < 1 || mes > 12 ) { 
            situacao = "falsa"; 
        }
        
        // verifica se e ano bissexto 
        if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
            situacao = "falsa"; 
        } 
        
        // verifica se ano possui 4 digitos.
        if ( (ano.length = 4) && (ano > 1900) ){
            situacao = "verdadeira";
        } else {
            situacao = "falsa"; 
        }
        
        if (c.value == "") { 
            situacao = "falsa"; 
        }
        
        if (situacao == "falsa") { 
            alert("Data inválida!"); 
        //c.focus();
        }
    }
}

function preencherData(dataJson){
    if (dataJson==null){
        return ""; 
    } 
    else {
        var data = new Date(dataJson);
        var dia = (data.getDate()); 
        if (dia < 10) {
            dia = "0" + dia;
        }
        var mes = (data.getMonth() + 1); 
        if (mes < 10) {
            mes = "0" + mes;
        }
        return dia + "/" + mes + "/" + data.getFullYear();
    }
}


function inStr(texto,c,posInicial) {
    if (posInicial<0) posInicial=0;
    
    for(var i=posInicial; i<texto.length;i++) {
        if(texto.charAt(i)==c) return i;
    }
    return -1;
}

// retira caracteres invalidos da string
function cleanStr(str,validos) {
    var i,temp = "";
    for (i=0;i<str.length;i++){
        if (validos.indexOf(str.charAt(i)) != -1){
            temp += str.charAt(i);
        }
    }
    return temp;
}

function preencherComboGenerico(jsonObj, comboId, qtdCarac){
    //alert(jsonObj);
    /* 
     * Verifica se foi informado o tamanho máximo de caracteres na combo.
     * Se não foi, então coloca o valor default deste método. 
     */
    var qtdMaxCarac = 20; // valor default.
    if (qtdCarac > 0){
        qtdMaxCarac = qtdCarac;
    }
    
    var combo = document.getElementById(comboId);
    limparCombo(combo);
    var elemOpt = document.createElement("OPTION");
    var text = document.createTextNode("");
    elemOpt.setAttribute("value",0);
    elemOpt.appendChild(text);
    combo.appendChild(elemOpt);
    
    if (jsonObj != null){
        for (var i = 0; i < jsonObj.length; i++){
          
            // Verifica se é necessário diminuir o tamanho do texto que vai na combo.
            var nomeTmp = "";
            if ((jsonObj[i].nome).length > qtdMaxCarac) {
                nomeTmp = (jsonObj[i].nome).substring(0,qtdMaxCarac) + '...';
            }
            else {
                nomeTmp = jsonObj[i].nome;
            }

            elemOpt = document.createElement("OPTION");
            text = document.createTextNode(nomeTmp);
            elemOpt.setAttribute("value",jsonObj[i].id);
            elemOpt.appendChild(text);
            combo.appendChild(elemOpt);
        }
    }   
    
}

function preencherComboGenericoComStatus(jsonObj, comboId, qtdCarac){
    //alert(jsonObj);
    /* 
     * Verifica se foi informado o tamanho máximo de caracteres na combo.
     * Se não foi, então coloca o valor default deste método. 
     */
    var qtdMaxCarac = 20; // valor default.
    if (qtdCarac > 0){
        qtdMaxCarac = qtdCarac;
    }
    
    var combo = document.getElementById(comboId);
    limparCombo(combo);
    var elemOpt = document.createElement("OPTION");
    var text = document.createTextNode("");
    elemOpt.setAttribute("value",0);
    elemOpt.appendChild(text);
    combo.appendChild(elemOpt);
    
    if (jsonObj != null){
        for (var i = 0; i < jsonObj.length; i++){
          
            // Verifica se é necessário diminuir o tamanho do texto que vai na combo.
            var nomeTmp = "";
            if ((jsonObj[i].nome).length > qtdMaxCarac) {
                nomeTmp = (jsonObj[i].nome).substring(0,qtdMaxCarac) + '...';
            }
            else {
                nomeTmp = jsonObj[i].nome;
            }
          
            if (jsonObj[i].status == 'C'){
                nomeTmp += ' (C)';
            }

            elemOpt = document.createElement("OPTION");
            text = document.createTextNode(nomeTmp);
            elemOpt.setAttribute("value",jsonObj[i].id);
            elemOpt.appendChild(text);
            combo.appendChild(elemOpt);
        }
    }   
    
}

function inserirOptionNaCombo(comboId, idObjeto, descObjeto){
    var combo = document.getElementById(comboId);
    var elemOpt = document.createElement("OPTION");
    var text = document.createTextNode(descObjeto);
    elemOpt.setAttribute("value",idObjeto);
    elemOpt.appendChild(text);
    combo.appendChild(elemOpt);
}

function aplicarMascaraCpf(cpf) {     
    var tam = cpf.length;
        
    cpf = cleanStr(cpf,"0123456789");
    tam = cpf.length;
    if (tam > 2) {
        cpf = cpf.substr(0,3) + "." + cpf.substr(3, tam);
    }    
    if (tam > 5) {
        cpf = cpf.substr(0,7) + "." + cpf.substr(7, tam);
    }     
    if (tam > 8) {
        cpf = cpf.substr(0,11) + "-" + cpf.substr(11, tam);
    }     

    return cpf;    
}
    
function isTeclaEspecial(e){
    if ( (e.key == 'c' && e.control) || (e.key == 'x' && e.control) || 
        (e.key == 'v' && e.control) || (e.shift) || (e.key == "end") ||
        (e.key == "backspace") || (e.key == "delete") || (e.key == "left") ||
        (e.key == "right") || (e.key == "tab") ){
        return true;
    } else {
        return false;
    }
}

function digitarCpf(c, e) { 
    
    var cpf = c.value;
    var tam = cpf.length;
    
    if (!isTeclaEspecial(e) ){
        if (tam > 13){
            e.stop();
        }
        if (inStr("1234567890.-", e.key, 0) == -1){
            e.stop();
        }
        cpf = cleanStr(cpf,"0123456789");
        tam = cpf.length;
        if (tam > 2) {
            if (e.key != ".") cpf = cpf.substr(0,3) + "." + cpf.substr(3, tam);
        }    
        if (tam > 5) {
            if (e.key != ".") cpf = cpf.substr(0,7) + "." + cpf.substr(7, tam);
        }     
        if (tam > 8) {
            if (e.key != "-") cpf = cpf.substr(0,11) + "-" + cpf.substr(11, tam);
        }     

        c.value = cpf;        
    }
}

function digitarCep(c, e) { 
    var cep = c.value;
    var tam = cep.length;
    if (!isTeclaEspecial(e) ){
        if (tam > 9){
            e.stop();
        }
        if (inStr("1234567890-", e.key, 0) == -1){
            e.stop();
        }
        cep = cleanStr(cep,"0123456789");
        tam = cep.length;
        if (tam > 4) {
            if (e.key != "-") cep = cep.substr(0,5) + "-" + cep.substr(5, tam);
        }    

        c.value = cep;
    }
}

function digitarFone(c, e) { 
    var fone = c.value;
    var tam = fone.length;
    if (!isTeclaEspecial(e) ){
        if (tam > 15){
            e.stop();
        }
        if (inStr("1234567890()-", e.key, 0) == -1){
            e.stop();
        }
        fone = cleanStr(fone,"0123456789");
        tam = fone.length;        
        if (tam > 1) {
            if (e.key != "(") fone = fone.substr(0,2) + "(" + fone.substr(2, tam);
        }    
        if (tam > 3) {
            if (e.key != ")") fone = fone.substr(0,5) + ")" + fone.substr(5, tam);
        }    
        if (tam > 7) {
            if (e.key != "-") fone = fone.substr(0,10) + "-" + fone.substr(10, tam);
        }    
        c.value = fone;
    }
}

function aplicarMascaraCnpj(cnpj) { 
    var tam = cnpj.length;
    
    cnpj = cleanStr(cnpj,"0123456789");
    tam = cnpj.length;
    if (tam > 1) {
        cnpj = cnpj.substr(0,2) + "." + cnpj.substr(2, tam);
    }    
    if (tam > 4) {
        cnpj = cnpj.substr(0,6) + "." + cnpj.substr(6, tam);
    }     
    if (tam > 7) {
        cnpj = cnpj.substr(0,10) + "/" + cnpj.substr(10, tam);
    }     
    if (tam > 11) {
        cnpj = cnpj.substr(0,15) + "-" + cnpj.substr(15, tam);
    }     

    return cnpj;    
}

function digitarCnpj(c, e) { 
    var cnpj = c.value;
    var tam = cnpj.length;
    if (!isTeclaEspecial(e) ){
        if (tam > 17){
            e.stop();
        }
        if (inStr("1234567890./-", e.key, 0) == -1){
            e.stop();
        }
        cnpj = cleanStr(cnpj,"0123456789");
        tam = cnpj.length;
        if (tam > 1) {
            if (e.key != ".") cnpj = cnpj.substr(0,2) + "." + cnpj.substr(2, tam);
        }    
        if (tam > 4) {
            if (e.key != ".") cnpj = cnpj.substr(0,6) + "." + cnpj.substr(6, tam);
        }     
        if (tam > 7) {
            if (e.key != "/") cnpj = cnpj.substr(0,10) + "/" + cnpj.substr(10, tam);
        }     
        if (tam > 11) {
            if (e.key != "-") cnpj = cnpj.substr(0,15) + "-" + cnpj.substr(15, tam);
        }     

        c.value = cnpj;
    }
}

function validarCpf(c){
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    var cpf = cleanStr(c.value,"0123456789");
    digitos_iguais = 1;
    if (cpf.length < 11) return false;
    for (i = 0; i < cpf.length - 1; i++){
        if (cpf.charAt(i) != cpf.charAt(i + 1)){
            digitos_iguais = 0;
            break;
        }
    }
    if (!digitos_iguais){
        numeros = cpf.substring(0,9);
        digitos = cpf.substring(9);
        soma = 0;
        for (i = 10; i > 1; i--){
            soma += numeros.charAt(10 - i) * i;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0)) return false;
        numeros = cpf.substring(0,10);
        soma = 0;
        for (i = 11; i > 1; i--){
            soma += numeros.charAt(11 - i) * i;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1)) return false;
        return true;
    }
    else
        return false;
}

function varCpfTudoZero(valor){
    var cpf  = cleanStr(valor,"0123456789");
    if (cpf == '00000000000'){
        return true;
    } else{
        return false;
    }    
}

function campoCpfTudoZero(c){
    var cpf  = cleanStr(c.value,"0123456789");
    if (cpf == '00000000000'){
        return true;
    } else{
        return false;
    }
}
    
function campoCnpjTudoZero(c){
    var cnpj  = cleanStr(c.value,"0123456789");
    if (cnpj == '00000000000000'){
        return true;
    } else{
        return false;
    }
}

function validarCnpj(c){
    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    var cnpj  = cleanStr(c.value,"0123456789");
    digitos_iguais = 1;
    
    if (cnpj.length < 14 && cnpj.length > 15) return false;
    for (i = 0; i < cnpj.length - 1; i++){
        if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
            digitos_iguais = 0;
            break;
        }
    }
    if (!digitos_iguais){
        tamanho = cnpj.length - 2
        numeros = cnpj.substring(0,tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--){
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0)) return false;
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0,tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--){
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2) pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1)) return false;
        return true;
    }
    else
        return false;
}

function exibirMensagemErro(errObj){
    try {
        var erro = Json.evaluate(errObj);
        result = erro.mensagem;
    } catch(err) {
        result = errObj;
    }
    return result;
}
 

function limitarTexto(textoIn, maxChars){
    // Verifica se é necessário diminuir o tamanho do texto que vai na combo.
    var nomeTmp = "";
    if (textoIn.length > maxChars) {
        nomeTmp = textoIn.substring(0,maxChars) + '...';
    }
    else {
        nomeTmp = textoIn;
    }
    return nomeTmp;
}

function encode_utf8( s )
{
    return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
    return decodeURIComponent( escape( s ) );
}