// JavaScript Document
var Ajax = false;
	function AjaxRequest()
	{
		Ajax = false;
		if (window.XMLHttpRequest)
		{ // Mozilla, Safari,...
			Ajax = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // IE
			try {
				Ajax = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					Ajax = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
	} 


// JavaScript Document
function Dados(valor) {
//verifica se o browser tem suporte a ajax
	try {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
			}
	catch(ex) {
		try {
			ajax = new XMLHttpRequest();
			}
			catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				ajax = null;
			}
	}
}

//se tiver suporte ajax
if(ajax) { 
	//deixa apenas o elemento 1 no option, os outros são excluídos
	document.form1.cidades.options.length = 1;
	idOpcao  = document.getElementById("nome_cidades");
	ajax.open("POST", "gre_cidades_ajax.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.onreadystatechange = 
	function() {
		//enquanto estiver processando...emite a msg de carregando
		if(ajax.readyState == 1) {
			idOpcao.innerHTML = "Aguarde Carregando...!";   
		}
		//após ser processado - chama função processXML que vai varrer os dados
		if(ajax.readyState == 4 ){
			if(ajax.responseXML) {
				processXML(ajax.responseXML);
			}else {
				//caso não seja um arquivo XML emite a mensagem abaixo
				idOpcao.innerHTML = "Primeiro selecione o estado";
			}
		}
	}
	//passa o código do estado escolhido
	var params = "estado="+valor;
	ajax.send(params);
	}
}


function processXML(obj){
	document.form1.cidades.disabled=false;
	//pega a tag cidade
	var dataArray   = obj.getElementsByTagName("cidades");
	//total de elementos contidos na tag cidade
	if(dataArray.length > 0) {
		//percorre o arquivo XML paara extrair os dados
		for(var i = 0 ; i < dataArray.length ; i++) {
			var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var nome =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
			idOpcao.innerHTML = "Selecione";
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			//atribui um ID a esse elemento
			novo.setAttribute("id", "nome_cidades");
			//atribui um valor
			novo.value = nome;
			//atribui um texto
			novo.text  = nome;
			//finalmente adiciona o novo elemento
			document.form1.cidades.options.add(novo);
		}
	}
	else {
		//caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Primeiro selecione o estado--";
	}	  
}

function logandoRestrito(id,id1){
	
	if(id.value=="" || id1.value==""){
		document.getElementById('msgHeader').innerHTML = '<img src="img/erro.gif"> <font color="#FF0000"><strong>Favor preencher corretamente os campo acima!</strong></font>';
		return false;	
	} else {
		AjaxRequest();
		Ajax.open('GET', 'rc_login_off.php?usuario='+id.value+'&senha='+id1.value, true);		
		Ajax.setRequestHeader('Content-Type', 'text/xml');
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4){
				if (Ajax.status == 200){
			
					var xmlDoc = Ajax.responseXML;
					var teste = xmlDoc.getElementsByTagName('usuario')[0].childNodes[0].firstChild.nodeValue;
					
					if(teste==="n"){
						document.getElementById('msgHeader').innerHTML = '<img src="img/erro.gif"> <font color="#FF0000"><strong>Usuário / Senha Inválidos. <br />Ou usuário não ativo no sistema ainda!</strong></font>';
						return false;
					}
				
					if(teste==="s"){
						document.getElementById('msgHeader').innerHTML = '<img src="img/sucesso.gif"> <font color="#009933"><strong>Logado!</strong></font>';	
						location.href='index.php';	
					}
			
				} else {
					document.getElementById('msgHeader').innerHTML = '<img src="img/erro.gif"> <font color="#009933"><strong>Erro: Página não encontrada</strong></font>';
				}
			} else {
				document.getElementById('msgHeader').innerHTML = '<img src="img/loading.gif" width="16" hegth="16">Carregando...';
			}			
		}
		Ajax.send(null);
	}
}


function getEmailUsuario(email){

	if(email==""){
		document.getElementById('msg1').innerHTML = '';
		return false;	
	} else {
		AjaxRequest();
		Ajax.open('GET', 'rc_email_off.php?email='+email, true);		
		Ajax.setRequestHeader('Content-Type', 'text/xml');
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4){
				if (Ajax.status == 200){
			
					var xmlDoc = Ajax.responseXML;
					var teste = xmlDoc.getElementsByTagName('usuario')[0].childNodes[0].firstChild.nodeValue;
					
					if(teste==="n"){
						document.getElementById('msg1').innerHTML = '';
						return false;
					}
				
					if(teste==="s"){
						document.getElementById('msg1').innerHTML = '<img src="img/erro.gif"> <font color="#FF0000"><strong>Email já existe em nossa base de dados!</strong></font>';
						document.form1.email.value="";	
					}
			
				} else {
					document.getElementById('msg1').innerHTML = '<img src="img/erro.gif"> <font color="#009933"><strong>Erro: Página não encontrada</strong></font>';
				}
			} else {
				document.getElementById('msg1').innerHTML = '<img src="img/loading.gif" width="16" hegth="16">Carregando...';
			}			
		}
		Ajax.send(null);
	}
}


function esqueceuSenha(email){
	
	if(email.value==""){
		document.getElementById('msgEsqueceuSenha').innerHTML = '<img src="img/erro.gif"> <font color="#FF0000"><strong>Favor preencher corretamente os campo acima!</strong></font>';
		return false;	
	} else {
		AjaxRequest();
		Ajax.open('GET', 'ak_senha_off.php?email='+email.value, true);		
		Ajax.setRequestHeader('Content-Type', 'text/xml');
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4){
				if (Ajax.status == 200){
			
					var xmlDoc = Ajax.responseXML;
					var teste = xmlDoc.getElementsByTagName('usuario')[0].childNodes[0].firstChild.nodeValue;
					
					if(teste==="n"){
						document.getElementById('msgEsqueceuSenha').innerHTML = '<img src="img/erro.gif"> <font color="#FF0000"><strong>Usuário / Senha Inválidos.</strong></font>';
						return false;
					}
				
					if(teste==="s"){
						document.getElementById('msgEsqueceuSenha').innerHTML = '<img src="img/sucesso.gif"> <font color="#009933"><strong>Usuário e Senha encaminha para seu email!</strong></font>';
					}
			
				} else {
					document.getElementById('msgEsqueceuSenha').innerHTML = '<img src="img/erro.gif"> <font color="#009933"><strong>Erro: Página não encontrada</strong></font>';
				}
			} else {
				document.getElementById('msgEsqueceuSenha').innerHTML = '<img src="img/loading.gif" width="16" hegth="16">Carregando...';
			}			
		}
		Ajax.send(null);
	}
}