// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject(); 

// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() 
{	
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // if running Internet Explorer
  if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try 
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e) 
    {
      xmlHttp = false;
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
 
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

// make asynchronous HTTP request using the XMLHttpRequest object 
function process(idacao)
{
  
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {

    // execute the php page from the server
    xmlHttp.open("GET", "includes/ajax/opportunity.php?idacao=" + idacao, true);  
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;
    // make the server request
    xmlHttp.send(null);
  }
  else{
    // if the connection is busy, try again after one second  
    setTimeout('process()', 1000);
	}

}

// executed automatically when a message is received from the server
function handleServerResponse() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {
      xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlRoot = xmlResponse.documentElement;
      
      // get the document element and set in html
      tituloAcaoArray = xmlRoot.getElementsByTagName("titulo_acao");
      tituloAcao = tituloAcaoArray.item(0).firstChild.data;
      if(document.getElementById("tituloOportunidade").value == ""){
      	//document.getElementById("tituloOportunidade").value = tituloAcao;
  	  }
      
      // get the document element and set in html
      id_estadoArray = xmlRoot.getElementsByTagName("id_estado");
      id_estado = id_estadoArray.item(0).firstChild.data;
      
      
      if(document.getElementById("idEstado").value == ""){
      	 document.getElementById("idEstado").value = id_estado;
      	 Dados(document.getElementById("idEstado").value,'idCidade',"");
  	  }
      
      //captura os nós o xml de publico, causa e ODM
      publicoArray = xmlRoot.getElementsByTagName("elemento_publico");
      causaArray = xmlRoot.getElementsByTagName("elemento_causa");
      odmArray = xmlRoot.getElementsByTagName("elemento_odm");
      
      //atribui os valores de publico, causa e odm
      publicoCausaOdm(publicoArray,"publicoAcao");
      publicoCausaOdm(causaArray,"causaAcao");
      publicoCausaOdm(odmArray,"ODMAcao");

    } 
    // a HTTP status different than 200 signals an error
    else 
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}






/*
atribui publico, causa e odm nos labels do html
*/
function publicoCausaOdm(ARR,labelName){
  //para cada item do array
  document.getElementById(labelName).innerHTML = "";
    if(ARR.length > 0) {
	    for(var i = 0 ; i < ARR.length ; i++) {	      
      		var item = ARR[i];
      		var nome = item.getElementsByTagName("nome")[0].firstChild.nodeValue;
      		var id = item.getElementsByTagName("id")[0].firstChild.nodeValue;
      		var separador = (i+1 < ARR.length)?",":".";
      		document.getElementById(labelName).innerHTML = document.getElementById(labelName).innerHTML+nome+separador+" ";
   		}
    }
}







/*
Exibe o titulo correto da descricao
de acordo com os tipos das oportunidades marcadas.
*/
function tituloDescricao(tipo){
	if(tipo == '1' || tipo == '2'){
		document.getElementById("tipoOpp").innerHTML = "O que você precisa?";
	}
	
	else if(tipo == '4' || tipo == '3'){
		document.getElementById("tipoOpp").innerHTML = "O que você oferece?";
	}
	else{
		document.getElementById("tipoOpp").innerHTML = "";
	}
	
}


/*
Exibe/esconde E muda o titulo de acordo com o tipo de oportunidade
*/
function perfilVoluntario(tipo){

	if(tipo == '1'){
		document.getElementById("tipoOppPerfil").innerHTML = "Perfil do voluntário (requisitos).";
		document.getElementById("linhaTipoOppPerfil").style.display="";
	}
	
	else if(tipo == '3'){
		document.getElementById("tipoOppPerfil").innerHTML = "Meu perfil como voluntário.";
		document.getElementById("linhaTipoOppPerfil").style.display="";
	}
	else{
		document.getElementById("tipoOppPerfil").innerHTML = "";
		document.getElementById("linhaTipoOppPerfil").style.display="none";
		document.getElementById("perfil").value = "";
	}
	
}






/*
Inicializa corretamente marcada a combo dos paises.
*/
function iniciaPais(){
	var idpais = document.getElementById("idPais").value;
	
	if(idpais == ""){
		document.getElementById("idPais").selectedIndex = '1';
	}
	//oculta estado e cidade
	if(idpais != "27" && idpais != ""){
		document.getElementById("linhaIdEstado").style.display="none";
		document.getElementById("linhaIdCidade").style.display="none";
		document.getElementById("idEstado").value = "";
		document.getElementById("idCidade").value = "";
		document.getElementById("id_cidade_temp").value = "";
		Dados(idEstado,'idCidade','');
	}
	
	//mostra estado e cidade
	if(idpais == "27"){
		document.getElementById("linhaIdEstado").style.display="";
		document.getElementById("linhaIdCidade").style.display="";
	}	
}





/*
Inicializa corretamente marcada a combo dos estados.
*/
function iniciaEstados() {
	var idEstado = document.getElementById("idEstado").value;
	
	if(idEstado == ""){
		document.getElementById("id_cidade_temp").value = ""
		document.getElementById("idEstado").selectedIndex = 0;
	}
}






/*
Inicializa corretamente marcada a combo das cidades.
*/
function iniciaCidades() {
	var idEstado = document.getElementById("idEstado").value;
	
	if(idEstado > 0){
		Dados(idEstado,'idCidade',document.getElementById("id_cidade_temp").value);	
	}
}





/*
Inicializa corretamente titulo da acao.
*/
function iniciaAcao() {
	var idacao = document.getElementById("idAcao").value;
	
	if(idacao > 0){
		process(idacao);
	}	
}






/*
Chama funcoes de inicializacao do formulario
colocar esta funcao no body do site.


function iniciaFormulario() {
	
	iniciaPais();
	iniciaEstados();
	iniciaCidades();
	iniciaAcao();
	tituloDescricao(document.getElementById("tipo").value);
	perfilVoluntario(document.getElementById("tipo").value);
}

*/