// JavaScript Document
var ajax_gw = 'ajax/gw.imovel.ajax.php';
atual=0;fila=[];ifila=0;
var xmlhttp; var CadastroInfo; var local; var acao='update'; var atualizado=false; 
try{xmlhttp=new XMLHttpRequest();}catch(ee){try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(E){xmlhttp=false;}}}
array_request = new Object();
array_request.totalItens = 0;
array_request.index = 0;
array_request.cmb = new Array();
array_request.ra  = new Array();
array_request.pv  = new Array();
array_request.dv  = new Array();
array_request.tit = new Array();

var xmlhttp2; 
try{xmlhttp2=new XMLHttpRequest();}catch(ee){try{xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");}catch(E){xmlhttp2=false;}}}
function ajaxHTML(id,url) {
	//alert("ajaxHTML("+id+","+url+")");
    document.getElementById(id).innerHTML="Carregando...";
	fila[fila.length]=[id,url];
    if((ifila+1)==fila.length)ajaxRun();
}

function writeDIV(id,conteudo) {
	document.getElementById(id).innerHTML=conteudo;
}
function ajaxRun(){
    xmlhttp2.open("GET",fila[ifila][1],true);
    xmlhttp2.onreadystatechange=function() {
        if (xmlhttp2.readyState==4){
            //retorno=unescape(xmlhttp2.responseText.replace(/\+/g," "))
            retorno=unescape(xmlhttp2.responseText);
            document.getElementById(fila[ifila][0]).innerHTML=retorno
            ifila++
            if(ifila<fila.length)setTimeout("ajaxRun()",20)
        }
    }
    xmlhttp2.send(null)
}

function init_ajax_combo() {
	//alert('init_ajax_combo()')
	array_request = new Object();
	array_request.totalItens = 0;
	array_request.index = 0;
	array_request.cmb = new Array();
	array_request.ra  = new Array();
	array_request.pv  = new Array();
	array_request.dv  = new Array();
	array_request.tit = new Array();	
}
function next_ajax_combo() {
	if (array_request.index < array_request.totalItens) {		
		setTimeout("preenche_combo()",20);		
	} /*else if (array_request.index == 0 && array_request.totalItens > 1) {
		init_ajax_combo();
	}*/
}
var array_request = false;

function ajax_combo(combo, remote_action, post_vars, title, default_value) {
	//alert("ajax_combo("+combo+", "+remote_action+", "+post_vars+", "+title+", "+default_value+");\nindex: "+array_request.index+"\ntotalItens: "+array_request.totalItens);
	if (!array_request) init_ajax_combo();
	var cc = 0;
	document.getElementById(combo).length = 0;
	document.getElementById(combo).options[0] = new Option('Carregando...','');
	array_request.cmb.push(combo);
	array_request.ra.push(remote_action);
	array_request.pv.push(post_vars);
	array_request.dv.push(((!default_value || default_value=='')?(""):(default_value)));
	array_request.tit.push(title);
	array_request.totalItens++;
	if ((array_request.index+1) == array_request.totalItens || (array_request.index) == array_request.totalItens) {
		preenche_combo();
	} else {
		//alert('NAO INICIOU');
	}	
}

function preenche_combo() {
	//alert('preenche_combo();');
	var pp = array_request.index;
	//var combo = array_request.cmb[pp];
	var remote_action = array_request.ra[pp];
	var post_vars 	  = array_request.pv[pp];
	var title 		  = array_request.tit[pp];
	var default_value = array_request.dv[pp];
	var cb 			  = document.getElementById(array_request.cmb[pp]);
	//var msg_carregando = document.getElementById('msg_carregandof');
	if (!cb) {
		alert('ComboBox Inválida !');
		array_request.index++;
		next_ajax_combo();
		return;
	}
	var str_url = ajax_gw+"?acao="+remote_action;
	if (post_vars) {
		for (var s in post_vars) {
			str_url += "&"+s+"="+post_vars[s];
		}
	}
	var sel_index = false;
	//msg_carregando.innerHTML='Carregando...';
	xmlhttp.open("GET", str_url, true);
	xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			array_request.index++;
			retorno = xmlhttp.responseText;
			//alert(retorno);
			dataProvider = new Function("return "+retorno)();
			//alert('TotalRows: '+dataProvider.totalRows);
			if (title && title != "") {
				cb.options[0] = new Option(title,'');
			}
			if (dataProvider.totalRows < 1) {
				reset_combo(cb);
				return;
			}
			for (var i=0;i<dataProvider.totalRows;i++) {
				if (title && title != "") {
					ii = i+1;
				} else {
					ii = i;
				}
				index = dataProvider.registros[i][1];
				valor = dataProvider.registros[i][0];
				if (default_value != "") {
					if ((valor.toLowerCase() == default_value.toLowerCase()) || (index.toLowerCase() == default_value.toLowerCase())) {
						sel_index = ii;
					}
				}
				if (valor.substring(0,1)=='#') {
					cb.options[ii] = new Option(valor.substring(1,valor.length),index);
					cb.options[ii].className = 'grupo';
				} else {
					cb.options[ii] = new Option(valor,index);
				}
			}
			
			if (sel_index != false) {
				//alert('sel_index: '+sel_index+'  default: '+default_value);
				cb.selectedIndex = sel_index;
			}
			next_ajax_combo();
		}
	}
	xmlhttp.send(null);
}
function reset_combo(cb_id) {
	if (!cb_id || cb_id == "") {
		return false;	
	}
	var cb = document.getElementById(cb_id);
	cb.length = 0;
	cb.options[0] = new Option('-------','');
}

function deleteVeiculo (veiculo_id) {
	  hr_deleteVeiculo = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         hr_deleteVeiculo = new XMLHttpRequest();
         if (hr_deleteVeiculo.overrideMimeType) {
            hr_deleteVeiculo.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            hr_deleteVeiculo = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               hr_deleteVeiculo = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!hr_deleteVeiculo) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  
	  var str_url = ajax_gw + "?acao=deleteVeiculo&id=" + veiculo_id;
	  
	  hr_deleteVeiculo.open("GET", str_url, true);
	  hr_deleteVeiculo.onreadystatechange = function() {
		if (hr_deleteVeiculo.readyState==4)  {
			if (hr_deleteVeiculo.responseText == "SUCCESS") {
				alert('VEÍCULO REMOVIDO COM SUCESSO!');	
				deleteVeiculo_onLoad(veiculo_id);
				return true;
			} else {
				alert("Erro: "+hr_deleteVeiculo.responseText);
				return false;
			}
		}
	  }
	  hr_deleteVeiculo.send(null);
}

function deleteImage(veiculo_id, field_image) {
	  hr_deleteImage = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         hr_deleteImage = new XMLHttpRequest();
         if (hr_deleteImage.overrideMimeType) {
            hr_deleteImage.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            hr_deleteImage = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               hr_deleteImage = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!hr_deleteImage) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  var str_url = ajax_gw + "?acao=deleteImage&id=" + veiculo_id + "&field=" + field_image;
	  //alert("deleteImage URL: "+str_url);
	  hr_deleteImage.open("GET", str_url, true);
	  hr_deleteImage.onreadystatechange = function() {
		if (hr_deleteImage.readyState==4)  {
			if (hr_deleteImage.responseText == "SUCCESS") {
				alert('IMAGEM REMOVIDA COM SUCESSO!');	
				deleteImage_onLoad(veiculo_id);
				return true;
			} else {
				alert("Erro: "+hr_deleteImage.responseText);
				return false;
			}
		}
	  }
	  hr_deleteImage.send(null);
}

function msgcarregando_show() {
	if (document.getElementById('msg_carregando')) {
		document.getElementById("msg_carregando").style.visibility = "visible";
	}
}
function msgcarregando_hide() {
	if (document.getElementById('msg_carregando')) {
		document.getElementById("msg_carregando").style.visibility = "hidden";
	}
}
function ajaxLogin(x){
	var cPost='';
	//document.getElementById('CadastroInfo').style.display='none';
	if (x==1) {
		getCadastroInfo();
		return true;
		usuario=senha=1;
	} else {
		usuario=document.getElementById('REV_USUARIO').value;
		senha=document.getElementById('REV_SENHA').value;
	}
/*
	if (usuario==''){
		alert('Favor preencher o campo Login!');
		document.getElementById('REV_USUARIO').focus();
		return false;
	}
	if (senha==''){
		alert('Favor preencher o campo Senha!');
		document.getElementById('REV_SENHA').focus();
		return false;
	}
*/
	document.getElementById('resposta').innerHTML="Aguarde...";
	//url='getCadastroInfo.php?usuario='+usuario+'&senha='+senha;
	url = 'ajax/gw.cadastro.ajax.php?acao=login';
	//alert(url);
	cPost='usuario='+usuario+'&senha='+senha+'&tipo=1';
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			//alert(xmlhttp.responseText);
			retorno=xmlhttp.responseText;
			local=new Function("return "+retorno)();

			//document.getElementById('resposta').innerHTML=retorno;

			//alert("Status: "+local.status+' - '+local.status_text);
			//document.getElementById('resposta').innerHTML=local.status_text;

			if (local.status==0) {
				document.getElementById('resposta').innerHTML='';
				alert(local.status_text);
				return false;
			} else {
				document.getElementById('resposta').innerHTML=local.status_text;
				document.location='http://www.carrobauru.com.br/webos/extranet/';
				return true;
			}

			//document.getElementById('CadastroInfo').style.display='list-item';
			//document.getElementById('CadastroInfoNovo').style.display='none';
			//document.getElementById('CadastroInfoSenha').style.display='none';
			//CadastroInfo=local.CadastroInfo;
			//getCadastroInfo();
		}
	}
    xmlhttp.send(cPost);
}
function ajaxLoginPart(x){
	var cPost='';
	//document.getElementById('CadastroInfo').style.display='none';
	if (x==1) {
		getCadastroInfo();
		return true;
		usuario=senha=1;
	} else {
		usuario=document.getElementById('PAR_USUARIO').value;
		senha=document.getElementById('PAR_SENHA').value;
	}
	if (usuario==''){
		alert('Favor preencher o campo Login!');
		document.getElementById('PAR_USUARIO').focus();
		return false;
	}
	if (senha==''){
		alert('Favor preencher o campo Senha!');
		document.getElementById('PAR_SENHA').focus();
		return false;
	}
	document.getElementById('respostaP').innerHTML="Aguarde...";
	//url='getCadastroInfo.php?usuario='+usuario+'&senha='+senha;
	url=ajax_gw+'?acao=login';
	cPost='usuario='+usuario+'&senha='+senha+'&tipo=3';
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=unescape(xmlhttp.responseText);
			local=new Function("return "+retorno)();
 			if (local.status==0) {
				document.getElementById('respostaP').innerHTML='';
				alert(local.status_text);
				return false;
			} else {
				document.getElementById('respostaP').innerHTML=local.status_text;
				//document.location='/webos/extranet/';
				return true;
			}
			//document.getElementById('CadastroInfo').style.display='list-item';
			//document.getElementById('CadastroInfoNovo').style.display='none';
			//document.getElementById('CadastroInfoSenha').style.display='none';
			//CadastroInfo=local.CadastroInfo;
			//getCadastroInfo();
		}
	}
    xmlhttp.send(cPost);
}
//==============================================================
   http_request = false;
   gateway_url = ajax_gw;
   function makeRequest(action, method, parameters, phpfile) {
	  //alert('makeRequest('+action+','+method+', '+parameters+')');
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  //alert("parameters: "+parameters);
	  qs = "?acao="+action;
	  if (method == 'GET') {
		  qs += parameters;
	  }
	  if (!phpfile || phpfile == '') {
		  phpfile = gateway_url;
	  }
      http_request.open(method, phpfile + qs, true);
	  http_request.onreadystatechange = function() {
		   if (http_request.readyState==4) {
			   	fonload = eval(action+"_onLoad");
				fonload(unescape(http_request.responseText));
				return true;
		   }
	  }
	  if (method == "POST") {
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	  	http_request.send(parameters);
	  } else {
		  http_request.send(null);
	  }
   }
   
   function SubmitForm(form, action, method, phpfile) {
	   if (!phpfile) phpfile='';
	  //alert('get('+obj+', '+fonload+')');
      var getstr = "&";
      for (i=0; i<form.elements.length; i++) {
		 	var type = form.elements[i].type;
			if (type) {
				var name = form.elements[i].name.replace('!','');
				//if (type != "checkbox") alert('type: '+type);
				
				if (type == "text" || type == "hidden" || type == "password" || type == "textarea") {
				   getstr += name + "=" + form.elements[i].value + "&";
				}
				
				if (type == "checkbox") {
				   if (form.elements[i].checked) {
					  getstr += name + "=" + form.elements[i].value + "&";
				   }
				}
				
				if (type == "radio") {
				   if (form.elements[i].checked) {
					  getstr += name + "=" + form.elements[i].value + "&";
				   }
				}
			  
				if (type == "select" || type == "select-one") {
					getstr += name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
				}
			}
         
      }
	  //alert(action+', '+ method+', '+ getstr);
      makeRequest(action, method, getstr, phpfile);
   }
//==============================================================
function ajaxLembraSenha(){
	var cPost='';
	document.getElementById('respostaS').innerHTML="Aguarde...";
	usuario	= document.getElementById('EMAIL_SENHA').value;
	if (usuario==''){
		alert('Favor preencher o campo email!');
		document.getElementById('respostaS').innerHTML="";
		document.getElementById('EMAIL_SENHA').focus();
		return false;	
	}
	//url='ajax/gw.cadastro.ajax.php?acao=lembrete';
	url = ajax_gw + '?acao=lembrete';
	cPost='usuario='+usuario;
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=unescape(xmlhttp.responseText);
			local=new Function("return "+retorno)();
			//document.getElementById('respostaS').innerHTML=local.status_text;
			if (local.status==0) {
				alert(local.status_text);
				document.getElementById('respostaS').innerHTML="";
				return false;
			}
			alert(local.status_text);
			document.getElementById('respostaS').innerHTML="";
			document.getElementById('EMAIL_SENHA').value='';
			Expande('box_lembra_senha');
			return true;
		}
	}
    xmlhttp.send(cPost);
}

// 1 -> busca rapida
// 2 -> busca avancada

function formBusca(i){

	if(i==2){
		_cidade		= document.getElementById('CIDADE_IMOVEL');
		_tipo		= document.getElementById('TIPO_NEG2');
		_finalidade	= document.getElementById('FINALIDADE2');
		_imovel		= document.getElementById('IMOVEL2');
		_valor		= document.getElementById('VALOR2');
		_uf     = document.getElementById('UF_IMOVEL');
		_dormitorios = document.getElementById('DORMITORIOS');
		_garagem	= document.getElementById('GARAGEM');
		
		qs_form = "?TIPO_BUSCA=savancada";

		if ( _cidade.value != 0) { qs_form += "&CIDADE="+encodeURI(_cidade.value); }
		if ( _uf.value != 0) { qs_form += "&UF_IMOVEL="+_uf.value; }
		if ( _tipo.selectedIndex != 0) { qs_form += "&TIPO_NEGOCIO="+_tipo.value; } else { alert('Favor preencher um Tipo de Negócio!'); _tipo.focus(); return false;}
		if ( _finalidade.selectedIndex != 0) { qs_form += "&FINALIDADE="+_finalidade.value; }  else { alert('Favor preencher uma Finalidade!'); _finalidade.focus(); return false;}
		if ( _imovel.selectedIndex != 0) { qs_form += "&TIPO_IMOVEL="+_imovel.value; } else { alert('Favor preencher um Tipo de Imóvel!'); _imovel.focus(); return false;}
		if ( _valor.selectedIndex != 0) { qs_form += "&VALOR="+_valor.value; }
		if ( _dormitorios.selectedIndex != 0) { qs_form += "&DORMITORIOS="+_dormitorios.value; }
		if ( _garagem.selectedIndex != 0) { qs_form += "&GARAGENS="+_garagem.value; }
	
		
	} else {
		_cidade		= document.getElementById('CIDADE');
		_tipo		= document.getElementById('TIPO_NEG');
		_finalidade	= document.getElementById('FINALIDADE');
		_imovel		= document.getElementById('IMOVEL');
		_valor		= document.getElementById('VALOR');
		_bairro		= document.getElementById('BAIRRO');
		_placa      = document.getElementById('PLACA');

		qs_form = "?TIPO_BUSCA=srapida";
		
		if(_placa.value != ""){
		qs_form += "&PLACA="+_placa.value;			
		} else {
			if ( _tipo.selectedIndex != 0) { qs_form += "&TIPO_NEGOCIO="+_tipo.value; } else { alert('Favor preencher um Tipo de Negócio!'); _tipo.focus(); return false;}
			if ( _finalidade.selectedIndex != 0) { qs_form += "&FINALIDADE="+_finalidade.value; }  else { alert('Favor preencher uma Finalidade!'); _finalidade.focus(); return false;}
			if ( _imovel.selectedIndex != 0) { qs_form += "&TIPO_IMOVEL="+_imovel.value; } else { alert('Favor preencher um Tipo de Imóvel!'); _imovel.focus(); return false;}
			if ( _valor.selectedIndex != 0) { qs_form += "&VALOR="+_valor.value; }
			if ( _bairro.selectedIndex != 0) { qs_form += "&BAIRRO="+encodeURI(_bairro.value); }
		}
	
	}


	ajaxHTML('conteudo','busca.inc.php'+qs_form);
	return true;
}

function formBuscaPlaca(){
	_placa		= document.getElementById('PLACA');

	if ( _placa.value != '') { 
		qs_form = "?PLACA="+_placa.value; 
	} else { 
		alert('Favor preencher a Placa!'); 
		_placa.focus(); 
		return false;
	}
	ajaxHTML('conteudo','busca.inc.php'+qs_form);
	return true;
}

function formBuscaImobiliaria(){
	_imobiliaria		= document.getElementById('IMOBILIARIA');

	if ( _imobiliaria.value != '') { 
		qs_form = "?IMOBILIARIA="+_imobiliaria.value; 
	} else { 
		alert('Favor Selecionar a Imobiliária!'); 
		_imobiliaria.focus(); 
		return false;
	}
	ajaxHTML('conteudo','busca.inc.php'+qs_form);
	return true;
}