/**
Quando o usuárior clica no campo, limpa o campo e/ou
reescreve o texto.
Texto: texto que deve ficar dentro do botao
Campo: campo
Tipo: tipo do campo para trocar.
*/
function limparNoFocus(texto, tipo, campo)
{
	if(campo.value == texto)
	{
		campo.value = '';
		//campo.type = tipo;
	}
}

function escreverNoBlur(texto, tipo, campo)
{
	if (campo.value == "") 8137-4863
	{
		campo.value = texto;
		//campo.type = tipo;
	}
}

// When the page loads:
function onloadObject(){
	if (document.getElementsByTagName) {
	// Get all the tags of type object in the page.
	var objs = document.getElementsByTagName("object");
		for (i=0; i<objs.length; i++) {
		// Get the HTML content of each object tag
		// and replace it with itself.
		objs[i].outerHTML = objs[i].outerHTML;
		}
	}
}

// When the page unloads:
function onunloadObjects() {
	if (document.getElementsByTagName) {
		//Get all the tags of type object in the page.
		var objs = document.getElementsByTagName("object");
		for (i=0; i<objs.length; i++) {
		// Clear out the HTML content of each object tag
		// to prevent an IE memory leak issue.
		objs[i].outerHTML = "";
		}
	}
} 

function maiuscula(campo) {
        document.getElementById(campo.id).value = campo.value.toUpperCase();
}

function minuscula(campo) {
        document.getElementById(campo.id).value = campo.value.toLowerCase();
}

// Retorna uma string como apenas os caracteres que ela pode ter ou sem os que nao pode ter (de acordo com os parâmetros)
// texto - texto alvo que será analisado e retornado apenas com os caracteres permitidos
// permissao - pode ter os valores 'PodeTerApenas' e 'NaoPodeTer'
// escopo - string de caracteres que pode ter ou nao no texto de acordo com a permissao
function filtraTexto(texto, permissao, escopo) {
        try {
                var novoTexto = '';
                
                if (permissao == 'PodeTerApenas') {
                        for (i = 0; i < texto.length; i++) {
                                if (escopo.indexOf(texto.charAt(i)) != -1) {
                                        novoTexto += texto.charAt(i);
                                }
                        }
                } else {
                        for (i = 0; i < texto.length; i++) {
                                if (escopo.indexOf(texto.charAt(i)) == -1) {
                                        novoTexto += texto.charAt(i);
                                }
                        }
                }
                
                return novoTexto;
        } catch (e) {
                alert('Erro: ' + e.toString());
                return false;
        }
}

function contem(texto, part) {
        if (texto.indexOf(part) == -1) {
                return false;
        } else {
                return true;
        }
}

function semAcentos(texto) {
        try {
                var novoTexto = '';
                
                for (i = 0; i < texto.length; i++) {
                        if (texto.charAt(i) == 'á' || texto.charAt(i) == 'à' || texto.charAt(i) == 'â' || texto.charAt(i) == 'ä' || texto.charAt(i) == 'ã') novoTexto += 'a';
                        else if (texto.charAt(i) == 'Á' || texto.charAt(i) == 'À' || texto.charAt(i) == 'Â' || texto.charAt(i) == 'Ä' || texto.charAt(i) == 'Ã') novoTexto += 'A';
                        else if (texto.charAt(i) == 'é' || texto.charAt(i) == 'è' || texto.charAt(i) == 'ê' || texto.charAt(i) == 'ë') novoTexto += 'e';
                        else if (texto.charAt(i) == 'É' || texto.charAt(i) == 'È' || texto.charAt(i) == 'Ê' || texto.charAt(i) == 'Ë') novoTexto += 'E';
                        else if (texto.charAt(i) == 'í' || texto.charAt(i) == 'ì' || texto.charAt(i) == 'î' || texto.charAt(i) == 'ï' || texto.charAt(i) == '?') novoTexto += 'i';
                        else if (texto.charAt(i) == 'Í' || texto.charAt(i) == 'Ì' || texto.charAt(i) == 'Î' || texto.charAt(i) == 'Ï' || texto.charAt(i) == '?') novoTexto += 'I';
                        else if (texto.charAt(i) == 'ó' || texto.charAt(i) == 'ò' || texto.charAt(i) == 'ô' || texto.charAt(i) == 'ö' || texto.charAt(i) == 'õ') novoTexto += 'o';
                        else if (texto.charAt(i) == 'Ó' || texto.charAt(i) == 'Ò' || texto.charAt(i) == 'Ô' || texto.charAt(i) == 'Ö' || texto.charAt(i) == 'Õ') novoTexto += 'O';
                        else if (texto.charAt(i) == 'ú' || texto.charAt(i) == 'ù' || texto.charAt(i) == 'û' || texto.charAt(i) == 'ü' || texto.charAt(i) == '?') novoTexto += 'u';
                        else if (texto.charAt(i) == 'Ú' || texto.charAt(i) == 'Ù' || texto.charAt(i) == 'Û' || texto.charAt(i) == 'Ü' || texto.charAt(i) == '?') novoTexto += 'U';
                        else if (texto.charAt(i) == '´' || texto.charAt(i) == '¨');
                        else if (texto.charAt(i) == 'ç')novoTexto += 'c';
                        else if (texto.charAt(i) == 'Ç')novoTexto += 'C';
                        else novoTexto += texto.charAt(i);
                }
                return novoTexto;
        } catch (e) {
                alert('Erro: ' + e.toString());
                return false;
        }
        
}

// Preenche o formulário de endereço com informações conseguidas com o cep
function enderecoPorCEP(cep, logradouro, bairro, estado, cidade) {
        try {
                request = createRequest();
                var url = "pegaEnderecoPorCEP.php?cep=" + cep + "&dummy=" + new Date().getTime();
                request.open("GET", url, true);
                request.onreadystatechange = function() {
                        if (request.readyState == 4) {
                                if (request.status == 200) {
                                        var resposta = eval("(" + request.responseText + ")");

                                        logradouro.value = resposta.tipo_logradouro + " " + resposta.logradouro;
                                        logradouro.value = semAcentos(logradouro.value);
                                        maiuscula(logradouro);
                                        
                                        bairro.value = resposta.bairro;
                                        bairro.value = semAcentos(bairro.value);
                                        maiuscula(bairro);
                                        
                                        estado.value = resposta.estado;
                                        estado.value = semAcentos(estado.value);
                                        maiuscula(estado);
                                        
                                        cidade.value = resposta.cidade;
                                        cidade.value = semAcentos(cidade.value);
                                        maiuscula(cidade);
                                }
                        }
                }
                request.send(null);
        } catch(e) {
                alert(e.toString());
        }
}

function formataCPF(cpf) {
        try {
                vr = filtraTexto(cpf, "PodeTerApenas", "0123456789");

                if (vr.length <= 2) {
                        cpf = vr;
                }

                if (vr.length >= 3 && vr.length <= 5) {
                        cpf = vr.substr(0, vr.length - 2) + '-' + vr.substr(vr.length - 2, 2);
                }

                if (vr.length >= 6 && vr.length <= 8) {
                        cpf = vr.substr(0, vr.length - 5) + '.' + vr.substr(vr.length - 5, 3) + '-' + vr.substr(vr.length - 2, 2);
                }

                if (vr.length >= 9 && vr.length <= 10) {
                        cpf = vr.substr(0, vr.length - 8) + '.' + vr.substr(vr.length - 8, 3) + '.' + vr.substr(vr.length - 5, 3) + '-' + vr.substr(vr.length - 2, 2);
                }
                
                if (vr.length >= 11) {
                        cpf = vr.substr(vr.length - 11, 3) + '.' + vr.substr(vr.length - 8, 3) + '.' + vr.substr(vr.length - 5, 3) + '-' + vr.substr(vr.length - 2, 2);
                }
                
                return cpf;
        } catch(e) {
                alert(e.toString());
                return false;
        }
}

function formataCNPJ(cnpj) {
        try {
                vr = filtraTexto(cnpj, "PodeTerApenas", "0123456789");

                if (vr.length <= 2) {
                        cnpj = vr;
                }

                if (vr.length >= 3 && vr.length <= 6) {
                        cnpj = vr.substr(0, vr.length - 2) + '-' + vr.substr(vr.length - 2, 2);
                }

                if (vr.length >= 7 && vr.length <= 9) {
                        cnpj = vr.substr(0, vr.length - 6) + '/' + vr.substr(vr.length - 6, 4) + '-' + vr.substr(vr.length - 2, 2);
                }

                if (vr.length >= 10 && vr.length <= 12) {
                        cnpj = vr.substr(0, vr.length - 9) + '.' + vr.substr(vr.length - 9, 3) + '/' + vr.substr(vr.length - 6, 4) + '-' + vr.substr(vr.length - 2, 2);
                }
                
                if (vr.length >= 13 && vr.length <= 14) {
                        cnpj = vr.substr(0, vr.length - 12) + '.' + vr.substr(vr.length - 12, 3) + '.' + vr.substr(vr.length - 9, 3) + '/' + vr.substr(vr.length - 6, 4) + '-' + vr.substr(vr.length - 2, 2);
                }
                
                if (vr.length >= 15) {
                        cnpj = vr.substr(vr.length - 15, 3) + '.' + vr.substr(vr.length - 12, 3) + '.' + vr.substr(vr.length - 9, 3) + '/' + vr.substr(vr.length - 6, 4) + '-' + vr.substr(vr.length - 2, 2);
                }
                
                return cnpj;
        } catch(e) {
                alert(e.toString());
                return false;
        }
}

function formataTel(tel) {
        try {
                vr = filtraTexto(tel, "PodeTerApenas", "0123456789");

                if (vr.length <= 4) {
                        tel = vr;
                }

                if (vr.length >= 5 && vr.length <= 8) {
                        tel = vr.substr(0, vr.length - 4) + '-' + vr.substr(vr.length - 4, 4);
                }

                if (vr.length == 9) {
                        tel = vr.substr(vr.length - 9, 1) + ') ' + vr.substr(vr.length - 8, 4) + '-' + vr.substr(vr.length - 4, 4);
                }

                if (vr.length >= 10) {
                        tel = '(' + vr.substr(vr.length - 10, 2) + ') ' + vr.substr(vr.length - 8, 4) + '-' + vr.substr(vr.length - 4, 4);
                }
                
                return tel;
        } catch(e) {
                alert(e.toString());
                return false;
        }
}

function formataCEP(cep) {
        try {
                vr = filtraTexto(cep, "PodeTerApenas", "0123456789");

                if (vr.length <= 3) {
                        cep = vr;
                }

                if (vr.length >= 4 && vr.length <= 7) {
                        cep = vr.substr(0, vr.length - 3) + '-' + vr.substr(vr.length - 3, 3);
                }
                
                if (vr.length >= 8) {
                        cep = vr.substr(vr.length - 8, 5) + '-' + vr.substr(vr.length - 3, 3);
                }
                
                return cep;
        } catch(e) {
                alert(e.toString());
                return false;
        }
}

function formataData(data) {
        try {
                vr = filtraTexto(data, "PodeTerApenas", "0123456789");

                if (vr.length <= 4) {
                        data = vr;
                }

                if (vr.length >= 5 && vr.length <= 6) {
                        data = vr.substr(0, vr.length - 4) + '/' + vr.substr(vr.length - 4, 4);
                }
                
                if (vr.length == 7) {
                        data = vr.substr(0, 1) + '/' + vr.substr(vr.length - 6, 2) + '/' + vr.substr(vr.length - 4, 4);
                }

                if (vr.length >= 8) {
                        data = vr.substr(vr.length - 8, 2) + '/' + vr.substr(vr.length - 6, 2) + '/' + vr.substr(vr.length - 4, 4);
                }
                
                return data;
        } catch(e) {
                alert(e.toString());
                return false;
        }
}

function createRequest() {
        var request;
        
        try {
                request = new XMLHttpRequest();
        } catch (e) {
                var XmlHttpVersions = new Array(
                        "MSXML2.XMLHTTP.6.0",
                        "MSXML2.XMLHTTP.5.0",
                        "MSXML2.XMLHTTP.4.0",
                        "MSXML2.XMLHTTP.3.0",
                        "MSXML2.XMLHTTP",
                        "Microsoft.XMLHTTP"
                );
                for (var i = 0; i < XmlHttpVersions.length && !request; i++) {
                        try {
                                request = new ActiveXObject(XmlHttpVersions[i]);
                        } catch (e) {}
                }
        }
        if (!request) {
                alert("Seu navegador não suporta AJAX!");
                return null;
        } else {
                return request;
        }
}

// Troca o texto (filhos) de um elemento identificado pelo id (primeiro argumento da função)
function trocaTexto(el, text) {
        if (el != null) {
                limpaTexto(el);
                var newNode = document.createTextNode(text);
                el.appendChild(newNode);
        }
}

function limpaTexto(el) {
        if (el != null) {
                while (el.hasChildNodes()) {
                        for (var i = 0; i < el.childNodes.length; i++) {
                                var childNode = el.childNodes[i];
                                el.removeChild(childNode);
                        }
                }
        }
}

function pegaTexto(id) {
        texto = "";
        if (id != null) {
                if (id.childNodes) {
                        for (i = 0; i < id.childNodes.length; i++) {
                                no = id.childNodes[i];
                                if (no.nodeValue != null) {
                                        texto += no.nodeValue;
                                }
                        }
                }
        }
        return texto;
}

function validaCpf(CPF) {
        var POSICAO, I, N, SOMA, DV, DV_INFORMADO;
        var DIGITO = new Array;
        DV_INFORMADO = CPF.substr(12, 2); // Retira os dois últimos dígitos do número informado

        // Desemembra o número do CPF na array DIGITO
        N = 0;
        for (I = 0; I <= 10; I++) {
                if (!(I == 3 || I == 7)) {
                        DIGITO[N] = CPF.substr(I, 1);
                        N++;
                }

        }

        // Calcula o valor do 10º dígito da verificação
        POSICAO = 10;
        SOMA = 0;
        for (I = 0; I <= 8; I++) {
                SOMA = SOMA + DIGITO[I] * POSICAO;
                POSICAO--;
        }
        DIGITO[9] = SOMA % 11;
        if (DIGITO[9] < 2) {
                DIGITO[9] = 0;
        } else {
                DIGITO[9] = 11 - DIGITO[9];
        }

        // Calcula o valor do 11º dígito da verificação
        POSICAO = 11;
        SOMA = 0;
        for (I=0; I<=9; I++) {
                SOMA = SOMA + DIGITO[I] * POSICAO;
                POSICAO--;
        }
        DIGITO[10] = SOMA % 11;
        if (DIGITO[10] < 2) {
                DIGITO[10] = 0;
        } else {
                DIGITO[10] = 11 - DIGITO[10];
        }

        // Verifica se os valores dos dígitos verificadores conferem
        DV = DIGITO[9] * 10 + DIGITO[10];
        if (DV != DV_INFORMADO) {
                return false;
        }
        
        return true;
}

// Valida o codigo do cartão
function validaCartao(cod) {
        
        // Deixa apenas os números do cartão
        cod = filtraTexto(cod, "PodeTerApenas", "0123456789");
        
        // Verifica se o codigo tem 16 caracteres
        if (cod.length == 16) {
                
                // O dígito verificador é o ultimo digito do cartão com 16 dígitos
                dvInformado = cod.substr(15, 1);
                
                // exemplo do cálculo com um número ipotético (1632000002989092):
                // (1 * 8) + (6 * 7) + (3 * 6) + (2 * 5) + (0 * 4) + (0 * 3) + (0 * 2) + (0 * 9) + (0 * 8) + (2 * 7) + (9 * 6) + (8 * 5) + (9 * 4) + (0 * 3) + (9 * 2)
                fator = 8;
                somaFatores = 0;
                for (c = 0; c <= 14; c++) {
                        if (fator < 2) {
                                fator = 9;
                        }
                        somaFatores += cod.substr(c, 1) * fator;
                        fator--;
                }
                
                // Calcula o dígito verificador
                dvCalculado = 11 - (somaFatores % 11);
                if (dvCalculado > 9) {
                        dvCalculado = 0;
                }
                
                // Verifica se os dígitos verificadores são iguais
                if (dvCalculado == dvInformado) {
                        return true;
                } else {
                        return false;
                }
                
        // Codigo com quantidade de digitos diferente de 16
        } else {
                return false;
        }
}

// Função para validar data no formato dd/mm/aaaa ou dd-mm-aaaa ou dd.mm.aaaa ou qualquer outro separador nesse formato
function validaData(data) {
        
        // Verifica se a data não tem exatamente 10 caracteres
        if (data.length != 10) {
                return false;
        }
        
        // Verifica se o dia não é formado por números
        if (!isInt(data.substr(0, 2))) {
                return false;
        }
        
        // Verifica se o dia é maior que 31
        if (data.substr(0, 2) > 31) {
                return false;
        }
        
        // Verifica se o mês não é formado por números
        if (!isInt(data.substr(3, 2))) {
                return false;
        }
        
        // Verifica se o mes é maior que 12
        if (data.substr(3, 2) > 12) {
                return false;
        }
        
        switch (data.substr(3, 2)) {
                
                // Para abril, junho, setembro e novembro, verifica se o dia é maior que 30
                case '04':
                case '06':
                case '09':
                case '11':
                        if (data.substr(0, 2) > 30) {
                                return false;
                        }
                        break;
                        
                // Para fevereiro, verifica se o ano é bissexto e tem mais de 29 dias ou se tem mais de 28 dias
                case '02':
                        if ((data.substr(7, 4) % 400 == 0) || (data.substr(7, 4) % 100 != 0) && (data.substr(7, 4) % 4 == 0)) {
                                if (data.substr(0, 2) > 29) {
                                        return false;
                                }
                        } else {
                                if (data.substr(0, 2) > 28) {
                                        return false;
                                }
                        }
                        break;
        }
        
        return true;
}

function isInt(n) {
        for (i = 0; i < n.length; i++) {   
                if (isNaN(n.charAt(i))) {
                        return false;
                }
        }
        return true;
}
