///////////////
// EncontraImoveis - Portal de Pesquisa de Imoveis
// -----------------------------------------------
//
// Funcoes JavaScript
//
//
///////////////


// Para acesso a banco de dados baseado em AJAX
 function xvConectaBrowseAjax() {
   //verifica se o browser tem suporte a pcAjaxXObj
   try {
     pcAjaxXObj = new ActiveXObject("Microsoft.XMLHTTP");
   }
   catch(e) {
     try {
       pcAjaxXObj = new ActiveXObject("Msxml2.XMLHTTP"); // activeX (IE5.5+/MSXML2+)
     }
     catch(ex) {
       try {
         pcAjaxXObj = new XMLHttpRequest(); // FF, Safari, Konqueror, Opera, ...
       }
       catch(exc) {
         try {
           pcAjaxXObj = new ActiveXObject("Microsoft.XMLHTTP"); // activeX (IE5+/MSXML1)
         } catch(exc2) {
//           alert("Browser sem recursos para uso do Ajax");
           pcAjaxXObj = null;
         }
       }
     }
   }
 }

 function xvProcessaXMLCombo(cObj, cClasse, paCallMsg){
   //pega a tag cidade
   var cDataArray   = cObj.getElementsByTagName("elemento");

   //total de elementos contidos na tag cidade
   if(cDataArray.length > 0) {
     //percorre o arquivo XML paara extrair os dados
     for(var nIdx = 0 ; nIdx < cDataArray.length ; nIdx++) {
       var cItem = cDataArray[nIdx];

       //cont�udo dos campos no arquivo XML
       var nCodigo    = cItem.getElementsByTagName("id")[0].firstChild.nodeValue;
       var aDescricao = cItem.getElementsByTagName("nome")[0].firstChild.nodeValue;

       idOpcao.innerHTML = paCallMsg;
       //cria um novo option dinamicamente  
       var novo = document.createElement("option");
       //atribui um ID a esse elemento
       novo.setAttribute("id", "opcoes");
       //atribui um valor
       novo.value = nCodigo;
       //atribui um texto
       novo.text  = aDescricao;
       //finalmente adiciona o novo elemento
       cClasse[0].options.add(novo);
     }
   }
 }

 // Recebe uma string dentro de outra string:
 // 1a string deve ser separada por @
 // 2a string deve ser separada por |
 // ex: cbUf|'Msg de Erro'@cbCidade|'Msg de Erro de Cidade'@...
 function xvTrataCombos(paPedido, paCallPHP, paCallMsgOk, arOpcoes)
 {
   //verifica se o browser tem suporte a pcAjaxXObj
   xvConectaBrowseAjax();
   //se tiver suporte pcAjaxXObj
   if(pcAjaxXObj) {
     //deixa apenas o elemento 1 no option, os outros s�o exclu�dos
     // Tratando diversas opcoes
     var arUmCombo=arOpcoes.split("@");

     // Inicia Tudo
     var cClassePri = false;
     var cPri = false;
     for(var nI=0; nI < arUmCombo.length; nI++) {

       var arOpc=arUmCombo[nI].split("|"); // 0-classe 1-onde carregar 2-msg erro

       // Testa se existe classe pra esta entrada
       cClasse = document.getElementsByName(arOpc[0]);
       if(cClasse) {
         if(nI == 0) { // primeiro
           // primeira opcao mantem o dado la, o resto inicia
         }
         else {
           if(cClassePri == false) {
             cClassePri = cClasse;
             cPri = arOpc;
           }
           cClasse[0].options.length = 1;
           idOpcao2  = document.getElementById(arOpc[1]);
           idOpcao2.innerHTML = arOpc[2];
         }
       }
     }
//   	paCallPHP = "components/com_encontraimoveis/quick/teste.php";
     pcAjaxXObj.open("POST", paCallPHP, true);

     pcAjaxXObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     pcAjaxXObj.onreadystatechange = function() {
       idOpcao  = document.getElementById(cPri[1]);
       //enquanto estiver processando...emite a msg de carregando

       if(pcAjaxXObj.readyState == 1)
         idOpcao.innerHTML = "Carregando...";
       //ap�s ser processado - chama fun��o processXML que vai varrer os dados
       if(pcAjaxXObj.readyState == 4 ) {
         if(pcAjaxXObj.responseXML)
{
           xvProcessaXMLCombo(pcAjaxXObj.responseXML, cClassePri, paCallMsgOk);
}
         else
           idOpcao.innerHTML = cPri[2];
       }
     }
     //passa o c�digo do estado escolhido para cidade.php
     var paParams = 'ID=Combo&Pedido='+paPedido;
     pcAjaxXObj.send(paParams);
   }
 }

 function ValidaEcontraFacil(cForm)
 {
   xvConectaBrowseAjax();

   //se tiver suporte pcAjaxXObj
   if(pcAjaxXObj) {
     //deixa apenas o elemento 1 no option, os outros s�o exclu�dos
     cClasse = document.getElementsByName("cbUf");
     if(cClasse
     && cClasse.length > 0
     && cClasse[0].value == 'all') {
       alert("O campo 'UF' é obrigatório!");
       cClasse[0].focus();
       return;
     }

     cClasse = document.getElementsByName("cbCidade");
     if(cClasse.length > 0
     && cClasse[0].value == 'all') {
       alert("O campo 'Cidade' é obrigatório!");
       cClasse[0].focus();
       return;
     }
   }
//  Abre popup
   document.fmEncontra.submit(); 
 }

 function AtualizaBd(paPath, paParam)
 {
   xvConectaBrowseAjax();

   //se tiver suporte pcAjaxXObj
   if(pcAjaxXObj) {
     //Requisita pagina para atualizacao do bd
     pcAjaxXObj.open("POST", paPath, true);
      
     pcAjaxXObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     //Envia parametros
     pcAjaxXObj.send(paParam);
     
     id = paParam.split("=");
     xvLimpaDestino(id[1]);
   }
 }

 function popupCentral(arquivo) {
     largura = 600;
     altura = 600;
     calcleft = ((screen.width-34) / 2) - (largura / 2)
     calctop = (screen.height / 2) - (altura / 2)
     open(arquivo,"popupcentral","status=no, width=" + largura + ",height=" + altura + ",left=" + calcleft + ",top=" + calctop + ",scrollbars=yes")
 }

// function popupGeral(arquivo,largura,altura) {
   function popupGeral(arquivo, largura, altura) {
   if(!largura)
     largura= 700;
   if(!altura)
     altura = 720;
     var d = new Date()
     x = d.getTime();
     calcleft = ((screen.width-34) / 2) - (largura / 2)
     calctop = (screen.height / 2) - (altura / 2)
     if(arquivo != 'img/')
       window.open(arquivo,"popupgeral"+x,"status=no, width=" + largura + ",height=" + altura + ",left=" + calcleft + ",top=" + calctop + ",scrollbars=yes")
 }


   function CarregarImagem(imagem,old)
   {
/*
     if(document.getElementById(old).src != document.getElementById('grande').src) {
       document.getElementById(old).src= document.getElementById('grande').src;
       document.getElementById('grande').src=imagem;
     }
*/
     document.getElementById('grande').src=imagem;
   }

function TestaEmail(email) {
  if(!email)   
    email = document.formulario.email;
/*
  var Exp = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*
             @(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
 // /^[a-z0-9](\.?\w)*(\-?\w)*@[a-z0-9\-\_]+(\.[a-z0-9]+)*(\.[a-z0-9]{2,4})$/;

  if (!Exp.test(str))
  {
     alert("Digite um e-mail v�lido!");
     return false;
  }
  return true;
*/
    parte1 = email.value.indexOf("@");
//    parte2 = document.formulario.email.value.indexOf(".");
    parte3 = email.value.length;
      if (!(parte1 >= 3 && parte3 >= 6)) {
       alert("Digite um e-mail válido!");
       email.focus();
       return false;
     }
    return true;
}

 function ValidaFaleConosco() {

  if(ValidaForm() == false) {
    return false;
  }
  // Mensagem
  if (document.formulario.mensagem.value==""){
    alert("A mensagem deve ser preenchida");
    document.formulario.mensagem.focus();
    return false;
  }
  return true;
}

 function ValidaForm() {

  if (document.formulario.nome.value==""){
    alert("O nome deve ser preenchido");
    document.formulario.nome.focus();
    return false;
  }
  if (document.formulario.email.value==""){
    alert("O e-mail deve ser preenchido");
    document.formulario.email.focus();
    return false;
  } else
  if (TestaEmail() == false){
    document.formulario.email.focus();
    return false;
  }
  //Telefone
  if (document.formulario.fone.value==""){
    alert("O fone deve ser preenchido");
    document.formulario.fone.focus();
    return false;
  }
  return true;
 }
 function ValidaRecomendar() {

  if (document.formulario.remetente.value==""){
    alert("Todos os campos são obrigatórios");
    document.formulario.remetente.focus();
    return false;
  }
  if (document.formulario.email_rem.value==""){
    alert("Todos os campos são obrigatórios");
    document.formulario.email_rem.focus();
    return false;
  } else
  if (TestaEmail(document.formulario.email_rem) == false){
    document.formulario.email_rem.focus();
    return false;
  }
  if (document.formulario.destinatario.value==""){
    alert("Todos os campos são obrigatórios");
    document.formulario.destinatario.focus();
    return false;
  }
  if (document.formulario.email_dest.value==""){
    alert("Todos os campos são obrigatórios");
    document.formulario.email_dest.focus();
    return false;
  } else
  if (TestaEmail(document.formulario.email_dest) == false){
    document.formulario.email_dest.focus();
    return false;
  }
  return true;
}

// Mostra / Esconde a Div
function MostraDiv(div) {
	var objeto = document.getElementById(""+div+"");
	objeto.style.display = 'block';
}

function EscondeDiv(div) {
	var objeto = document.getElementById(""+div+"");
	objeto.style.display = 'none';
}



 function xvLimpaDestino(paDst)
 {
   cObj = document.getElementById(paDst);
   while(cObj.firstChild)
     cObj.removeChild(cObj.firstChild);
 }
 function MyRefresh()
 {
//  alert("MyRefresh");
  // Aqui voce varre todos os elementos do form
  var paNomeSelect=null;
  for(nF=0; nF < document.forms.length; nF++) {
    cForm = document.forms[nF];

    for(nI=0; nI < cForm.length; nI++) {
      if(cForm.elements[nI].type == 'select-one') {
        if(paNomeSelect != cForm.elements[nI].name) {
          if(paNomeSelect == null)
            // Primeira entrada
            cForm.elements[nI].selectedIndex = 1;
          else
            cForm.elements[nI].selectedIndex = 0;
          paNomeSelect = cForm.elements[nI].name;
        }
      }
    }
  }
 }

function AbrePopup(url,popup_w,popup_h)
{	
	var config;
	config = "scrollbars=no,toolbar=no,location=no, resizable=no, width=";
	config = config.concat(popup_w,",height=",popup_h);
	window.open(url,'directions',config); 			

//	window.open(url,'directions','width=1020,scrollbars=yes,toolbar=no,location=no, resizable=no'); 			
}
function DesabilitaCampo(input){
    var input = document.getElementsByName(input)[0];
    input.style.backgroundColor = '#EaEaEa';
    input.value = '';
    input.disabled = "disabled";
}

function HabilitaCampo(input){
    var input = document.getElementsByName(input)[0];
    input.removeAttribute('disabled');
    input.style.backgroundColor = '#FaFaFa';
}

function TrocaClasse(elemento, id){
    var aba_selecionada = document.getElementById(id);
    aba_selecionada.className='';
    aba_selecionada.removeAttribute('class');
    aba_selecionada.removeAttribute('id');
    elemento.className = id;
    elemento.setAttribute('id',id);
    elemento.setAttribute('class',id);
}
