var xmlHttp;

var idPais;
var idPara;

var selectEstado;
var conteinerEstado;
var estadoSelected;
var cidadeSelected;
var idBloqueado;
var idFavorito;
var origemFavorito;
var mensagem;
var resultado;
var provedor;

/**
* Variável que controla a mensagem de apelido invalido
*/
var existeSpanApelidoInvalido = false;

/**
* Variável que controla a mensagem de apelido existente
*/
var existeSpanApelidoExistente = false;

/**
* Variável que controla a mensagem de email existente
*/
var existeSpanEmailExistente = false;

/**
* Variável que controla a mensagem de email existente
*/
var existeSpanSenhaInvalida = false;

function addOption(obj, value, label){
	
	var option = document.createElement('option');
	
	option.setAttribute('value', value);
	option.setAttribute('label', label);
	
	var textOption = document.createTextNode(label);
	
	option.appendChild(textOption);
	obj.appendChild(option);
	
}

function clear(obj){
	
	if ( obj != null ){
	
		if (obj.hasChildNodes()){
			
			var nos = obj.childNodes;
			
			while (nos.length > 0){
				
				var no = nos[nos.length - 1];
				obj.removeChild(no);
			
			}
		}
	
	}
	
}

/*
*Função que envia uma mensagem expressa ao usuario
*/
function enviaMensagemExpressa(obj, para){
	
	idPara = para;
	
	obj.onclick = function desabilitar(){		
		return false;
	}
	
	obj.title = "Aguarde até que a mensagem seja enviada!";
	
	var url = "./enviarMensagem.php?id_para="+para+"&express=1";				
	
	xmlHttpeme=GetXmlHttpObject(rotinaEnviaMensagemExpressa);
	xmlHttpeme.open("GET", url , true);
	xmlHttpeme.send(null);		

	obj.onclick = function habilitar(){		
		return true;
	}	
	
	obj.title = "Enviar Mensagem Expressa";
	
}


/*
*Acao da funcao enviaMensagemExpressa
*/
function rotinaEnviaMensagemExpressa(){
	
	if ( ( xmlHttpeme.readyState == 4 ) || ( xmlHttpeme.readyState == "complete" ) ){ 
		var response = xmlHttpeme.responseText;
		if ( response == 1 ){
			alert('Mensagem enviada com sucesso!');
		}else if ( response == 2 ){
			alert('Para enviar uma mensagem expressa você precisa estar cadastrado e logado!');
		}else if ( response == 3 ){
			alert('Este usuário optou por bloquea-ló.\nSendo assim você não pode enviar mensagens para ele(a)!');
		}else if ( response == 4 ){
			alert('Você optou por bloquear este usuário.\nSendo assim você também não pode enviar mensagens para ele(a)!');
		}else if ( response == 5 ){
			alert('Este usuário escolheu que somente pessoas do mesmo estado que ele podem ter acesso ao seu perfil!');
		}else if ( response == 6 ){
			alert('Este usuário escolheu que somente pessoas que tenham a mesma preferência sexual que ele podem ter acesso ao seu perfil!');
		}else if ( response == 7 ){
			alert('Este usuário escolheu que somente pessoas do sexo oposto ao dele podem ter acesso ao seu perfil!');
		}else if ( response == 8 ){
			alert('Este usuário foi descadastrado do nosso sistema!');
		}else if ( response == 9 ){
			alert('Para mandar uma mensagem expressa você primeiro tem que ativa-lá!');
			window.location = "./enviarMensagem.php?id_para="+idPara+"&express=1&edit=1";
		}else{
			alert('Ocorreu um erro ao enviar a mensagem, tente novamente!');
		}		
		
	}		
	
}

/*
*Função que envia uma sugestao feita pelo usuário
*/
function enviaSugestao(obj){					
	
	var textoSugestao = document.getElementById('sugestao').value;
	
	obj.onclick = function desabilitar(){		
		return false;
	}
	
	obj.title = "Aguarde até que a sugestão seja enviada!";
	
	var url = "./submitSugestao.php?sugestao="+textoSugestao;				
	
	xmlHttpes=GetXmlHttpObject(rotinaEnviaSugestao);
	xmlHttpes.open("GET", url , true);
	xmlHttpes.send(null);		

	obj.onclick = function habilitar(){		
		return true;
	}	
	
	obj.title = "Enviar Sugestão";
	
}


/*
*Acao da funcao enviaSugestao
*/
function rotinaEnviaSugestao(){
	
	if ( ( xmlHttpes.readyState == 4 ) || ( xmlHttpes.readyState == "complete" ) ){ 
		var response = xmlHttpes.responseText;
		if ( response == 1 ){
			alert('Sugestão enviada com sucesso!');
			
			document.getElementById('sugestao').value = "";
		}else{
			alert('Ocorreu um erro ao enviar a sugestão, tente novamente!');
		}		
		
	}		
	
}


/*
* Função que envia uma sugestao feita pelo usuário
*/
function bloquearUsuario(bloqueado,origem){
	
	idBloqueado = bloqueado;
	
	var url = "./bloquearUsuario.php?id_usu="+idBloqueado;				
	
	if (origem == "busca"){
		xmlHttpbu = GetXmlHttpObject(rotinaBloquearUsuarioBusca);
	}else if (origem == "perfil"){
		xmlHttpbu = GetXmlHttpObject(rotinaBloquearUsuarioPerfil);
	}else if (origem == "mensagem"){
		xmlHttpbu = GetXmlHttpObject(rotinaBloquearUsuarioMensagem);
	}
	
	xmlHttpbu.open("GET", url , true);
	xmlHttpbu.send(null);
	
}

/*
* Função que denuncia um spam feito pelo usuário
*/
function denunciarSpam( mensagemSpam ){
	
	idSpam = mensagemSpam;
	
	var url = "./denunciarSpam.php?idSpam="+idSpam;				

	xmlHttpbu = GetXmlHttpObject( rotinaDenunciarSpamMensagem );
	
	xmlHttpbu.open("GET", url , true);
	xmlHttpbu.send(null);
	
}

/*
*Acao da funcao denunciarSpam
*/
function rotinaDenunciarSpamMensagem(){
	
	if ( ( xmlHttpbu.readyState == 4 ) || ( xmlHttpbu.readyState == "complete" ) ){
		
		var response = xmlHttpbu.responseText;
		
		if ( response == 1 ){
			
			alert('Spam denunciado com sucesso!');
			
			window.location = "mensagensRecebidas.php";
				
		} else if ( response == 3 ) {
			
			alert('Para bloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		} else if ( response == 2 ) {
			
			alert('Ocorreu um erro ao denunciar este spam, tente novamente!');
			
		} else {
			
			alert('Ocorreu um erro ao denunciar este spam, tente novamente!');
			
		}
		
	}	
	
}


/*
*Acao da funcao BloquearUsuario
*/
function rotinaBloquearUsuarioBusca(){
	
	if ( ( xmlHttpbu.readyState == 4 ) || ( xmlHttpbu.readyState == "complete" ) ){
		
		var response = xmlHttpbu.responseText;
		
		if ( response == 1 ){
			
			alert('Usuário bloqueado com sucesso!');
						
			var img = document.getElementById("img" + idBloqueado);
			img.setAttribute("src","./img/desbloquearUsuario.gif");
			img.setAttribute("alt","Desbloquear Usuário");
			img.setAttribute("id","img" + idBloqueado);
			
			if ( display == "lista" ){
				
				var span = img.parentNode.parentNode;
				var link = document.createElement("a");
				link.setAttribute("href","Javascript:desbloquearUsuario(" +idBloqueado+ ",'busca');");
				link.setAttribute("onmouseover","showTip('desbloquearUsuario'," +idBloqueado+ ");");						
				link.setAttribute("title", "Desbloquear Usuário");
				link.appendChild(img);			
				span.removeChild(span.lastChild);
				span.appendChild(link);
				
				var tip = document.getElementById("bloquearUsuario" + idBloqueado);														
				var firstChildTip = tip.firstChild;						
				
				tip.removeChild(firstChildTip);
				
				var newLink = document.createElement("a");
				newLink.setAttribute("href","Javascript:desbloquearUsuario(" +idBloqueado+ ",'busca');");
				newLink.setAttribute("title","Desbloquear Usuário");
				
				var textLink = document.createTextNode("Desbloquear Usuário");
				newLink.appendChild(textLink);
				
				tip.appendChild(newLink);
				
				tip.setAttribute("id","desbloquearUsuario" + idBloqueado);
				
			}else{
				
				var link = document.getElementById("aBloquearUsuario" + idBloqueado);
				link.setAttribute("href", "javascript:desbloquearUsuario(" +idBloqueado+ ",'busca');");
				link.setAttribute("title","Desbloquear Usuário");
				link.setAttribute("id","aDesbloquearUsuario" + idBloqueado);
				
			}
			
		}else if ( response == 2 ){
			
			alert('Este usuário já está bloqueado por você!');
			
		}else if ( response == 3 ){
			
			alert('Para bloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else if ( response == 4 ){
			
			alert("Este usuário foi descadastrado do nosso sistema!");
			
		}else{
			
			alert('Ocorreu um erro ao bloquear este usuário, tente novamente!');
			
		}		
		
	}		
	
}

/*
*Acao da funcao BloquearUsuario
*/
function rotinaBloquearUsuarioPerfil(){
	
	if ( ( xmlHttpbu.readyState == 4 ) || ( xmlHttpbu.readyState == "complete" ) ){
		
		var response = xmlHttpbu.responseText;
		
		if ( response == 1 ){
			
			alert('Usuário bloqueado com sucesso!');
				
			//muda a imagem		
			var imgs = document.getElementsByTagName("img");
			
			for (var i = 0; i < imgs.length; i++){
				
				if ( imgs[i].getAttribute("alt") == "img" + idBloqueado ){
					
					imgs[i].setAttribute("src","./img/desbloquearUsuario.gif");										
					
				}
				
			}			
			
			//muda o link
			var link = document.getElementsByTagName("a");
			
			for (var i = 0; i < link.length; i++){
				
				if ( link[i].getAttribute("name") == "link" + idBloqueado){
					
					link[i].setAttribute("href","Javascript:desbloquearUsuario(" +idBloqueado+ ",'perfil');");
					link[i].setAttribute("title","Desbloquear Usuário");
					var textLink = link[i].firstChild;
					link[i].removeChild(textLink);
					textLink = document.createTextNode("Desbloquear");
					link[i].appendChild(textLink);						
					
				}
				
			}			
			
		}else if ( response == 2 ){
			
			alert('Este usuário já está bloqueado por você!');
			
		}else if ( response == 3 ){
			
			alert('Para bloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else if ( response == 4 ){
			
			alert("Este usuário foi descadastrado do nosso sistema!");
			
		}else{
			
			alert('Ocorreu um erro ao bloquear este usuário, tente novamente!');
			
		}		
		
	}		
	
}


/*
*Acao da funcao BloquearUsuario
*/
function rotinaBloquearUsuarioMensagem(){
	
	if ( ( xmlHttpbu.readyState == 4 ) || ( xmlHttpbu.readyState == "complete" ) ){
		
		var response = xmlHttpbu.responseText;
		
		if ( response == 1 ){
			
			alert('Usuário bloqueado com sucesso!');
				
			//muda a imagem
			var img = document.getElementById("imgBloquear" + idBloqueado);
			
			img.setAttribute("src","./img/desbloquearUsuario.gif");		
			img.setAttribute("id","imgDesbloquear" + idBloqueado);		
			img.setAttribute("alt","Desbloquear");		
			
			//muda o link
			var link = document.getElementById("linkBloquear" + idBloqueado);
								
			link.setAttribute("href","javascript:desbloquearUsuario(" +idBloqueado+ ",'mensagem');");
			link.setAttribute("title","Desbloquear Usuário");
			link.setAttribute("id","linkDesbloquear" + idBloqueado);
			
			var textLink = link.firstChild;
			link.removeChild(textLink);
			textLink = document.createTextNode("Desbloquear");
			link.appendChild(textLink);									
			
		}else if ( response == 2 ){
			
			alert('Este usuário já está bloqueado por você!');
			
		}else if ( response == 3 ){
			
			alert('Para bloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else if ( response == 4 ){
			
			alert("Este usuário foi descadastrado do nosso sistema!");
			
		}else{
			
			alert('Ocorreu um erro ao bloquear este usuário, tente novamente!');
			
		}		
		
	}		
	
}


/*
* Função que envia uma sugestao feita pelo usuário
*/
function desbloquearUsuario(bloqueado,origem){
	
	idBloqueado = bloqueado;
	
	var url = "./desbloquearUsuario.php?id_usu="+idBloqueado;				
	
	if (origem == "busca"){
		xmlHttpdu = GetXmlHttpObject(rotinaDesbloquearUsuarioBusca);
	}else if (origem == "perfil"){
		xmlHttpdu = GetXmlHttpObject(rotinaDesbloquearUsuarioPerfil);
	}else if (origem == "mensagem"){
		xmlHttpdu = GetXmlHttpObject(rotinaDesbloquearUsuarioMensagem);
	}
	xmlHttpdu.open("GET", url , true);
	xmlHttpdu.send(null);		
	
}


/*
*Acao da funcao DesbloquearUsuario
*/
function rotinaDesbloquearUsuarioBusca(){
	
	if ( ( xmlHttpdu.readyState == 4 ) || ( xmlHttpdu.readyState == "complete" ) ){
		
		var response = xmlHttpdu.responseText;
		
		if ( response == 1 ){
			
			alert('Usuário desbloqueado com sucesso!');

			//pega e trata a imagem		
			var img = document.getElementById("img" + idBloqueado);
			img.setAttribute("src","./img/bloquearUsuario.gif");
			img.setAttribute("alt","Bloquear Usuário");
			img.setAttribute("id","img" + idBloqueado);
			
			if ( display == "lista" ){
				
				//pega o span que contem o link da imagem
				var span = img.parentNode.parentNode;
				
				//cria um novo link de imagem e altera
				var link = document.createElement("a");
				link.setAttribute("href","Javascript:bloquearUsuario(" +idBloqueado+ ",'busca');");
				link.setAttribute("onmouseover","showTip('bloquearUsuario'," +idBloqueado+ ");");						
				link.setAttribute("title", "Bloquear Usuário");
				link.appendChild(img);			
				span.removeChild(span.lastChild);
				span.appendChild(link);
				
				//pega a dica remove o link escrito atual
				var tip = document.getElementById("desbloquearUsuario" + idBloqueado);
				var firstChildTip = tip.firstChild;
				tip.removeChild(firstChildTip);
				
				//cria um novo link
				var newLink = document.createElement("a");
				newLink.setAttribute("href","Javascript:bloquearUsuario(" +idBloqueado+ ",'busca');");
				newLink.setAttribute("title","bloquear Usuário");
				var textLink = document.createTextNode("Bloquear Usuário");
				newLink.appendChild(textLink);
				tip.appendChild(newLink);
				
				//muda o id da dica 
				tip.setAttribute("id","bloquearUsuario" + idBloqueado);
				
			}else{
				
				var link = document.getElementById("aDesbloquearUsuario" + idBloqueado);
				link.setAttribute("href", "javascript:bloquearUsuario(" +idBloqueado+ ",'busca');");
				link.setAttribute("title","Bloquear Usuário");
				link.setAttribute("id","aBloquearUsuario" + idBloqueado);
				
			}
			
		}else if ( response == 2 ){
			
			alert('Para desbloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else{
			
			alert('Ocorreu um erro ao desbloquear este usuário, tente novamente!');
			
		}		
		
	}		
	
}

/*
*Acao da funcao DesbloquearUsuario
*/
function rotinaDesbloquearUsuarioPerfil(){
	
	if ( ( xmlHttpdu.readyState == 4 ) || ( xmlHttpdu.readyState == "complete" ) ){
		
		var response = xmlHttpdu.responseText;
		
		if ( response == 1 ){
			
			alert('Usuário desbloqueado com sucesso!');
				
			//muda a imagem		
			var imgs = document.getElementsByTagName("img");
			
			for (var i = 0; i < imgs.length; i++){
				
				if ( imgs[i].getAttribute("alt") == "img" + idBloqueado ){
					
					imgs[i].setAttribute("src","./img/bloquearUsuario.gif");										
					
				}
				
			}			
			
			//muda o link
			var link = document.getElementsByTagName("a");
			
			for (var i = 0; i < link.length; i++){
				
				if ( link[i].getAttribute("name") == "link" + idBloqueado){
					
					link[i].setAttribute("href","Javascript:bloquearUsuario(" +idBloqueado+ ",'perfil');");
					link[i].setAttribute("title","Bloquear Usuário");
					var textLink = link[i].firstChild;
					link[i].removeChild(textLink);
					textLink = document.createTextNode("Bloquear");
					link[i].appendChild(textLink);						
					
				}
				
			}
			
		}else if ( response == 2 ){
			
			alert('Para desbloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else{
			
			alert('Ocorreu um erro ao desbloquear este usuário, tente novamente!');
			
		}		
		
	}		
	
}


/*
*Acao da funcao DesbloquearUsuario
*/
function rotinaDesbloquearUsuarioMensagem(){
	
	if ( ( xmlHttpdu.readyState == 4 ) || ( xmlHttpdu.readyState == "complete" ) ){
		
		var response = xmlHttpdu.responseText;
		
		if ( response == 1 ){
			
			alert('Usuário desbloqueado com sucesso!');
				
			//muda a imagem		
			var img = document.getElementById("imgDesbloquear" + idBloqueado);
			
			img.setAttribute("src","./img/bloquearUsuario.gif");
			img.setAttribute("id","imgBloquear" + idBloqueado);
			img.setAttribute("alt","Bloquear");
					
			//muda o link
			var link = document.getElementById("linkDesbloquear" + idBloqueado);
			
			link.setAttribute("href","javascript:bloquearUsuario(" +idBloqueado+ ",'mensagem');");
			link.setAttribute("title","Bloquear Usuário");
			link.setAttribute("id","linkBloquear" + idBloqueado);
			
			var textLink = link.firstChild;
			link.removeChild(textLink);
			textLink = document.createTextNode("Bloquear");
			link.appendChild(textLink);						
			
		}else if ( response == 2 ){
			
			alert('Para desbloquear este usuário você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else{
			
			alert('Ocorreu um erro ao desbloquear este usuário, tente novamente!');
			
		}		
		
	}		
	
}


/*
*Função que adiciona um usuário a lista de favoritos de outro usuário
*/
function adicionarFavorito(favorito, origem){
	
	idFavorito = favorito;
	origemFavorito = origem;
		
	var url = "./adicionarFavorito.php?id_usu=" + idFavorito;
	
	xmlHttpAF=GetXmlHttpObject(rotinaAdicionarFavorito);
	xmlHttpAF.open("GET", url , true);
	xmlHttpAF.send(null);		
	
}


/*
*Acao da funcao adicionarFavorito
*/
function rotinaAdicionarFavorito(){
	
	if ( ( xmlHttpAF.readyState == 4 ) || ( xmlHttpAF.readyState == "complete" ) ){
		
		var response = xmlHttpAF.responseText;
		
		if ( response == 1 ){
			
			alert('Para adicionar este usuário aos seus favoritos você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else if ( response == 2 ){
			
			alert('Este usuário optou por bloquea-ló.\nSendo assim você não pode adicioná-lo aos seus favoritos!');
			
		}else if ( response == 3 ){
			
			alert('Você optou por bloquear este usuário.\nSendo assim você também não pode adicioná-lo aos seus favoritos!');
			
		}else if ( response == 4 ){
			
			alert('Este usuário escolheu que somente pessoas do mesmo estado que ele podem ter acesso ao seu perfil!');
			
		}else if ( response == 5 ){
			
			alert('Este usuário escolheu que somente pessoas que tenham a mesma preferência sexual que ele podem ter acesso ao seu perfil!');
			
		}else if ( response == 6 ){
			
			alert('Este usuário escolheu que somente pessoas do sexo oposto ao dele podem ter acesso ao seu perfil!');
			
		}else if ( response == 7 ){
			
			alert('Usuário adicionado com sucesso!');
			
			if ( origemFavorito == 'minhaArea' ){
				
				var img = document.getElementById("imgFavorito" + idFavorito);
				
				img.setAttribute("src","./img/excluirFavorito.gif");
				img.setAttribute("id","imgFavorito" + idFavorito);
				
				var link = document.getElementById("linkFavorito" + idFavorito);
				
				link.setAttribute("href","javascript:excluirFavorito(" + idFavorito + ",'minhaArea');");
				link.setAttribute("title","Excluir Favorito");
				link.setAttribute("onclick","return confirm('Excluir este usuário da sua lista de favoritos?')");
				link.setAttribute("id","linkFavorito" + idFavorito);
				
				link.appendChild(img);
						
			}else if ( origemFavorito == 'busca' ){
				
				var img = document.getElementById("imgFavorito" + idFavorito);
				
				img.setAttribute("src","./img/excluirFavorito.gif");
				img.setAttribute("id","imgFavorito" + idFavorito);
				
				var link = document.getElementById("linkFavorito" + idFavorito);
						
				link.setAttribute("href","javascript:excluirFavorito(" + idFavorito + ",'busca');");
				link.setAttribute("title","Excluir Favorito");
				link.setAttribute("onclick","return confirm('Excluir este usuário da sua lista de favoritos?')");
				link.setAttribute("id","linkFavorito" + idFavorito);
				
				if ( display == "lista" ){
					
					link.setAttribute("onmouseover","showTip('excluirFavorito'," + idFavorito + ");");
					
					//pega o span que contem o link da imagem
					var span = document.getElementById("adicionarFavorito" + idFavorito);
					
					span.setAttribute("id","excluirFavorito" + idFavorito);
							
					//link que está dentro do span
					var aSpan = span.firstChild;
					
					//removo o link antigo
					span.removeChild(aSpan);
					
					//crio o novo link
					aSpan = document.createElement("a");
					aSpan.setAttribute("href","javascript:excluirFavorito(" + idFavorito + ",'busca');");
					aSpan.setAttribute("onclick","return confirm('Excluir este usuário da sua lista de favoritos?')");
							
					//texto do novo link
					var textoASpan = document.createTextNode("Excluir dos Meus Favoritos");
					
					//adiciono o texto no link
					aSpan.appendChild(textoASpan);
					
					//adiciono o link no span
					span.appendChild(aSpan);
					
				}
						
				link.appendChild(img);
						
			}else if ( origemFavorito == 'perfil' ){
				
				var imgs = document.getElementsByTagName("img");
				
				for (var i = 0; i < imgs.length; i++){
							
					if ( imgs[i].getAttribute("name") == "imgFavorito" + idFavorito){
						
						imgs[i].setAttribute("src","./img/excluirFavorito.gif");
						imgs[i].setAttribute("name","imgFavorito" + idFavorito);
						
					}
					
				}
											
				var links = document.getElementsByTagName("a");
						
				for (var i = 0; i < links.length; i++){
							
					if ( links[i].getAttribute("name") == "linkFavorito" + idFavorito){
						
						var elementoPaiLink = links[i].parentNode;
						
						elementoPaiLink.removeChild(links[i]);
						
						var link = document.createElement("a");
								
						link.setAttribute("href","javascript:excluirFavorito(" + idFavorito + ",'perfil');");
						link.setAttribute("title","Excluir Favorito");
						link.setAttribute("onclick","return confirm('Excluir este usuário da sua lista de favoritos?')");
						link.setAttribute("name","linkFavorito" + idFavorito);
						
						//texto do link
						var textoLink = document.createTextNode("Excluir Favorito");
						
						link.appendChild(textoLink);
						
						elementoPaiLink.appendChild(link);
						
					}
					
				}
				
			}
			
		}else if ( response == 8 ){
			
			alert('Este usuário já consta na sua lista de favoritos!');
			
		}else if ( response == 9 ){
			
			alert("Este usuário foi descadastrado do nosso sistema!");
			
		}else{
			
			alert('Ocorreu um erro ao adicionar o usuário aos seus favoritos, tente novamente!');
			
		}
		
	}		
	
}

/*
*Função que adiciona um usuário a lista de favoritos de outro usuário
*/
function excluirFavorito(favorito, origem){
	
	idFavorito = favorito;
	origemFavorito = origem;
		
	var url = "./excluirFavorito.php?id_usu=" + idFavorito;
	
	xmlHttpEF=GetXmlHttpObject(rotinaExcluirFavorito);
	xmlHttpEF.open("GET", url , true);
	xmlHttpEF.send(null);		
	
}


/*
*Acao da funcao adicionarFavorito
*/
function rotinaExcluirFavorito(){
	
	if ( ( xmlHttpEF.readyState == 4 ) || ( xmlHttpEF.readyState == "complete" ) ){
		
		var response = xmlHttpEF.responseText;
		
		if ( response == 1 ){
			
			alert('Para excluir este usuário dos seus favoritos você precisa estar cadastrado e logado!');
			
			window.location = "cadastroPrincipal.php?naoCadastrado=1";
			
		}else if ( response == 2 ){
			
			alert('Usuário excluido com sucesso!');
								
			if ( origemFavorito == 'minhaArea' ){
				
				var img = document.getElementById("imgFavorito" + idFavorito);
				
				img.setAttribute("src","./img/favoritos.gif");
				img.setAttribute("id","imgFavorito" + idFavorito);
				
				var link = document.getElementById("linkFavorito" + idFavorito);
				
				var paiLink = link.parentNode;
				
				paiLink.removeChild(link);
				
				link = document.createElement("a");				
				link.setAttribute("href","javascript:adicionarFavorito(" + idFavorito + ",'minhaArea');");
				link.setAttribute("title","Adicionar Favorito");
				link.setAttribute("id","linkFavorito" + idFavorito);
				
				link.appendChild(img);
				
				paiLink.appendChild(link);
						
			}else if ( origemFavorito == 'busca' ){
				
				var img = document.getElementById("imgFavorito" + idFavorito);
				
				var link = document.getElementById("linkFavorito" + idFavorito);
				
				img.setAttribute("id","imgFavorito" + idFavorito);
				
				if ( display == "lista" ){
					
					img.setAttribute("src","./img/adicionarFavorito.gif");
					
					link.setAttribute("onmouseover","showTip('adicionarFavorito'," + idFavorito + ");");
					
					//pega o span que contem o link da imagem
					var span = document.getElementById("excluirFavorito" + idFavorito);
					
					span.setAttribute("id","adicionarFavorito" + idFavorito);
							
					//link que está dentro do span
					var aSpan = span.firstChild;
					
					//removo o link antigo
					span.removeChild(aSpan);
					
					//crio o novo link
					aSpan = document.createElement("a");
					aSpan.setAttribute("href","javascript:adicionarFavorito(" + idFavorito + ",'busca');");
							
					//texto do novo link
					var textoASpan = document.createTextNode("Adicionar aos Meus Favoritos");
					
					//adiciono o texto no link
					aSpan.appendChild(textoASpan);
					
					//adiciono o link no span
					span.appendChild(aSpan);
					
				}else{
					
					img.setAttribute("src","./img/favoritos.gif");
					
				}
				
				link.appendChild(img);
						
				link.setAttribute("href","javascript:adicionarFavorito(" + idFavorito + ",'busca');");
				link.setAttribute("title","Adicionar Favorito");
				link.setAttribute("id","linkFavorito" + idFavorito);
						
			}else if ( origemFavorito == 'perfil' ){
				
				var imgs = document.getElementsByTagName("img");
				
				for (var i = 0; i < imgs.length; i++){
							
					if ( imgs[i].getAttribute("name") == "imgFavorito" + idFavorito){
						
						imgs[i].setAttribute("src","./img/aFavorito.gif");
						imgs[i].setAttribute("name","imgFavorito" + idFavorito);
						
					}
					
				}
				
				var links = document.getElementsByTagName("a");
						
				for (var i = 0; i < links.length; i++){
							
					if ( links[i].getAttribute("name") == "linkFavorito" + idFavorito){
						
						var elementoPaiLink = links[i].parentNode;
						
						elementoPaiLink.removeChild(links[i]);
						
						var link = document.createElement("a");
								
						link.setAttribute("href","javascript:adicionarFavorito(" + idFavorito + ",'perfil');");
						link.setAttribute("title","Adicionar Favorito");
						link.setAttribute("name","linkFavorito" + idFavorito);
						
						//texto do link
						var textoLink = document.createTextNode("Adicionar Favorito");
						
						link.appendChild(textoLink);
						
						elementoPaiLink.appendChild(link);
						
					}
					
				}
				
			}else if ( response == 3 ) {
				
				alert('Este usuário não consta na sua lista de favoritos!');
				
			}else{
				
				alert('Ocorreu um erro ao excluir o usuário dos seus favoritos, tente novamente!');
			
			}
			
		}
		
	}
	
}

/*
*Função que registra a impressao de um anuncio
*/
function registraImpressaoAnuncio(idAnuncio,idComissao){					
	
	var url = "./acaoRegistraImpressaoAnuncio.php?idAnuncio="+idAnuncio+"&idComissao="+idComissao;				
	
	xmlHttpr=GetXmlHttpObject(function (){});
	xmlHttpr.open("GET", url , true);
	xmlHttpr.send(null);					
	
}

/**
* Verifica se alguém chamou o usuário para um papo online
*/
function processaRequisicoes(){		
	
	var url = "./processaRequisicoes.php";
	
	xmlHttpx=GetXmlHttpObject(fProcessaRequisicoes);
	xmlHttpx.open("GET", url , true);
	xmlHttpx.send(null);		
	
	//repete a executa desta função a cada 10 segundos
	timer = setTimeout("processaRequisicoes()",20000);	
	
}


/**
* Ação da função chekOpenedChat
*/
function fProcessaRequisicoes(){
	
	if ( ( xmlHttpx.readyState == 4 ) || ( xmlHttpx.readyState == "complete" ) ){ 
		var response = xmlHttpx.responseText;
		
		if ( response > 0 ){
			
			win = openWindow(550,225,300,300,'./confirmChat.php?idPapoOnline='+response);
			win.focus();
						
		}
		
	}	
	
}


function carregaEstados(pais, selected){												
	
		estadoSelected = selected;
		idPais = pais;										
		
		var estado = document.getElementById('estado');

		//se não for encontrado o select#estado
		if ( estado == null ){
			
			//remove o texto
			conteinerEstado.removeChild(conteinerEstado.lastChild);
			
			conteinerEstado.appendChild(selectEstado);			
			estado = selectEstado;			
		}
			
		clear(estado);							
		
		var cidade = document.getElementById('cidade');			
		
		// limpa a cidade			
		clear(cidade);					
		var valueCidade = 0;
		var labelCidade = "Escolha primeiro o estado";		
		addOption(cidade, valueCidade, labelCidade);			
		
		if ( pais > 0 ){
								
			var valueEstado = 0;
			var labelEstado = "Espere carregar por alguns segundos";		
			addOption(estado, valueEstado, labelEstado);	
			
		
			var url= "./ajaxEstados.php?&pais=" + pais;		
			
			xmlHttpCE = GetXmlHttpObject(estadosAjax);
			xmlHttpCE.open("GET", url , true);
			xmlHttpCE.send(null);
		
		}else{			
			
			//limpa o estado							
			var valueEstado = 0;
			var labelEstado = "Escolha primeiro o país";		
			addOption(estado, valueEstado, labelEstado);										
			
		}
		
		
}

function estadosAjax(){
	
	if (xmlHttpCE.readyState == 4 || xmlHttpCE.readyState == "complete"){								
		
		var estado = document.getElementById('estado');		
		
		var xmlDoc = xmlHttpCE.responseXML;
		
		var estados = xmlDoc.getElementsByTagName('estado');
		
		if ( estados.length > 0 ){
			
			clear(estado);		
			var valueEstado = 0;
			var labelEstado = "Escolha";		
			addOption(estado, valueEstado, labelEstado);			
		
			for (var i = 0; i < estados.length; i++){
				
				var idEstado = estados[i].getElementsByTagName('idEstado')[0].firstChild.nodeValue;
				var nome = estados[i].getElementsByTagName('nome')[0].firstChild.nodeValue;
				
				addOption(estado, idEstado, nome);
				
			}										
				
			for (var i = 0; i < estado.options.length; i++){								
					
				if ( estadoSelected == estado.options[i].value ){					
					estado.options[i].selected = true;					
				}
					
			}
			
		
			
		}else{						
			
			selectEstado = estado;
			
			conteinerEstado = estado.parentNode;
			conteinerEstado.removeChild(estado);
			
			var textNode = document.createTextNode("Este país não possui estados.");
			conteinerEstado.appendChild(textNode);
			conteinerEstado.style.fontSize = "10px";												
			
			carregaCidades(idPais,'',cidadeSelected);						
			
		}
		
	}
	
}


function carregaCidades(pais,estado,selected){				
	
	cidadeSelected = selected;		
	
	var cidade = document.getElementById('cidade');		
	
	if ( (estado == 0) && (document.getElementById('estado') != null) ){
		
		clear(cidade);		
		var valueCidade = 0;
		var labelCidade = "Escolha primeiro o estado";		
		addOption(document.getElementById('cidade'), valueCidade, labelCidade);		
		
	}else if ((pais > 0) || (estado > 0)){
	
		clear(cidade);
		
		var valueCidade = 0;
		var labelCidade = "Espere carregar por alguns segundos";		
		addOption(document.getElementById('cidade'), valueCidade, labelCidade);
			
		var url= "./ajaxCidades.php?&pais=" + pais + "&estado=" + estado;															
		
		xmlHttpCC = GetXmlHttpObject(cidadesAjax);
		xmlHttpCC.open("GET", url , true);
		xmlHttpCC.send(null);		
		
	}else if ( estado == 0 ){
		
		clear(cidade);
				
		var valueCidade = 0;
		var labelCidade = "Escolha primeiro o estado";
		
		addOption(cidade, valueCidade, labelCidade);		
		
	}
	
	
}

function cidadesAjax(){
	
	if (xmlHttpCC.readyState == 4 || xmlHttpCC.readyState == "complete"){
		
		var cidade = document.getElementById('cidade');
		
		clear(cidade);
		
		var valueCidade = 0;
		var labelCidade = "Selecione uma cidade";		
		addOption(cidade, valueCidade, labelCidade);
		
		var xmlDoc = xmlHttpCC.responseXML;
		
		var cidades = xmlDoc.getElementsByTagName('cidade');				
		
		for (var i = 0; i < cidades.length; i++){
			
			var idCidade = cidades[i].getElementsByTagName('idCidade')[0].firstChild.nodeValue;
			var nome = cidades[i].getElementsByTagName('nome')[0].firstChild.nodeValue;
				
			addOption(cidade, idCidade, nome);
			
		}				
		
		for (var i = 0; i < cidade.options.length; i++){								
				
			if ( cidadeSelected == cidade.options[i].value ){					
				cidade.options[i].selected = true;					
			}
				
		}		
		
	}
	
}

function buscaAmigosMSN(senhaMSN, usuarioMSN){
	
	if ( (senhaMSN != '') && (usuarioMSN != '') ){
		
		clear(document.getElementById('amigosMSN'));
		clear(document.getElementById('amigosConfirmadosMSN'));
		
		var valueAmigos = 0;
		var labelAmigos = "Espere carregar...";		
		addOption(document.getElementById('amigosMSN'), valueAmigos, labelAmigos);
		
		var url= "./buscaAmigosMSN.php?usuarioMSN=" + usuarioMSN + "&senhaMSN=" + senhaMSN;															
		
		xmlHttpBAMSN = GetXmlHttpObject(buscaAmigosMSNAjax);
		xmlHttpBAMSN.open("GET", url , true);
		xmlHttpBAMSN.send(null);		
		
	}else{
		
		alert('Primeiro digite seu usuário e senha do MSN e clique no botão Listar Seus Amigos do MSN!');
		
	}
	
}

function buscaAmigosMSNAjax(){
	
	if (xmlHttpBAMSN.readyState == 4 || xmlHttpBAMSN.readyState == "complete"){
		
		var amigos = document.getElementById('amigosMSN');
		
		clear(amigos);
		
		var xmlDoc = xmlHttpBAMSN.responseXML;
				
		var contatos = xmlDoc.getElementsByTagName('contato');
				
		for (var i = 0; i < contatos.length; i++){
			
			var emailContato = contatos[i].firstChild.nodeValue;
							
			addOption(amigos, emailContato, emailContato);
			
		}
		
	}
	
}

function trocarAmigosLado(amigos, ondeAdicionar){
	
	var emailsAmigos = pegaSelectMultipleSelecionado(amigos);
	emailsAmigos = emailsAmigos.split(",");
	
	var selectAmigos = document.getElementById(amigos);
	
	var selecionado = 0;
	
	if ( emailsAmigos.length > 0 ){
		
		for (var i = 0; i < emailsAmigos.length; i++){
			
			var emailContato = emailsAmigos[i];
				
			addOption(ondeAdicionar, emailContato, emailContato);
				
			selecionado++;
						
		}
		
		for (var i = 0; i < selectAmigos.childNodes.length; i++){
			
			for (var j = 0; j < emailsAmigos.length; j++){
				
				if ( selectAmigos.childNodes[i].value == emailsAmigos[j] ){
					
					var no = selectAmigos.childNodes[i];
					
					selectAmigos.removeChild(no);
					
				}
				
			}
			
		}
		
	}else{
		
		alert('Primeiro digite seu usuário e senha do MSN e clique no botão Listar Seus Amigos do MSN!');
		
	}
	
	if ( selecionado == 0 ){
		
		alert('É preciso selecionar algum amigo para efetuar esta operação!');
		
	}
	
}

function trocarTodosAmigosLado(amigos, ondeAdicionar){
	
	if ( ondeAdicionar.hasChildNodes() ){
		
		optionsOndeAdicionar = ondeAdicionar.options;
		
		for(var j = 0; j < optionsOndeAdicionar.length; j++){
			
			var emailContato = optionsOndeAdicionar[j].value;
				
			addOption(ondeAdicionar, emailContato, emailContato);
			
			var no = optionsOndeAdicionar[j];
			
			ondeAdicionar.removeChild(no);
			
		}
		
	}
	
	var selectAmigos = document.getElementById(amigos);
	
	var options = selectAmigos.options;
	
	if ( options.length > 0 ){
		
		for(var i = 0; i < options.length; i++){
			
			emailContato = options[i].value;
				
			addOption(ondeAdicionar, emailContato, emailContato);
						
		}
		
		clear(selectAmigos);
	
	}else{
		
		alert('Primeiro digite seu usuário e senha do MSN e clique no botão Listar Seus Amigos do MSN!');
		
	}
	
}

function enviarListaAmigosConfirmados(amigosConfirmados){
	
	if ( amigosConfirmados.hasChildNodes() ){
		
		var emailsContatos = '';
		
		optionsAmigosConfirmados = amigosConfirmados.options;
		
		for(var j = 0; j < optionsAmigosConfirmados.length; j++){
			
			if ( emailsContatos == '' ){
				
				emailsContatos += optionsAmigosConfirmados[j].value;
				
			}else{
				
				emailsContatos += "," + optionsAmigosConfirmados[j].value;
				
			}
			
		}
		
		var div = document.createElement("div");
		div.style.margin = "0px";
		div.style.padding = "20px";
		div.style.height = "20px";
		div.style.width = "100px";
		div.style.top = "-150px";
		div.style.left = "150px";
		div.style.border = "2px #000000 solid";
		div.style.backgroundColor = "#EAEAFF";
		div.style.color = "#000000";
		div.style.fontWeight = "bold";
		div.style.textAlign = "center";
		div.style.positon = "absolute";
		div.style.display = "block";
		div.style.zIndex = "500000";
		div.id = "statusEnvio";
		
		var textoDiv = document.createTextNode('Enviando...');
		
		div.appendChild(textoDiv);
		
		var local = document.getElementById('conteudoFormMSN');		
		local.appendChild(div);
		
		var usuarioMSN = document.getElementById('usuarioMSN').value;
		
		var url= "./submitIndiqueAmigosMSN.php?amigosConfirmadosMSN=" + emailsContatos + "&usuarioMSN=" + usuarioMSN;
		
		xmlHttpELAC = GetXmlHttpObject(enviarListaAmigosConfirmadosAjax);
		xmlHttpELAC.open("GET", url , true);
		xmlHttpELAC.send(null);
		
	}else{
		
		alert('Primeiro selecione o(s) amigo(s) na caixa Amigos!');
		
	}
	
}

function enviarListaAmigosConfirmadosAjax(){
	
	if (xmlHttpELAC.readyState == 4 || xmlHttpELAC.readyState == "complete"){
		
		var local = document.getElementById('conteudoFormMSN');
		var statusEnvio = document.getElementById('statusEnvio');
				
		local.removeChild(statusEnvio);
				
		var usuario = document.getElementById('usuarioMSN');
		var senha = document.getElementById('senhaMSN');
		var amigos = document.getElementById('amigosMSN');
		var amigosConfirmados = document.getElementById('amigosConfirmadosMSN');
		
		usuario.value = '';
		senha.value = '';
		
		clear(amigos);
		clear(amigosConfirmados);
		
		alert('Indicações enviadas!');
		
	}
	
}

function pegaSelectMultipleSelecionado(id){
	
	var options = document.getElementById(id).options;
	var ret = "";
	
	for(var i = 0; i < options.length; i++){
		
		if( options[i].selected ){
			
			if ( ret == "" ){
				
				if ( options[i].value != 0 || options[i].value != '' ){
					
					ret += options[i].value;
					
				}
				
			}else{
				
				if ( options[i].value != 0 || options[i].value != '' ){
					
					ret += "," + options[i].value;
					
				}
				
			}
			
		}
		
	}
	
	return ret;
	
}

/**
* Abre uma solicitação para papo online
*/
function openChat(idSolicitado, obj){		
	
	
	//var ob = document.getElementById(obj);
	
	//ob.href = "Javascript:alert('Você já chamou este usuário para o PapoOnline!\nCaso a janela de confirmação ainda não tenha aberto, espere alguns segundos até que ela abra!\nSe por algum motivo a janela não abrir, pressione a tecla F5 para recarregar a página, e então chame o usuário novamente.');";		
	
	var url = "./openChat.php?idSolicitado="+idSolicitado;
	
	xmlHttpz=GetXmlHttpObject(fOpenChat);
	xmlHttpz.open("GET", url , true);
	xmlHttpz.send(null);				
	
	
}



/**
* Ação da função open chat
*/
function fOpenChat(){
	
	if ( ( xmlHttpz.readyState == 4 ) || ( xmlHttpz.readyState == "complete" ) ){ 
		var response = xmlHttpz.responseText;
		
		if ( response == 1 ){
			alert('Este usuário optou por bloquea-lo.\nSendo assim você não pode chama-lo(a) para o papo online!');
		}else if ( response == 2 ){
			alert('Você optou por bloquear este usuário.\nSendo assim você também não pode chama-lo(a) para o papo online!');
		}else if ( response == 3 ){
			alert('Este usuário escolheu que somente pessoas do mesmo estado que ele podem ter acesso ao seu perfil!');
		}else if ( response == 4 ){
			alert('Este usuário escolheu que somente pessoas que tenham a mesma preferência sexual que ele podem ter acesso ao seu perfil!');
		}else if ( response == 5 ){
			alert('Este usuário escolheu que somente pessoas do sexo oposto ao dele podem ter acesso ao seu perfil!');
		}
		else if ( response == 6 ){
			alert('Este usuário escolheu que não quer ser chamado para Papo Online no momento!');
		}
		else if ( response == "tempo" ){
			alert('Você chamou este usuário para o Papo Online há pouquíssimo tempo!\nAguarde um pouco para chamá-lo novamente!');
		}		
		else if ( response > 6 ){			
			messageChat("O usuário foi notificado. Aguarde a resposta...",response);
		}else{
			messageChat("Ocorreu um problema ao notificar o usuário. Aguarde uns minutos e tente novamente",'');
		}
		
	}	
	
}


/**
* Altera a permissão sobre a aceitação do papo online
*/
var permissaoPapoOnline = function (obj){
	if ( obj.checked ){
		
		//recusar
		var url = "./permissaoPapoOnline.php?acao=recusar";		
		
	}else{
		
		//aceitar
		var url = "./permissaoPapoOnline.php?acao=aceitar";				
		
	}
	
	var ajax=GetXmlHttpObject( function(){} );
	ajax.open("GET", url , true);
	ajax.send(null);	
	
}


/**
* Abre uma janela de mensagem
*/
function messageChat(message,idPapoOnline){	
	var url = "./messageChat.php?mensagem="+message+'&idPapoOnline='+idPapoOnline;	
	openWindow(550,225,300,300,url);
}

function buscarAmigos(iProvedor){
	
	provedor = iProvedor;
	
	var email, senha;
	
	if ( provedor == 'msn' ){
		email = document.getElementById('emailMsn');
		senha = document.getElementById('senhaMsn');
		mensagem = document.getElementById('mensagemMsn');
		resultado = document.getElementById('resultadoMsn');
	}else if( provedor == 'yahoo' ){
		email = document.getElementById('emailYahoo');
		senha = document.getElementById('senhaYahoo');
		mensagem = document.getElementById('mensagemYahoo');
		resultado = document.getElementById('resultadoYahoo');
	}else if( provedor == 'gmail' ){
		email = document.getElementById('emailGmail');
		senha = document.getElementById('senhaGmail');
		mensagem = document.getElementById('mensagemGmail');
		resultado = document.getElementById('resultadoGmail');
	}else if( provedor == 'hotmail' ){
		email = document.getElementById('emailHotmail');
		senha = document.getElementById('senhaHotmail');
		mensagem = document.getElementById('mensagemHotmail');
		resultado = document.getElementById('resultadoHotmail');
	}else if( provedor == 'orkut' ){
		email = document.getElementById('emailOrkut');
		senha = document.getElementById('senhaOrkut');
		mensagem = document.getElementById('mensagemOrkut');
		resultado = document.getElementById('resultadoOrkut');
	}
	
	if ( (email.value.length < 1) || (email.value == '') ){
		alert("Por favor preencha o campo: '" + email.title + "'");
		email.focus();
		return false;
	}
	
	if ( (senha.value.length < 1) || (senha.value == '') ){
		alert("Por favor preencha o campo: '" + senha.title + "'");
		senha.focus();
		return false;
	}
	
	if( document.getElementById ){
		mensagem.innerHTML = "<img src='http://imagens.aondenamoro.com/img/wait.gif' />&nbsp;&nbsp;<font style='font-size:11px; font-family:tahoma;'>Aguarde, importando contatos...</font>";
	}
	
	var url = "./buscaAmigos.php?acesso=" + provedor + "&email=" + email.value + "&senha=" + escape(senha.value);
	
	xmlHttpBA = GetXmlHttpObject(buscarAmigosAjax);
	xmlHttpBA.open("GET", url , true);
	xmlHttpBA.send(null);		
	
}

function buscarAmigosAjax(){
	
	if ( ( xmlHttpBA.readyState == 4 ) || ( xmlHttpBA.readyState == "complete" ) ){
		
		mensagem.innerHTML = '';
		resultado.innerHTML = '';
		
		var responseJSON = jsonResponse(xmlHttpBA.responseText);
		
		if ( responseJSON != null ){
			
			var p, br, texto, a, input, label, emailContato, table, tr, td;
			
			p = document.createElement('p');
			
			p.style.textAlign = 'center';
			p.style.fontFamily = 'Tahoma';
			p.style.fontSize = '11px';
			texto = document.createTextNode('Há um total de ' + responseJSON.length + ' emails importados.');
			p.appendChild(texto);
			
			resultado.appendChild(p);
			
			br = document.createElement('br');
			
			resultado.appendChild(br);
			
			p = document.createElement('p');
			p.style.textAlign = 'center';
			a = document.createElement('a');
			a.setAttribute('href', 'javascript:void(0);');
			a.setAttribute('onclick', "convidarAmigos('emailAmigo','" + provedor + "')");
			a.setAttribute('class', 'botao');
			a.setAttribute('className', 'botao');
			texto = document.createTextNode('Indicar o site aos meus amigos');
			
			a.appendChild(texto);
			p.appendChild(a);
			resultado.appendChild(p);
			
			br = document.createElement('br');
			
			resultado.appendChild(br);
			
			p = document.createElement('p');
			p.style.textAlign = 'center';
			a = document.createElement('a');
			a.style.color = '#333333';
			a.setAttribute('href', 'javascript:void(0);');
			a.setAttribute('onclick', "selectAll('emailAmigo')");
			texto = document.createTextNode('Marcar Todos');
			
			a.appendChild(texto);
			p.appendChild(a);
			
			p.innerHTML += "&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;";
			
			a = document.createElement('a');
			a.style.color = '#333333';
			a.setAttribute('href', 'javascript:void(0);');
			a.setAttribute('onclick', "unselectAll('emailAmigo')");
			texto = document.createTextNode('Desmarcar Todos');
			
			a.appendChild(texto);
			p.appendChild(a);
			
			resultado.appendChild(p);
			
			var conteudoTabelaContatos = '';
			
			// Vou percorrer a array de retorno pegando os emails e montando a tabela
			for ( var i = 0; i < responseJSON.length; i++ ){
				
				conteudoTabelaContatos += "<tr><td class='resultado'><input type='checkbox' checked='checked' name='emailAmigo' id='" + decodeURI(responseJSON[i]['email']) + "' value='" + decodeURI(responseJSON[i]['email']) + "' /><input type='hidden' id='nome_" + decodeURI(responseJSON[i]['email']) + "' value='" + responseJSON[i]['nome'] + "' /></td><td class='resultado'><label for='" + decodeURI(responseJSON[i]['email']) + "' class='label'>" + responseJSON[i]['nome'] + "</label></td><td class='resultado'><label for='" + decodeURI(responseJSON[i]['email']) + "' class='label'>" + decodeURI(responseJSON[i]['email']) + "</label></td></tr>";
				
			}
			
			resultado.innerHTML += "<table><tr><th class='resultado'>&nbsp;</th><th class='resultado'>Nome</th><th class='resultado'>Email</th></tr>" + conteudoTabelaContatos + "</table>";
			
			br = document.createElement('br');
			resultado.appendChild(br);
			
			p = document.createElement('p');
			p.style.textAlign = 'center';
			a = document.createElement('a');
			//a.setAttribute('href', 'javascript:void(0);');
			a.setAttribute('href', "javascript:convidarAmigos('emailAmigo','" + provedor + "');");
			a.setAttribute('class', 'botao');
			a.setAttribute('className', 'botao');
			texto = document.createTextNode('Indicar o site aos meus amigos');
			
			a.appendChild(texto);
			p.appendChild(a);
			resultado.appendChild(p);
			
			br = document.createElement('br');
			resultado.appendChild(br);
			
		}else{
			
			mensagem.innerHTML = "<font style='font-family: Tahoma; font-size: 11px;'>Falha ao importar contatos. Por favor verifique seu e-mail e senha!</font>";
			
		}
		
	}	
	
}

function convidarAmigos(obj, provedor){
	
	var email;
	var listaEmails = document.getElementsByName(obj);
	var url = "./submitIndicacao.php";
	var dados = '';
	var qtd = listaEmails.length;
	
	if ( provedor == 'msn' ){
		email = document.getElementById('emailMsn');
		mensagem = document.getElementById('mensagemMsn');
	}else if( provedor == 'yahoo' ){
		email = document.getElementById('emailYahoo');
		mensagem = document.getElementById('mensagemYahoo');
	}else if( provedor == 'gmail' ){
		email = document.getElementById('emailGmail');
		mensagem = document.getElementById('mensagemGmail');
	}else if( provedor == 'hotmail' ){
		email = document.getElementById('emailHotmail');
		mensagem = document.getElementById('mensagemHotmail');
	}else if( provedor == 'orkut' ){
		email = document.getElementById('emailOrkut');
		mensagem = document.getElementById('mensagemOrkut');
	}
	
	mensagem.innerHTML = "<img src='http://imagens.aondenamoro.com/img/wait.gif' />&nbsp;&nbsp;<font style='font-size:11px; font-family:tahoma;'>Aguarde, enviando indicações...</font>";
	
	var paragrafoEnviando = document.createElement('p');
	paragrafoEnviando.innerHTML = "<img src='http://imagens.aondenamoro.com/img/wait.gif' />&nbsp;&nbsp;<font style='font-size:11px; font-family:tahoma;'>Aguarde, enviando indicações...</font>";
	
	resultado.appendChild(paragrafoEnviando);
	
	dados = "from=" + email.value + "&acesso=" + provedor;
	
	for ( var i = 0; i < listaEmails.length; i++ ){
		
		if ( listaEmails[i].checked == true ){
			
			dados += "&email" + i + "=" + escape( encodeURI(listaEmails[i].value) );
			dados += "&nome" + i + "=" + escape( encodeURI(document.getElementById('nome_' + listaEmails[i].value).value) );
			
		}else{
			
			qtd--;
			
		}
		
	}
	
	if ( qtd == 0 ){
		
		resultado.removeChild(paragrafoEnviando);
		mensagem.innerHTML = '';
		
		alert('Escolha pelo menos um amigo a ser indicado.');
		
		return;
		
	}
	
	xmlHttpCA = GetXmlHttpObject(convidarAmigosAjax);
	xmlHttpCA.open('POST', url, true);
	xmlHttpCA.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttpCA.setRequestHeader("Content-length", dados.length);
	xmlHttpCA.setRequestHeader("Connection", "close");
	xmlHttpCA.send(dados);
	
}

function convidarAmigosAjax(){
	
	if (xmlHttpCA.readyState == 4 || xmlHttpCA.readyState == "complete"){
		
		mensagem.innerHTML = '';
		
		var response = xmlHttpCA.responseText;
		var pai, avo;
		
		if ( response == 1 ){
			
			pai = mensagem.parentNode;
			avo = pai.parentNode;
			avo.removeChild(pai);
			
			avo.innerHTML += "<font style='font-size:11px; font-family:tahoma;'>Indicações enviadas.</font>";
			
		}else if( response == 0 ){
			
			mensagem.innerHTML = "<font style='font-family: Tahoma; font-size: 11px;'>Falha ao importar contatos. Por favor verifique seu e-mail e senha!</font>";
			
		}
		
	}
	
}

function convidarAmigosDireto(provedor){
	
	var email, senha;
	
	if ( provedor == 'msn' ){
		email = document.getElementById('emailMsn');
		mensagem = document.getElementById('mensagemMsn');
		senha = document.getElementById('senhaMsn');
	}else if( provedor == 'yahoo' ){
		email = document.getElementById('emailYahoo');
		mensagem = document.getElementById('mensagemYahoo');
		senha = document.getElementById('senhaYahoo');
	}else if( provedor == 'gmail' ){
		email = document.getElementById('emailGmail');
		mensagem = document.getElementById('mensagemGmail');
		senha = document.getElementById('senhaGmail');
	}else if( provedor == 'hotmail' ){
		email = document.getElementById('emailHotmail');
		mensagem = document.getElementById('mensagemHotmail');
		senha = document.getElementById('senhaHotmail');
	}else if( provedor == 'orkut' ){
		email = document.getElementById('emailOrkut');
		mensagem = document.getElementById('mensagemOrkut');
		senha = document.getElementById('senhaOrkut');
	}
	
	if ( (email.value.length < 1) || (email.value == '') ){
		alert("Por favor preencha o campo: '" + email.title + "'");
		email.focus();
		return false;
	}
	
	if ( (senha.value.length < 1) || (senha.value == '') ){
		alert("Por favor preencha o campo: '" + senha.title + "'");
		senha.focus();
		return false;
	}
	
	var url = "./submitIndicacaoDireto.php?acesso=" + provedor + "&email=" + email.value + "&senha=" + senha.value;
	
	mensagem.innerHTML = "<img src='http://imagens.aondenamoro.com/img/wait.gif' />&nbsp;&nbsp;<font style='font-size:11px; font-family:tahoma;'>Aguarde, enviando indicações...</font>";
	
	xmlHttpCA = GetXmlHttpObject(convidarAmigosAjax);
	xmlHttpCA.open('GET', url, true);
	xmlHttpCA.send(null);
	
}

function GetXmlHttpObject(handler){ 
	var objXmlHttp=null;
	
	if (navigator.userAgent.indexOf("Opera")>=0){
		alert("This example doesn't work in Opera");
		return; 
	}
	if (navigator.userAgent.indexOf("MSIE")>=0){ 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0){
			strName="Microsoft.XMLHTTP";
		} 
		try{ 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler; 
			return objXmlHttp;
		} 
		catch(e){ 
			alert("Error. Scripting for ActiveX might be disabled"); 
			return; 
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0){
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler; 
		return objXmlHttp;
	}
}

/**
* Função de tratamento de retorn de respostas no formato JSON
*/
function jsonResponse( str ){

	return eval( "(" + unescape(str) + ")" );

}

/**
* Verifica se o apelido que o usuário escolheu já existe
*/
function verificaApelidoExistente(apelido){
	
	var url = "./verificaApelidoExistente.php?apelido=" + escape( encodeURI(apelido) );
	
	xmlHttpVAE = GetXmlHttpObject(verificaApelidoExistenteAjax);
	xmlHttpVAE.open('GET', url, true);
	xmlHttpVAE.send(null);
	
}

/**
* AJAX da função verificaApelidoExistente
*/
function verificaApelidoExistenteAjax(){
	
	if (xmlHttpVAE.readyState == 4 || xmlHttpVAE.readyState == "complete"){
		
		var response = xmlHttpVAE.responseText;
		var divApelido = document.getElementById('divApelido');
		var inputApelido = document.getElementById('apelidoCadastro');
		
		// Caso já exista o apelido
		if ( response == 1 ){
			
			// Verifico se a mensagem de apelido existente já está na tela
			if ( existeSpanApelidoExistente == true ){
				
				// Dou o foco para o input
				inputApelido.focus();
				
				return false;
				
			}else{
				
				existeSpanApelidoExistente = true;
				
				inputApelido.style.backgroundColor = "#FFFFCC";
				inputApelido.focus();
				
				// Mando a mensagem para o usuário
				criarCaixaMensagem('apelidoExistente', 'Já existe um usuário cadastrado com este apelido.<br />Dica: Use seu nome junto com sua idade, estado, cidade, etc. para formar seu apelido.', divApelido);
				
				return false;
				
			}
			
		// Caso não exista
		}else if( response == 0 ){
			
			// Verifico se a mensagem de apelido existente já está na tela
			if ( existeSpanApelidoExistente == true ){
				
				existeSpanApelidoExistente = false;
				
				inputApelido.style.backgroundColor = "#FFF";
				
				divApelido.removeChild( document.getElementById('apelidoExistente') );
				
			}
			
		}
		
	}
	
}

/**
* Verifica se o apelido escolhido pelo usuário é válido
*/
function verificaApelidoValido(apelido){
	
	var expApelidoValido = /^[0-9a-z_]{1,}$/i;
	var divApelido = document.getElementById('divApelido');
	var inputApelido = document.getElementById('apelidoCadastro');
	
	var qtdCaracteresApelido = apelido.length;
	
	// Executo a expressão regular para verificar se o apelido atende as nossas regras
	// Caso seja um apelido válido, verifico se a mensagem de apelido inválido já foi enviada para o usuário e retiro
	// Em seguida, verifico se o apelido já existe
	if ( (expApelidoValido.test(apelido) == true) && (qtdCaracteresApelido >= 4) && (qtdCaracteresApelido <= 15) ){
		
		if ( existeSpanApelidoInvalido == true ){
			
			existeSpanApelidoInvalido = false;
			
			inputApelido.style.backgroundColor = "#FFF";
			
			divApelido.removeChild( document.getElementById('apelidoIncorreto') );
			
		}
		
		// Verifica se o apelido já existe
		verificaApelidoExistente(apelido);
		
	}else{
		
		// Verifico se a mensagem de apelido existente já está na tela
		// Caso esteja, removo
		if ( existeSpanApelidoExistente == true ){
			
			existeSpanApelidoExistente = false;
			
			divApelido.removeChild( document.getElementById('apelidoExistente') );
			
		}
		
		// Verifico se a mensagem de apelido inválido já está na tela
		if ( existeSpanApelidoInvalido == true ){
			
			// Dou o foco para o input
			inputApelido.focus();
			
			return false;
			
		}else{
			
			existeSpanApelidoInvalido = true;
			
			inputApelido.style.backgroundColor = "#FFFFCC";
			inputApelido.focus();
			
			// Mando a mensagem para o usuário
			criarCaixaMensagem('apelidoIncorreto', 'O apelido deve ter no mínimo 4 e no máximo 15 caracteres e conter apenas letras, números ou \'_\' (underscore).', divApelido);
			
			return false;
			
		}
		
	}
	
}

/**
* Verifica se o email que o usuário escolheu já existe
*/
function verificaEmailExistente(email){
	
	var url = "./verificaEmailExistente.php?email=" + escape( encodeURI(email) );
	
	xmlHttpVAE = GetXmlHttpObject(verificaEmailExistenteAjax);
	xmlHttpVAE.open('GET', url, true);
	xmlHttpVAE.send(null);
	
}

/**
* AJAX da função verificaApelidoExistente
*/
function verificaEmailExistenteAjax(){
	
	if (xmlHttpVAE.readyState == 4 || xmlHttpVAE.readyState == "complete"){
		
		var response = xmlHttpVAE.responseText;
		var divEmail = document.getElementById('divEmail');
		var inputEmail = document.getElementById('email');
		
		// Caso já exista o apelido
		if ( response == 1 ){
			
			// Verifico se a mensagem de apelido existente já está na tela
			if ( existeSpanEmailExistente == true ){
				
				// Dou o foco para o input
				inputEmail.focus();
				
				return false;
				
			}else{
				
				existeSpanEmailExistente = true;
				
				inputEmail.style.backgroundColor = "#FFFFCC";
				inputEmail.focus();
				
				// Mando a mensagem para o usuário
				criarCaixaMensagem('emailExistente', 'Já existe um usuário cadastrado com este email.', divEmail);
				
				return false;
				
			}
			
		// Caso não exista
		}else if( response == 0 ){
			
			// Verifico se a mensagem de apelido existente já está na tela
			if ( existeSpanEmailExistente == true ){
				
				existeSpanEmailExistente = false;
				
				inputEmail.style.backgroundColor = "#FFF";
				
				divEmail.removeChild( document.getElementById('emailExistente') );
				
			}
			
		}
		
	}
	
}

/**
* Verifica se o apelido escolhido pelo usuário é válido
*/
function verificaSenhaValida(senha){
	
	var expSenhaValida = /^[0-9a-z]{1,}$/i;
	var divSenha = document.getElementById('divSenha');
	var inputSenha = document.getElementById('senhaCadastro');
	
	var qtdCaracteresSenha = senha.length;
	
	if ( (expSenhaValida.test(senha) == true) && (qtdCaracteresSenha >= 6) && (qtdCaracteresSenha <= 10) ){
		
		if ( existeSpanSenhaInvalida == true ){
			
			existeSpanSenhaInvalida = false;
			
			inputSenha.style.backgroundColor = "#FFF";
			
			divSenha.removeChild( document.getElementById('senhaInvalida') );
			
		}
		
	}else{
		
		// Verifico se a mensagem de senha inválido já está na tela
		if ( existeSpanSenhaInvalida == true ){
			
			// Dou o foco para o input
			inputSenha.focus();
			
			return false;
			
		}else{
			
			existeSpanSenhaInvalida = true;
			
			inputSenha.style.backgroundColor = "#FFFFCC";
			inputSenha.focus();
			
			// Mando a mensagem para o usuário
			criarCaixaMensagem('senhaInvalida', 'A senha deve ter no mínimo 6 e no máximo 10 caracteres e conter apenas letras e números.', divSenha);
			
			return false;
			
		}
		
	}
	
}

/**
* Função que cria o box das mensagens de erro no cadastro
*/
function criarCaixaMensagem(id, msg, elementoPai){
	
	// Crio o span que vai conter a mensagem
	var span = document.createElement('span');
	span.setAttribute('id', id);
	span.style.fontWeight = 'bold';
	span.style.color = '#FF0000';
	span.style.fontFamily = 'Arial, Verdana';
	span.style.fontSize = '11px';
	span.style.display = 'block';
	span.style.width = '425px';
	
	// Imagem de alerta
	var img = document.createElement('img');
	img.setAttribute("src", "./img/alert.gif");
	img.style.border = '0';
	
	span.appendChild(img);
	span.innerHTML += "&nbsp;&nbsp;";
	span.innerHTML += msg;
	
	elementoPai.appendChild(span);
	
}