
// 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 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(){
	var cPost='';
		usuario=document.getElementById('lUsuario').value;
		senha=document.getElementById('lSenha').value;
		serie=document.getElementById('lSerie').value;

//	document.getElementById('resposta').innerHTML="Aguarde...";
	url = 'ajax/gw.cadastro.ajax.php?acao=login';
	cPost='usuario='+usuario+'&senha='+senha+'&tipo=1&serie='+serie;
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=xmlhttp.responseText;
			local=new Function("return "+retorno)();

			if (local.status==0) {
//				document.getElementById('resposta').innerHTML='';
				alert(local.status_text);
				return false;
			} else {
//				document.getElementById('resposta').innerHTML=local.status_text;
				//ajaxHTML('divLogin','login.php');
				//if(usuario == 'hibris')
				ajaxHTML('meio_conteudo','copa.php?serie='+serie);
				ajaxHTML('FormLogin','login.inc.php?serie='+serie)
				//else
					//alert('Login Indisponível temporáriamente!');
				//document.location='http://www.recordbauru.com.br/webos/extranet/';
				return true;
			}
		}
	}
    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){
	_cidade		= document.getElementById('CIDADE');
	_tipo		= document.getElementById('TIPO_NEG');
	_finalidade	= document.getElementById('FINALIDADE');
	_imovel		= document.getElementById('IMOVEL');
	_valor		= document.getElementById('VALOR');

	if (i==2) {
		_dormitorios= document.getElementById('DORMITORIOS');
		_garagem	= document.getElementById('GARAGEM');
		_bairro		= document.getElementById('BAIRRO');
		qs_form 	= "?TIPO_BUSCA=savancada";
	} else {
		qs_form 	= "?TIPO_BUSCA=srapida";
	}
	
	if ( _cidade.selectedIndex != 0) { qs_form += "&CIDADE="+_cidade.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 (i==2) {
		if ( _dormitorios.selectedIndex != 0) { qs_form += "&DORMITORIOS="+_dormitorios.value; }
		if ( _garagem.selectedIndex != 0) { qs_form += "&GARAGENS="+_garagem.value; }
		if ( _bairro.selectedIndex != 0) { qs_form += "&BAIRRO="+_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;
}