// JavaScript Document
var corAlerta = "#FFCE8E";
var corNormal = "#FFFFFF";
var proibidosSenha = new Array('"', "'", "<", ">");
var siteurl = "";

//-------------------------- jquery on load
$(function() {	
	
	//coloca classe png em todos os titulos com imagem dentro e nos topos do quero comprar
	$("h2 > img, #qc_topo").addClass("png");
	siteurl = $("#siteurl").val();
		
});

function ajax () {
	var temp;
	
	if (window.XMLHttpRequest) {
		temp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		temp = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Seu navegador não dá suporte à AJAX!\nAbra este site em um navegador mais recente.");
	}

	return temp;
}

//---------------------------------------------------------------------- funcoes do formulário cadastre-se
function marca (campo, cor) {
	if (campo == "[object HTMLSelectElement]" && navigator.appVersion.toLowerCase().indexOf("chrome") >= 0) {
		if (cor == corNormal) {
			campo.style.borderColor = cor;
		} else {
			campo.style.borderColor = "#FF6600";
		}
		return;
	}
		
	campo.style.backgroundColor = cor;
}

function avancaFoco (field, limite, idfoco) {
	if (field.value.length >= limite) {
		document.getElementById(idfoco).focus();
	}
}

function foco (id) {
	document.getElementById(id).focus();
}

function bloqueiaLetras (campo, permitidos) {
	var excecoes = new Array();
	
	if (isNaN(campo.value.charAt(campo.value.length - 1))) {
		
		//se não for número, checa se é um char permitido
		if (bloqueiaLetras.arguments.length > 1) {
			for (var i = 0; i < permitidos.length; i++) {
				if (campo.value.charAt(campo.value.length - 1) == permitidos[i]) {
					return;
				}
			}
			
			//se não for numero e não for nenhum permitido, é falso
			campo.value = campo.value.substr(0, campo.value.length - 1);
			
		//se não for numero e não foi definida nenhuma excecao, é falso	
		} else {
			campo.value = campo.value.substr(0, campo.value.length - 1);
		}
	}
}

function limpaPadrao (campo, padrao) {
	if (campo.value == padrao) {
		campo.value = "";
	}
}

//---- formatações automaticas
var dlength = 0;
function formataData (campo, proximo) {
	bloqueiaLetras(campo, ["/"]);

	if (campo.value.length > dlength) {
		if (campo.value.length == 2 || campo.value.length == 5) {
			campo.value += "/";
		} else if (campo.value.length == 10) {
			if (proximo != "") {
				foco(proximo);
			}
		}
	}
	
	dlength = campo.value.length;
}

function formataDinheiro(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/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));
	return (((sign)?'':'-') + 'R$ ' + num + ',' + cents);
}

var cpflength = 0;
function formataCPF (campo, proximo) {

	if (campo.value.length > cpflength) {
		if (campo.value.length == 3 || campo.value.length == 7) {
			campo.value += ".";
		} else if (campo.value.length == 11) {
			campo.value += "-";
		} else if (campo.value.length == 14) {
			foco(proximo);
		}
	}
	
	cpflength = campo.value.length;
}

var cnpjlength = 0;
function formataCNPJ (campo, proximo) {

	if (campo.value.length > cnpjlength) {
		if (campo.value.length == 2 || campo.value.length == 6) {
			campo.value += ".";
		} else if (campo.value.length == 10) {
			campo.value += "/";
		} else if (campo.value.length == 15) {
			campo.value += "-";
		} else if (campo.value.length == 18) {
			foco(proximo);
		}
	}
	
	cnpjlength = campo.value.length;
}

var tellength = 0;
function formataTel (campo, proximo) {

	if (campo.value.length > tellength) {
		if (campo.value.length == 4) {
			campo.value += "-";
		} else if (campo.value.length == 9) {
			foco(proximo);
		}
	}
	
	tellength = campo.value.length;
}

var ceplength = 0;
var prefixo_cep = "";
function formataConsultaCEP (campo, php, proximo, pref) {
	//alert (formataConsultaCEP.arguments.length);
	if (formataConsultaCEP.arguments.length == 4) {
		prefixo_cep = pref;
	}

	bloqueiaLetras(campo, ["-"]);

	if (campo.value.length > ceplength) {
		if (campo.value.length == 5) {
			campo.value += "-";
		} else if (
				   (campo.value.indexOf("-") == 5 && campo.value.length == 9) ||
				   (campo.value.indexOf("-") < 0 && campo.value.length == 8)
				   ) {
			consultaCEP(campo, php);
			foco(proximo);
		}
	}
	
	campo.style.backgroundColor = corNormal;
	
	ceplength = campo.value.length;
}

function consultaCEP (campo, php) {
	document.getElementById(prefixo_cep + "rua").value = "carregando ...";
	document.getElementById(prefixo_cep + "bairro").value = "carregando ...";
	document.getElementById(prefixo_cep + "cidade").value = "carregando ...";
	document.getElementById(prefixo_cep + "estado").options[0].firstChild.nodeValue = "carregando ...";
	
	var cep = campo.value.split("-").join("");
	var url = php + "?cep=" + cep + "&formato=xml";
	
	xmlhttp = ajax();
	
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = recebeInfosCep;
	xmlhttp.send(null);
}

function recebeInfosCep () {
	if (xmlhttp.readyState == 4) {
		
		if (xmlhttp.status == 200) {
			
			var raiz   = xmlhttp.responseXML.getElementsByTagName('resultado')[0];
			var rua    = valorNoh(raiz.getElementsByTagName('rua')[0]);
			var bairro = valorNoh(raiz.getElementsByTagName('bairro')[0]);
			var cidade = valorNoh(raiz.getElementsByTagName('cidade')[0]);
			var estado = valorNoh(raiz.getElementsByTagName('uf')[0]);
			
			document.getElementById(prefixo_cep + "rua").value = rua;
			document.getElementById(prefixo_cep + "bairro").value = bairro;
			document.getElementById(prefixo_cep + "cidade").value = cidade;
			
			var estados = document.getElementById(prefixo_cep + "estado");
			
			for (var i = 0; i < estados.options.length; i++) {
				if (estados.options[i].value.toUpperCase() == estado.toUpperCase()) {
					estados.selectedIndex = i;
				}
			}	
		}
	}
}

function checaProibidos (campo) {
	for (var i = 0; i < proibidosSenha.length; i++) {
		if (campo.value.indexOf(proibidosSenha[i]) >= 0) {
			if (campo.name != "usu_senha" && campo.name != "usu_senha2" ) {
				document.getElementById("aviso").innerHTML = "Não é permitido o uso dos seguintes caracteres em sua senha: " + proibidosSenha.join("  ") + "<br/>";
			}
			marca(campo, corAlerta);
			return false;
		}
	}
	
	marca(campo, corNormal);
	if (campo.name != "usu_senha" && campo.name != "usu_senha2" && campo.name != "usu_senha3" && campo.name != "age_senha2" ) {
		document.getElementById("aviso").innerHTML = "";
	}
	return true;
}

function matchConteudo (c1, c2) {
	var campo1 = document.getElementById(c1);
	var campo2 = document.getElementById(c2);
	
	if (campo1.value != campo2.value) {
		marca(campo1, corAlerta);
		marca(campo2, corAlerta);
		return false;
	} else {
		marca(campo1, corNormal);
		marca(campo2, corNormal);
		return true;
	}
}

function validaData (campo) {
	var ok = true;
	var hoje = new Date();
	
	var data = campo.value.split("/").join("");
	var dia = Number(data.substr(0, 2));
	var mes = Number(data.substr(2, 2));
	var ano = Number(data.substr(4, 4));
	
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)) {
		marca(campo, corAlerta);
		return false;
	}
	
	if (ano > hoje.getFullYear() || ano < 1900) {
		ok = false
		
	} else if (mes < 1 || mes > 12) {
		ok = false;
		
	} else if (
			   dia < 1 || dia > 31 ||
			   (mes == 2 && dia > 29) ||
			   ((mes == 4 || mes == 6 || mes == 9 || mes === 11) && dia > 30)
			   ) {
		ok = false;
	}
	
	
	if (!ok) {
		marca(campo, corAlerta);
		return false;
	} else {
		marca(campo, corNormal);
		return true;
	}
}

var cpfexistente = false;

function consultaCPF (campo, php) {
	if (campo.value.length > 0) {
		cpfexistente = "";
		var url = php + "?rand=" + Math.round(Math.random() * 1000);
		var params  =  "CPF=" + campo.value;
	
		xmlhttp = ajax();
		xmlhttp.open("POST", url, true);
		xmlhttp.onreadystatechange=respostaConsultaCPF;
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", params.length);
		xmlhttp.send(params);
		
		$("#modal_cadastro").fadeIn();
		$("#carregando").fadeIn();
		$("#cpfexistente").hide();
	}
}

function respostaConsultaCPF () {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			$("#carregando").fadeOut();
			if (xmlhttp.responseText == "existente") {
				$("#cpfexistente").fadeIn();
				document.getElementById("cpf").value = "";
				marca (document.getElementById("cpf"), corAlerta);
				cpfexistente = true;
			} else {
				$("#modal_cadastro").fadeOut();
				$("#cpfexistente").hide();
				cpfexistente = false;
			}
		}
	}
}

function limpaCampo (campo) {
	document.getElementById(campo).value = "";
}

function selectCPFouCNPJ (campo, tipo, nextCampo) {
	var tipoPessoa = document.getElementById("nf_tipo_pessoa").value;
	if (tipo == "formata")
	{
		if (tipoPessoa == "Fisica")
		{
			formataCPF(campo, nextCampo);
		}
		else
		{
			formataCNPJ(campo, nextCampo);
		}
	}
	else
	{
		if (tipoPessoa == "Fisica")
		{
			validaCPF(campo);
		}
		else
		{
			validaCNPJ(campo);
		}
	}
}

function validaCPF (campo) {
	
	var cpf = campo.value;
		cpf = cpf.split(".").join("");
		cpf = cpf.split("-").join("");
		
	if (cpf.length < 11) {
		marca(campo, corAlerta);
		return false;
	}
	
	if (cpf.match(/0{11}/) || cpf.match(/1{11}/) || cpf.match(/2{11}/) || cpf.match(/3{11}/) || cpf.match(/4{11}/) ||
		cpf.match(/5{11}/) || cpf.match(/6{11}/) || cpf.match(/7{11}/) || cpf.match(/8{11}/) || cpf.match(/9{11}/)){
		marca(campo, corAlerta);
		return false;
	}
	
	var a = [];
	var b = new Number;
	var c = 11;
	
	for (var i = 0; i < 11; i++) {
		
		a[i] = cpf.charAt(i);
		
		if (i < 9) {
			b += (a[i] * --c);
		}
	}
	
	if ((x = b % 11) < 2) {
		a[9] = 0;
	} else { 
		a[9] = 11 - x;
	}
	
	b = 0;
	c = 11;
	
	for (var y = 0; y < 10; y++) {
		b += (a[y] * c--);
	}
	
	if ((x = b % 11) < 2) {
		a[10] = 0;
	} else {
		a[10] = 11 - x;
	}
	
	
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		// os digitos verificadores (os 2 ultimos) não batem
		marca(campo, corAlerta);
		return false;
	}
	
	marca(campo, corNormal);
	return true;	
}

function validaCNPJ(campo) {
	var CNPJ = campo.value;
	var erro = new String;
	
	if (CNPJ.length < 18) {
		erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
	}
	
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) {
			erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
		}
	}
	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4) {
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x;
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) {
		erro += "A verificação de CNPJ suporta apenas números! \n\n";
	}
	
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	
	for (i = 0; i < 12; i++) {
		
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	
	if ((x = b % 11) < 2) { 
		a[12] = 0;
	} else {
		a[12] = 11 - x;
	}
	
	b = 0;
	
	for (y = 0; y < 13; y++) {
		b += (a[y] * c[y]);
	}
	
	if ((x = b % 11) < 2) {
		a[13] = 0;
	} else {
		a[13] = 11 - x;
	}
	
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
		erro +="Dígito verificador com problema!";
	}
	
	if (erro.length > 0){
		
		//alert(erro);
		marca(campo, corAlerta);
		return false;
		
	} else {
		marca(campo, corNormal);
		//alert("CNPJ válido!");
	}
	
	return true;
}

function validaSenha (campo, opt) {
	var senha = campo.value;
	
	if (
		validaSenha.arguments.length < 2 ||
		(validaSenha.arguments.length == 2 && validaSenha.arguments[1] == true && senha.length > 0)) {
	
		if (senha.length < 5 || senha.length > 10) {
			marca(campo, corAlerta);
			return false;
		}
		
		if (!checaProibidos(campo)) {
			return false;	
		}
	
	}

	marca(campo, corNormal);
	return true;
}

function validaNomeCompleto (campo) {
	if (campo.value.length > 5 && campo.value.split(" ").length > 1) {
		marca(campo, corNormal);
		return true;
	}
	
	marca(campo, corAlerta);
	return false;
}

function validaEmail (campo) {
	
	var email = campo.value;
	
	var regexp = new RegExp(/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/);
	
		if (regexp.test(email)) {
			marca(campo, corNormal);
			return true; 
		}
	
	marca(campo, corAlerta);
	return false;
}

function validaDDD (campo) {
	if (campo.value.length != 2) {
		marca(campo, corAlerta);
		return false;
	} else {
		marca(campo, corNormal);
		return true;
	}
}

function validaTel (campo) {
	var valor = campo.value.split("-").join("");
	if (valor.length < 7 || valor.length > 8) {
		marca(campo, corAlerta);
		return false;
	} else {
		marca(campo, corNormal);
		return true;
	}
}

function comparaEmail (e2) {
	var email = document.getElementById("email");
	var email2 = document.getElementById("email2");
	
	if (email.value != email2.value) {
		marca (email, corAlerta);
		marca (email2, corAlerta);
		$("#emailObs").html(" Os e-mails digitados não conferem.");
		return false;
	}
	marca (email, corNormal);
	marca (email2, corNormal);
	$("#emailObs").html("");
	return true;
}

function validaCadastro (form, mantersenha, alteracaocadastro, ag) {
	var nome, campo, valor, qtd;
	var ok = true;
	var aux = "dados inválidos:\n";
	
	var alteracao;
	if (validaCadastro.arguments.length >= 3 && alteracaocadastro == true) {
		alteracao = true;
	} else {
		alteracao = false;
	}
	
	var agente;
	if (validaCadastro.arguments.length >= 4 && ag == true || ag == 1) {
		agente = true;
	} else {
		agente = false;
	}
	
	for (var i = 0; i < form.elements.length; i++) {
		
		campo = form.elements[i];
		id  = form.elements[i].id;
		valor = form.elements[i].value;
		qtd   = form.elements[i].value.length;
		
		//valida os normais
		if (id == "rua" || id == "bairro" || id == "cidade") {
			if (qtd < 3) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			} else {
				marca (campo, corNormal);
			}
		}
		
		else if (id == "nome") {
			if (!validaNomeCompleto(campo)) {
				ok = false;
			}
		}
		
		else if ( id == "numero") {
			if (qtd < 1) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			} else {
				marca (campo, corNormal);
			}
		}
		
		//valida nascimento
		else if (id == "nascimento") {
			if (!validaData(campo)) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			} else {
				marca (campo, corNormal);
			}
		}
		
		//valida estado civil
		else if (id == "estadocivil") {
			if (campo.options[campo.selectedIndex].value < 0 || campo.options[campo.selectedIndex].value == "") {
				marca (campo, corAlerta);
				ok = false;
				aux += id + "\n";
			} else {
				marca (campo, corNormal);
			}
		}
		
		//valida rg ????????????????????
		else if (id == "rg") {
			if (valor.length < 6) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			} else {
				marca (campo, corNormal);
			}
		}
		
		//valida cpf
		else if (id == "cpf") {
			if (!validaCPF(campo)) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			} else {
				marca (campo, corNormal);
			}
			
			if (alteracao == false && cpfexistente == true) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + " cpf já existente\n";
			} else {
				marca (campo, corNormal);
			}
		}
		
		//valida email
		else if (id == "email") {
			if (!agente || (agente == true && campo.value.length > 0)) {
				if (!validaEmail(campo)) {
					marca (campo, corAlerta);
					ok = false;
					
					aux += id + "\n";
				} else {
					marca (campo, corNormal);
				}
			}
		}
		
		else if (id == "email2") {
			if (!comparaEmail()) {
				ok = false;
			}
		}
		
		
		//valida cep
		else if (id == "cep") {
			if (valor.split("-").join("").length != 8) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//valida estado
		else if (id == "estado") {
			if (campo.options[campo.selectedIndex].value < 0 || campo.options[campo.selectedIndex].value == "") {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//valida senha1  (nem vai entrar nesse se for agente pq não existe o campo)
		else if (id == "senha1" && 
				 (validaCadastro.arguments.length < 1 || validaCadastro.arguments[1] == false) ||
				 (validaCadastro.arguments.length == 1 && validaCadastro.arguments[1] == true && valor.length > 0)
				 ) {
			
			if (!validaSenha(campo) || valor != document.getElementById("senha2").value) {
				marca (campo, corAlerta);
				marca (document.getElementById("senha2"), corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//valida ddd -> OPCIONAL
		else if (id.indexOf("ddd_") >= 0) {
			if (id == "ddd_res") {
				if (!validaDDD(campo)) {
					marca (campo, corAlerta);
					ok = false;
				
					aux += id + "\n";
				}
			} else {
				//só valida se estiver preenchido já que não é obrigatório
				if (valor.length > 0) {
					if (valor.length != 2) {
						marca (campo, corAlerta);
						ok = false;
						aux += id + "\n";
					}
				}
			}
		}
		
		//valida telefone -> OPCIONAL
		else if (id.indexOf("tel_") >= 0) {
			if (id == "tel_res") {
				if (!validaTel(campo)) {
					marca (campo, corAlerta);
					ok = false;
					aux += id + "\n";
				}
				
			} else {
				//só valida se estiver preenchido já que não é obrigatório
				if (valor.length > 0) {
					
					valor = valor.split("-").join("");
					
					if (valor.length < 7 || valor.length > 8) {
						marca (campo, corAlerta);
						ok = false;
						aux += id + "\n";
					}
				}
			}
		}
		
		//alert ("elemento  " + id + " status = " + ok); 
		
	}
	
	
	
	if (!ok) {
		//alert (aux);
		document.getElementById("aviso").innerHTML = "Preencha corretamente os campos destacados.";
		jQuery("#boxAviso").css("display", "inline-block");
		return false;
	}
	
	return true;
	
}

function validaCadastroAgente (form) {
	var nome, campo, valor, qtd;
	var ok = true;
	var aux = "dados inválidos:\n";
	
	for (var i = 0; i < form.elements.length; i++) {
		
		campo = form.elements[i];
		id  = form.elements[i].id;
		valor = form.elements[i].value;
		//qtd   = form.elements[i].value.length;
		qtd = $(form.elements[i]).val().length
		marca (campo, corNormal);
		
		//valida os normais
		if (
			id == "nome" 
			|| id == "rua" 
			|| id == "bairro" 
			|| id == "cidade" 
			|| id == "razao_social" 
			|| id == "nome_fantasia"
			|| id == "ramo" 
			|| id == "banco" 
			|| id == "nf_tipo_pessoa" 
			|| id == "nome_favorecido" 
			|| id == "responsavel_financeiro"
			/*|| id == "agencia"
			|| id == "conta_corrente"
			|| id == "nf_cnpj" //////
			|| id == "rf_tel" ///////*/
			) {
				if (qtd < 2) {
					marca (campo, corAlerta);
					ok = false;
					
					aux += id + "\n";
				}
		}
		
		else if (
			id == "agencia" || id == "conta_corrente") {
			if (qtd < 1) {
					marca (campo, corAlerta);
					ok = false;
					aux += id + "\n";
				}
		}
		
		else if (id == "numero") {
			if (qtd < 1) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//valida cnpj
		else if (id.indexOf("cnpj") >= 0) {
			if (id == "nf_cnpj") {
				if (!validaCPF(campo) && !validaCNPJ(campo)) {
					marca (campo, corAlerta);
					ok = false;
					aux += id + "\n";
				}
			} else {
					if (!validaCNPJ(campo)) {
						marca (campo, corAlerta);
						ok = false;
						
						aux += id + "\n";
					}
			}
		}
		
		//valida email
		else if (id == "email") {
			if (!validaEmail(campo)) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		else if (id == "email2") {
			if (!comparaEmail()) {
				ok = false;
			}
		}
		
		//valida cep
		else if (id == "cep") {
			if (valor.split("-").join("").length != 8) {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//valida estado
		else if (id == "estado") {
			if (campo.options[campo.selectedIndex].value < 0 || campo.options[campo.selectedIndex].value == "") {
				marca (campo, corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//valida ddd -> OPCIONAL
		else if (id.indexOf("ddd_") >= 0) {
			if (id == "ddd_tel") {
				if (!validaDDD(campo)) {
					marca (campo, corAlerta);
					ok = false;
				
					aux += id + "\n";
				}
			} else {
				//só valida se estiver preenchido já que não é obrigatório
				if (valor.length > 0) {
					if (valor.length != 2) {
						marca (campo, corAlerta);
						ok = false;
						aux += id + "\n";
					}
				}
			}
		}
		
		//valida telefone -> OPCIONAL
		else if (id.indexOf("tel_") >= 0 || id.indexOf("_tel") >= 0) {
			if (id == "tel_tel") {
				if (!validaTel(campo)) {
					marca (campo, corAlerta);
					ok = false;
					aux += id + "\n";
				}
				
			} else if (id == "rf_tel") {
				if (qtd < 7) {
					marca (campo, corAlerta);
					ok = false;
					aux += id + "\n";
				}
			} else {
				//só valida se estiver preenchido já que não é obrigatório
				if (valor.length > 0) {
					
					valor = valor.split("-").join("");
					
					if (valor.length < 7 || valor.length > 8) {
						marca (campo, corAlerta);
						ok = false;
						aux += id + "\n";
					}
				}
			}
		}
		
		//valida senha1
		else if (id == "senha1") {
			
			if (!validaSenha(campo) || valor != document.getElementById("senha2").value) {
				marca (campo, corAlerta);
				marca (document.getElementById("senha2"), corAlerta);
				ok = false;
				
				aux += id + "\n";
			}
		}
		
		//alert ("elemento  " + id + " status = " + ok); 
		
	}
	
	if (!ok) {
		//alert (aux);
		document.getElementById("aviso").innerHTML = "Preencha corretamente os campos destacados.";
		jQuery("#boxAviso").css("display", "inline-block");
		//alert(aux);
		return false;
	}
	
	if (!document.getElementById('aceitar').checked) {
		document.getElementById("label_aceitar").style.color = "#FFDA00";
		document.getElementById("aviso").innerHTML = "Para prosseguir, é necessário aceitar o termo de adesão.";
		jQuery("#boxAviso").css("display", "inline-block");
		return false;
	}
	
	if ((document.getElementById("qtd_socios").value == "0" || document.getElementById("qtd_socios").value == 0) && !validaSocio()) {
		document.getElementById("aviso").innerHTML = "Inclua, pelo menos, um sócio.";
		jQuery("#boxAviso").css("display", "inline-block");
		return false;
	}
	
	return true;
}

function inserirSocio () {
	if (validaSocio()) {
		$("#qtd_socios").val(Number($("#qtd_socios").val()) + 1);
		
		var campos = new Array ("socio_nome", "socio_rg", "socio_cpf", "socio_participacao", "socio_estado_civil", "socio_profissao", "socio_ddd_res", "socio_tel_res", "socio_ddd_cel", "socio_tel_cel", "socio_cep", "socio_rua", "socio_numero", "socio_complemento", "socio_bairro", "socio_cidade", "socio_estado" );
		
		var table = $("#socios_incluidos");
		var ix = $("tr", table).length;
		
		var tr  = "<tr>";
		
			tr += "<td class='td_nome_socio'>" + $("#socio_nome").val() + "</td>";
			tr += "<td class='td_excluir_socio'><a href='#' onclick='javascript: return excluirSocio(this);' class='excluir-socio'>excluir</a>";
			
			for (var i = 0; i < campos.length; i++) {
				var input = "<input type='hidden' name='"+ campos[i] + "[]' id='" + campos[i] + ix + "' value='"+ $("#" + campos[i]).val() +"' />";
				tr += input;
				$("#" + campos[i]).val("");
			}
			
			tr += "</td>";
			tr += "</tr>";
			
			table.append(tr);
			
			$("#aviso").html("");
			$("#boxAviso").hide();
	}
}

function excluirSocio (a) {
	$("#qtd_socios").val(Number($("#qtd_socios").val()) - 1);
	$($($(a).parents("tr"))[0]).remove();
	return false;
}

function validaSocio () {
	var nome, campo, valor, qtd;
	var ok = true;
	var aux = "dados inválidos:\n";
	var form = document.getElementById("form_cadastrese");
	
	for (var i = 0; i < form.elements.length; i++) {
		
		if (form.elements[i].id.indexOf("socio") < 0) {
			continue;
		}
		
			campo = form.elements[i];
			id  = form.elements[i].id;
			valor = form.elements[i].value;
			qtd   = form.elements[i].value.length;
			
			//valida os normais
			if (
				id == "socio_nome" || id == "socio_rg" || id == "socio_rua" || id == "socio_numero" || id == "socio_bairro" || id == "socio_cidade" || id == "socio_estado_civil" || id == "socio_profissao"
				) {
				if (qtd < 2) {
					marca (campo, corAlerta);
					ok = false;
					
					aux += id + "\n";
				} else {
					marca (campo, corNormal);
				}
			}
			
			//valida cnpj
			else if (id == "socio_cpf") {
				if (!validaCPF(campo)) {
					marca (campo, corAlerta);
					ok = false;
					
					aux += id + "\n";
				}
			}
			
			//valida email
			else if (id == "socio_email") {
				if (!validaEmail(campo)) {
					marca (campo, corAlerta);
					ok = false;
					
					aux += id + "\n";
				}
			}
			
			//valida cep
			else if (id == "socio_cep") {
				if (valor.split("-").join("").length != 8) {
					marca (campo, corAlerta);
					ok = false;
					
					aux += id + "\n";
				}
			}
			
			//valida estado
			else if (id == "socio_estado") {
				if ($(campo).val() == "") {
					marca (campo, corAlerta);
					ok = false;
					aux += id + "\n";
				}
			}
			
			//valida ddd -> OPCIONAL
			else if (id.indexOf("socio_ddd_") >= 0) {
				//só valida se estiver preenchido já que não é obrigatório
				if (valor.length > 0) {
					if (valor.length != 2) {
						marca (campo, corAlerta);
						ok = false;
						aux += id + "\n";
					}
				}
			}
			
			//valida telefone -> OPCIONAL
			else if (id.indexOf("socio_tel_") >= 0) {
				if (valor.length > 0) {
						
						valor = valor.split("-").join("");
						
						if (valor.length < 7 || valor.length > 8) {
							marca (campo, corAlerta);
							ok = false;
							aux += id + "\n";
						}
					}
				}
			}
			
			//alert ("elemento  " + id + " status = " + ok); 
		
		if (!ok) {
			//alert (aux);
			document.getElementById("p_aviso_socio").innerHTML = "Preencha corretamente os dados do sócio.";
			jQuery("#boxAviso").css("display", "inline-block");
			return false;
		} else {
			return true;
		}
		
}


function abreFormPassageiros () {
	if ($("#form_passageiros").is(":hidden")) {
		$('#form_passageiros').fadeIn('slow', 
									  
									  function() {
											$('#obs_parcelas').animate({
																		top: '+=' + $('#form_passageiros').height()
																	  })
										
											
									  });
		$("#rodape").animate ({bottom: '0'});	
	}

}

function fechaFormPassageiros () {
	if (!$("#form_passageiros").is(":hidden")) {
		
		var f = document.getElementById("p3_compra");
		
		for (var i = 0; i < f.elements.length; i++) {
			
			if (f.elements[i].name.indexOf("passag_") >= 0) {
				
				marca(f.elements[i], corNormal);
				
				if (f.elements[i].name.indexOf("passag_nasc") >= 0) {
					f.elements[i].value = "dd/mm/aaaa";
				} else {
					f.elements[i].value = "";
				}
			}
		}
		
		$('#obs_parcelas').animate({
									top: '-=' + $('#form_passageiros').height()
								  }, function () {
													$('#form_passageiros').fadeOut();
												 });
	
		$("#rodape").animate ({bottom: '0'});
	}
}

function abreFechaParcelas (a) {
	
	if (a.innerHTML == " + detalhes") {
		a.innerHTML = " - detalhes";
	} else {
		a.innerHTML = " + detalhes";
	}
	exibeEsconde("obs_parcelas");
}

function calculaIdade (hj, nv) {
	var idade;
	var msg;
	
	var hoje = hj.split("/");
	var niver = nv.split("/");
	
	idade = hoje[2] - niver[2];
	msg = "primeiro cálculo: idade = " + idade + " anos<br />";
	
	if (//se o mes do niver for maior que o mes atual ou se for igual mas o dia for maior, não fez niver, tira um ano
		Number(niver[1]) > Number(hoje[1]) || 
		(Number(niver[1]) == Number(hoje[1]) && Number(niver[0]) > Number(hoje[0]))) {
		idade--;
		msg += "ainda não fez aniversário<br />";
		msg += "segundo cálculo: " + idade + "<br />";
	} else {
		msg += "já fez aniversário.<br />";
	}
	
	return idade;
}

//---------------------------------------------------------------------- validaCompra

function validaCadastroVenda (form) {
	
	if (!document.getElementById('aceitar').checked) {
		document.getElementById("label_aceitar").style.color = "#FFDA00";

		document.getElementById("aviso").innerHTML = "Para prosseguir, é necessário aceitar o contrato de Compra e Venda de passagens aéreas nacionais.";
		jQuery("#boxAviso").css("display", "inline-block");
		
		return false;
		
	} else if (
		//só checar alguns dados principais, só pra garantir novamente que a sessão não estava vazia
		$("#cod_usuario").val() == "" ||
		$("#cpf").val() == "" ||
		$("#tipo_trecho").val() == "" ||
		$("#valor_total").val() == "" ||
		$("#valor_parcela").val() == ""
	) {
		var c = confirm("Alguns dados não estão sendo informados. Desculpe-nos, tente refazer os passos da compra.\nPodemos encaminhá-lo para o primeiro passo?");
		if (c) { window.location.assign("quero-comprar.php");}
		return false;
	} else  {
		document.getElementById("label_aceitar").style.color = "#FFFFFF";
		$("#finalizar").attr("disabled", "disabled").css("cursor", "default").fadeTo(0.5);
		document.getElementById("aviso").innerHTML = "Aguarde enquanto seu pedido está sendo processado.";
		jQuery("#boxAviso").css("display", "inline-block");
		return true;
	}
	
	
}


//---------------------------------------------------------------------- funcao do faça seu login

function abreBox (id) {
	if (!document.getElementById(id).style.visibility) {
		document.getElementById(id).style.visibility = "visible";
	}
}

function fechaBox (id) {
	if (document.getElementById(id).style.visibility == "visible") {
		document.getElementById(id).style.visibility = "hidden";
	}
}


//--------------------------------------------------------------------- submenu do menu principal
function mostraSub (id) {
	fechar = false;
	$("#" + id).css("z-index", 200).show();
}

function escondeSub (id) {
	fechar = true;
	$("#" + id).hide();
}


//------------------------------------------------------------------------------------- validaçao dos forms

function avisar (msg, paragrafo) {	
	if (paragrafo != "") {
		document.getElementById(paragrafo).innerHTML = msg;
	}
}

function limitaChars (field, limite, p_aviso) {	
	limite--;
	
	if (field.value.length > limite) {
		field.value = field.value.substring(0, limite);
	}
	
	var restantes = limite - field.value.length;
	if (restantes > 1) {
		document.getElementById(p_aviso).innerHTML = "Restam " + restantes + " caracteres.";
	} else if (restantes == 1) {
		document.getElementById(p_aviso).innerHTML = "Resta " + restantes + " caractere.";
	} else {
		document.getElementById(p_aviso).innerHTML = "Nenhum caractere restante.";
	}
}


function valida (f, paragrafo, opcionais) {
	
	var tipo; // text, password, textarea, select-one, checkbox, radio
	var valor;
	var id;
	var name;
	var opc = new Array(); // neste parametro passa num array os index dos campos que não são obrigatorios
	var opcional = false;
	
	if (valida.arguments.length >= 3) {
		for (var j = 0; j < opcionais.length; j++) {
			opc[j] = opcionais[j];
		}				
	}
	
	for (var i = 0;  i < f.elements.length; i++) {
		
		
		//conferir se o i está entre os índices de elementos opcionais.
		opcional = false;
		for (var jj = 0; jj < opc.length; jj ++) {
			if (i == opc[jj]) {
				opcional = true;
				break;
			}
		}
		
		//se for obrigatório ou se for opcional mas estiver preenchido
		if (!opcional || (opcional && f.elements[i].value.length > 0)) {
		
			tipo = f.elements[i].type;
			valor = f.elements[i].value;
			id = f.elements[i].id;
			name = f.elements[i].name;
			
			if (tipo == "text" || tipo == "password" || tipo == "textarea") {
				
				//----------- se for email
				if (id == "email" || name == "email") {
					
					if (valor.length < 7 ||
						valor.split("@").length != 2 ||
						valor.indexOf("@") < 1 ||
						valor.lastIndexOf(".") <= valor.indexOf("@")) {
						
						avisar("Preencha o campo email com um email válido.", paragrafo);
						f.elements[i].focus();
						return false;
					}
					
				//------------ se for dia ou mes	
				} else if (id == "dia" || name == "dia" || id == "mes" || name == "mes" ||
						   id == "ddd" || name == "ddd") {
					
					if (valor.length != 2) {
						avisar("Formato da Data: dd-mm-aaaa", paragrafo);
						f.elements[i].focus();
						return false;
					}
				
				
				//----------- se for ano
				} else if (id == "ano" || name == "ano") {
						
						if (valor.length != 4) {
							avisar("Formato da Data: dd-mm-aaaa", paragrafo);
							f.elements[i].focus();
							return false;
						}
				
				
				//----------- se for texto simples, que não pode ter menos de 2 letras
				}  else if (id == "telefone" || name == "telefone") {
						
						if (valor.length < 8) {
							avisar("Preencha corretamente o telefone.", paragrafo);
							f.elements[i].focus();
							return false;
						}
				
				
				//----------- se for texto simples, que não pode ter menos de 2 letras
				} else {
					
						if (valor.length < 2) {
							avisar("Preencha corretamente os campos obrigatórios.", paragrafo);
							f.elements[i].focus();
							return false;
						}
				}
				
			} // fim do if type = text
			
			else if (tipo == "select-one") {
				
				if (valor == "" || valor == 0 || valor == "0") {
					avisar("Preencha corretamente os campos obrigatórios.", paragrafo);
					f.elements[i].focus();
					return false;
				}
				
			}
			
			else if (tipo == "file") {
				
				if (valor.length > 5) {
					var classe = f.elements[i].className;
					var permitido = false;
					
					if (classe != null && classe != "undefined" && classe.indexOf("EXT") >= 0) {
						var extensoes = classe.split("_");
						var extensao = valor.substr(valor.lastIndexOf(".") + 1);
						
						for (var ex = 0; ex < extensoes.length; ex++) {
							if (extensoes[ex] != "EXT" && extensao.toLowerCase() == extensoes[ex].toLowerCase()) {
								permitido = true;
							}
						}
						
						if (!permitido) {
							avisar("Preencha corretamente os campos obrigatórios.", paragrafo);
							f.elements[i].focus();
							return false;
						}
					}
				} else {
					avisar("Preencha corretamente os campos obrigatórios.", paragrafo);
					f.elements[i].focus();
					return false;
				}
			}
			
				
		} // fim do if opcional
		
	} // fim do loop dos elementos
	
	return true;
}


function validaEsqueci (n) {
	var id;
	if (validaEsqueci.arguments.length == 1) {
		id = n;
	} else {
		id = 'esqueci_cpf';
	}
	
	if (validaCPF(document.getElementById(id))) {
		return true;							  
	} else {
		return false;
	}
	
}

function validaLoginCliente (form) {
	
	if (validaCPF(form.elements[0]) && validaSenha(form.elements[1])) {
		return true;
	} else {
		return false;
	}
	
}

function validaBuscaContrato (form, p) {
	
	if (validaCPF(form.elements[0]) && form.elements[1].value.length > 5 && form.elements[1].value.length < 20) {
		return true;
	} else {
		if (validaBuscaContrato.arguments.length > 1 && p != "") {
			document.getElementById(p).innerHTML = "Verifique se os dados digitados estão corretos e tente novamente.";
		}
		return false;
	}
	
}

/*function validaLoginP2 (form) {
	//QUANDFO AINDA TINHA AGENTE DE VIAGEM
	if (document.getElementById("usu_senha2").value.length < 5) {
		//se não preencheu a senha, tem que ter preenchido login e senha de agente
		if (!validaEmail(document.getElementById("age_login2")) || !validaSenha(document.getElementById("age_senha2"))) {
			document.getElementById("aviso_login_p2").innerHTML = "Por favor, preencha todos os campos corretamente.";
			return false;
		} else {
			document.getElementById("aviso_login_p2").innerHTML = "... aguarde ...";
			//return false;
			return true;
		}
		
		
	} else {
		
		//se senha do cliente estiver preenchida
		if (validaCPF(form.elements[0]) && validaSenha(form.elements[1])) {
			
			document.getElementById("aviso_login_p2").innerHTML = "... aguarde ...";
			//return false;
			return true;
			
		} else {
			
			document.getElementById("aviso_login_p2").innerHTML = "Por favor, preencha todos os campos corretamente.";
			return false;
		}
		
	}
	
}*/
function validaLoginP2 (form) {
	
	if (validaCPF(form.elements[0]) && validaSenha(form.elements[1])) {
		document.getElementById("aviso_login_p2").innerHTML = "... aguarde ...";
		return true;
		
	} else {
		document.getElementById("aviso_login_p2").innerHTML = "Por favor, preencha todos os campos corretamente.";
		return false;
	}
	
}

function p2SouAgente (a) {
	
	if (a.innerHTML.toLowerCase() == "sou agente de viagem") {
		
		//abre opção para agente
		a.innerHTML = "não sou agente de viagem";
		marca(document.getElementById('usu_senha2'), corNormal);
		document.getElementById('usu_senha2').value = "";
		esconde('div_usu_senha2');
		exibe('div_login_agente2');
	} else {
		
		//limpa os campos e fecha opção de agente
		a.innerHTML = "sou agente de viagem";
		marca(document.getElementById('age_login2'), corNormal);
		marca(document.getElementById('age_senha2'), corNormal);
		document.getElementById('age_login2').value = "";
		document.getElementById('age_senha2').value = "";
		exibe('div_usu_senha2');
		esconde('div_login_agente2');
	}
	
}

function detalheCompra (row, a) {
	
	var table = row.parentNode.parentNode; //o parentNode é tbody, depois que vem table
	var contrato = row.cells[1].innerHTML;
	var tr = table.rows[row.rowIndex + 1];
	
	if (a.innerHTML == "+detalhes") {
		//cria e abre box de detalhes
		a.innerHTML = "-detalhes";
		$(tr).fadeIn("fast");
		
	
	} else if (a.innerHTML == "-detalhes") {
		//fecha box de detalhes
		a.innerHTML = "+detalhes";
		$(tr).fadeOut("fast");
	}
	
}


/*---------------------------------- rotas e destinos ---------------------------------*/
var liRota;
var rotaAnterior;
function exibeRotasDestinos (li_a, cod, php) {
	
	if (liRota && liRota != "undefined") {
		if (liRota == li_a.parentNode) {
			if (!$(liRota.getElementsByTagName("ul")[0]).is(":hidden")) {
				$(liRota.getElementsByTagName("ul")[0]).fadeOut();
			} else {
				$(liRota.getElementsByTagName("ul")[0]).fadeIn();
			}
			return;
		}
		rotaAnterior = liRota;
		//liRota.removeChild(liRota.getElementsByTagName("ul")[0]);
		rotaAnterior.getElementsByTagName("a")[0].removeAttribute("id");
	}
	
	$("#modal").fadeIn();
	
	var origem = cod;
	li_a.setAttribute("id", "rota_clicada");
	liRota = li_a.parentNode;
	
	var url = php + "?rand=" + Math.round(Math.random() * 1000);
	var params = "CodOrigem=" + cod + "&CodCompanhia=0";
	
	xmlhttp = ajax();
	
	xmlhttp.open("POST", url, true);
	xmlhttp.onreadystatechange=exibeListaDestinos;
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.send(params);
}

function exibeListaDestinos () {
	if (xmlhttp.readyState == 4) {
		
		if (xmlhttp.status == 200) {
			
			if (rotaAnterior && rotaAnterior != "undefined") {
				rotaAnterior.removeChild(rotaAnterior.getElementsByTagName("ul")[0]);
			}
			
			var raiz 	= xmlhttp.responseXML.getElementsByTagName('ArrayOfCidadesOrigensDestinosTO')[0];
			var destino = raiz.getElementsByTagName('CidadesOrigensDestinosTO');
			var qtd 	= raiz.getElementsByTagName('CidadesOrigensDestinosTO').length;
			
			var ul = document.createElement("ul");
				ul.setAttribute("id", "ulDestinos");
				ul.setAttribute("class", "displaynone");
				liRota.appendChild(ul);
			
			for (var i = 0; i < qtd; i++) {
				
				var li = document.createElement("li");
					li.appendChild(document.createTextNode(valorNoh(destino[i].getElementsByTagName("descricao")[0])));
					ul.appendChild(li);	
			}
			
			$("#modal").fadeOut();
			$("#ulDestinos").fadeIn();
			$("#rodape").animate ({bottom: '0'});
		}
	}
}

function copiaPara (campo, id) {
	document.getElementById(id).innerHTML = campo.value;
	if (campo.value == 0) {
		document.getElementById(id).innerHTML = "login: email cadastrado";
	}
}


var compraclicada = "";
var compracpf = "";
var trvis;
var tbody;
var totalcompra

function exibeDetalhesCompras (aclick, php, codvenda, cpf, total) {
	var exibeParcelas = ($("#tbody" + codvenda).length > 0);
	
	tbody = trvis = null;
	
	trvis = $($(aclick).parents("tr")[0]);
	trvis = trvis.next("tr.info_viagem");
	
	if (exibeParcelas) {
		tbody = document.getElementById("tbody" + codvenda);
		trvis = tbody.parentNode.parentNode.parentNode;
	}
	
	if (aclick.innerHTML == "+detalhes") {
		$(trvis).stop(true, true).fadeIn("fast");
		aclick.innerHTML = "-detalhes";
		
	} else if (aclick.innerHTML == "-detalhes") {
		$(trvis).stop(true, true).fadeOut("fast");
		aclick.innerHTML = "+detalhes";
	}
	
	if (compraclicada != codvenda) {
		compraclicada = codvenda;
		compracpf = cpf;
		totalcompra = total;
		
		if (exibeParcelas) {
			if (!tbody.hasChildNodes()) {
				var url = php + "?rand=" + Math.round(Math.random() * 1000);
				var params = "CodVenda=" + codvenda;
				$("#compramodal").fadeIn();
				
				xmlhttp = ajax();
				xmlhttp.open("POST", url, true);
				xmlhttp.onreadystatechange=listaDetalhesCompras;
				xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlhttp.setRequestHeader("Content-length", params.length);
				xmlhttp.send(params);
			}
		}
		
	}
}

function listaDetalhesCompras () {
if (xmlhttp.readyState == 4) {
		
		if (xmlhttp.status == 200) {
			
			var raiz 	= xmlhttp.responseXML.getElementsByTagName('ArrayOfDiasParcelasTO')[0];
			var parc = raiz.getElementsByTagName('DiasParcelasTO');
			var qtd 	= raiz.getElementsByTagName('DiasParcelasTO').length;
			
			for (var i = 0; i < qtd; i++) {
				
				var tr = document.createElement("tr");
				var td1 = document.createElement("td");
					td1.setAttribute("className", "info_parcelas");
					td1.setAttribute("class", "info_parcelas");
					td1.appendChild(document.createTextNode("Parcela " + valorNoh(parc[i].getElementsByTagName("Num_parcela")[0])));
					tr.appendChild(td1);
					
				var td2 = document.createElement("td");
					td2.setAttribute("className", "info_parcelas_data");
					td2.setAttribute("class", "info_parcelas_data");
					td2.appendChild(document.createTextNode(valorNoh(parc[i].getElementsByTagName("DataVencimento")[0])));
					tr.appendChild(td2);
					
				var td3 = document.createElement("td");
					td3.setAttribute("className", "info_parcelas_preco");
					td3.setAttribute("class", "info_parcelas_preco");
					td3.appendChild(document.createTextNode(valorNoh(parc[i].getElementsByTagName("ValorBoleto")[0])));
					tr.appendChild(td3);
					
				var td4 = document.createElement("td");
					td4.setAttribute("className", "info_parcelas_imprimir");
					td4.setAttribute("class", "info_parcelas_imprimir");
					
					var a = document.createElement("a");
						a.setAttribute("href", siteurl + "geracao_boletos/01/boleto.asp?cod_venda=" + compraclicada + "&cpf=" + compracpf + "&num_parcela=" + valorNoh(parc[i].getElementsByTagName("Num_parcela")[0]));
						a.setAttribute("target", "_blank");
						a.appendChild(document.createTextNode("imprimir"));
						td4.appendChild(a);
					tr.appendChild(td4);
					tbody.appendChild(tr);
			}
			
			var trlinha = document.createElement("tr");
					trlinha.setAttribute("className", "tb_linha");
					trlinha.setAttribute("class", "tb_linha");
					
				var tdl1 = document.createElement("td");
					tdl1.setAttribute("className", "info_parcelas");
					tdl1.setAttribute("class", "info_parcelas");
					trlinha.appendChild(tdl1);
					
					var tdl2 = document.createElement("td");
					//tdl2.setAttribute("colspan", "2");
					trlinha.appendChild(tdl2);
					
					var tdl2b = document.createElement("td");
					//tdl2.setAttribute("colspan", "2");
					trlinha.appendChild(tdl2b);
					
					var tdl3 = document.createElement("td");
					tdl3.setAttribute("className", "info_parcelas_imprimir");
					tdl3.setAttribute("class", "info_parcelas_imprimir");
					trlinha.appendChild(tdl3);
					tbody.appendChild(trlinha);
					
					
					
				var trf = document.createElement("tr");
					trf.setAttribute("className", "negrito");
					trf.setAttribute("class", "negrito");
					
				var tf1 = document.createElement("td");
					tf1.setAttribute("className", "info_parcelas");
					tf1.setAttribute("class", "info_parcelas");
					tf1.appendChild(document.createTextNode(" "));
					trf.appendChild(tf1);
					
				var tf2 = document.createElement("td");
					tf2.setAttribute("className", "info_parcelas_data");
					tf2.setAttribute("class", "info_parcelas_data");
					tf2.appendChild(document.createTextNode("Total"));
					trf.appendChild(tf2);
					
				var tf3 = document.createElement("td");
					tf3.setAttribute("className", "info_parcelas_preco");
					tf3.setAttribute("class", "info_parcelas_preco");
					tf3.appendChild(document.createTextNode(totalcompra));
					trf.appendChild(tf3);
					
				var tf4 = document.createElement("td");
					tf4.setAttribute("className", "info_parcelas_imprimir");
					tf4.setAttribute("class", "info_parcelas_imprimir");
					
					var af = document.createElement("a");
						af.setAttribute("href", siteurl + "geracao_boletos/01/boleto.asp?cod_venda=" + compraclicada + "&cpf=" + compracpf);
						af.setAttribute("target", "_blank");
						af.appendChild(document.createTextNode("imprimir"));
						tf4.appendChild(af);
					trf.appendChild(tf4);
					tbody.appendChild(trf);
			
			$("#compramodal").fadeOut();
			$(trvis).fadeIn("fast");
		}
	}
}

function preencheContratoAgente (url) {
	
	/*if (!validaCadastroAgente(document.getElementById("form_cadastrese"))) {
		alert("Preencha primeiro os campos obrigatórios do cadastro para visualizar corretamente o contrato.");
		return false;
	}*/
	
	var paramsArray = new Array(
								"razao_social",
								"nome_fantasia",
								"cnpj",
								"cidade",
								"estado",
								"cep",
								"ramo",
								"banco",
								"agencia",
								"conta_corrente",
								"nome_favorecido",
								"nf_cnpj"
								);
	
	var form = document.createElement("form");
		form = $(form);
		form.attr("action", url);
		form.attr("method", "POST");
		form.attr("target", "_blank");
		form.css("display", "none");
		
		
		var endereco = $("#rua").val() + ", " + $("#numero").val();
		if ($("#complemento").val().length > 0) endereco += " - " + $("#complemento").val();
		endereco += " - " + $("#bairro").val();
		form.append("<input type='text' name='endereco' value='" + endereco + "' />");
		
		form.append("<input type='text' name='socio_nome' value='" + $($('input[name="socio_nome[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_rg' value='" + $($('input[name="socio_rg[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_cpf' value='" + $($('input[name="socio_cpf[]"]')[0]).val() + "' />");
		
		form.append("<input type='text' name='socio_profissao' value='" + $($('input[name="socio_profissao[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_rua' value='" + $($('input[name="socio_rua[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_numero' value='" + $($('input[name="socio_numero[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_complemento' value='" + $($('input[name="socio_complemento[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_bairro' value='" + $($('input[name="socio_bairro[]"]')[0]).val() + "' />");
		form.append("<input type='text' name='socio_cidade' value='" + $($('input[name="socio_cidade[]"]')[0]).val() + "' />");
		
		var inputEstadoCivil = ($('input[name="socio_estado_civil[]"]').length > 0)? $($('input[name="socio_estado_civil[]"]')[0]) : $($('select[name="socio_estado_civil[]"]')[0]);
		var inputEstado = ($('input[name="socio_estado[]"]').length > 0)? $($('input[name="socio_estado[]"]')[0]) : $($('select[name="socio_estado[]"]')[0]);
		
		form.append("<input type='text' name='socio_estado_civil' value='" + inputEstadoCivil.val() + "' />");
		form.append("<input type='text' name='socio_estado' value='" + inputEstado.val() + "' />");
		
		//alert (socio_nome +socio_rg +socio_cpf +socio_estado_civil +socio_profissao +socio_rua +socio_numero +socio_complemento +socio_bairro +socio_cidade +socio_estado);
			
	for (var i = 0; i < paramsArray.length; i++) {
		form.append("<input type='text' name='" + paramsArray[i] + "' value='" + $("#" + paramsArray[i]).val() + "' />");
	}
	
	$("body").append(form);
	form.submit();
}

function exibe (id) {
	if ($("#" + id).is(":hidden")) {
		$('#' + id).fadeIn();
	}
}

function esconde (id) {
	if (!$("#" + id).is(":hidden")) {
		$("#" + id).fadeOut();
	}	 
}

function exibeEsconde (id) {
	if (!$("#" + id).is(":hidden")) {
		$("#" + id).fadeOut();
	} else {
		$("#" + id).fadeIn();
	}
}

function valorNoh (noh) {
	for (var i = 0; i < noh.childNodes.length; i++) {
		
		if (noh.childNodes[i].nodeType == 3) {
			return noh.childNodes[i].nodeValue;
		}
		
	}
}

function reenviaEmailConfirmacao (a, php, cpf, cod_venda) {
	var onclick = $(a).attr("onclick");
	var ahtml = $(a).html();
	$(a).html("Aguarde...").removeAttr("onclick");
	var url = php;
	var params = "intCodVenda=" + cod_venda + "&strCPF=" + cpf;
	$.ajax({
	   type: "POST",
	   url: url,
	   data: params,
	   success: function(echo){
		   		if (echo.toLowerCase().indexOf("não enviado") > 0) {
		   			alert (echo);
					$(a).html(ahtml).attr("onclick", onclick);
				} else {
					$(a).after("<p>" + echo + "</p>");
					$(a).remove();
				}
			  }
	 });
}
//................................ funcoes do twitter

function twitterCallback2(twitters) {
  var ul = document.createElement("ul");
  
  for (var i=0; i< twitters.length; i++){
	  
    var username = twitters[i].user.screen_name;
	var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
											  return url;
											}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
											  return  reply.charAt(0)+reply.substring(1);
											});
	
	if (i % 2 == 0) {
		var classe = "tweet cor_par";
	} else {
		var classe = "tweet cor_impar";
	}
	
	var li = document.createElement("li");
		li.setAttribute("class", classe);
		li.setAttribute("className", classe);
	var span = document.createElement("span");
		span.setAttribute("class", "tweet_texto");
		span.setAttribute("className", "tweet_texto");
		span.appendChild(document.createTextNode(status));
	var a = document.createElement("a");
		a.setAttribute("class", "tweet_link");
		a.setAttribute("className", "tweet_link");
		a.setAttribute("target", "_blank");
		a.setAttribute("href","http://twitter.com/"+username+"/statuses/"+twitters[i].id);
		a.appendChild(document.createTextNode(relative_time(twitters[i].created_at)));
		
	li.appendChild(span);
	li.appendChild(a);
	
	ul.appendChild(li);
  }
  
  document.getElementById('twitter').appendChild(ul);
  
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'há menos de um minuto atrás';
  } else if(delta < 120) {
    return 'há aproximadamente um minuto';
  } else if(delta < (60*60)) {
    return 'há ' + (parseInt(delta / 60)).toString() + ' minutos atrás';
  } else if(delta < (120*60)) {
    return 'há aproximadamente uma hora';
  } else if(delta < (24*60*60)) {
    return 'há aproximadamente ' + (parseInt(delta / 3600)).toString() + ' horas atrás';
  } else if(delta < (48*60*60)) {
    return 'há um dia';
  } else {
    return 'há ' + (parseInt(delta / 86400)).toString() + ' dias atrás';
  }
  
}
