// JavaScript Document
	//var abas = new Array("home","ofertasE","ofertasI","anunciar","dicas","contato");
	var outraJanela = null;
	var config = null;
	var tipo = null;
	var baseURL = "admin/";

	function LOG(msg) {
		document.getElementById("loadStatus").innerHTML = msg;
	}
	
	function trim(str) {
		while (str.charAt(0) == " ")
			str = str.substr(1, str.length-1);
		
		while (str.charAt(str.length-1) == " ")
			str = str.substr(0, str.length-1);
		
		return str;
	}
	
	function numero2moeda(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
			num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
			cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + 'R$ ' + num + ',' + cents);
	}
	
	function teclaPesquisa(e) {
		if(window.event) // IE
			keynum = e.keyCode
		else 
			if(e.which) // Netscape/Firefox/Opera
				keynum = e.which

		if (keynum == 13) { 
			irPara('ofertas');
			pesquisar();
		}
	}
	
	function tiraAcentos(texto) { // coloca em minusculas, tira acentos e tira plural e substitui algumas abreviações
		var novoTexto = texto.toLowerCase();

		novoTexto = novoTexto.replace(/á/g, 'a');
		novoTexto = novoTexto.replace(/ã/g, 'a');
		novoTexto = novoTexto.replace(/ó/g, 'o');
		novoTexto = novoTexto.replace(/õ/g, 'o');
		novoTexto = novoTexto.replace(/é/g, 'e');
		novoTexto = novoTexto.replace(/í/g, 'i');
		novoTexto = novoTexto.replace(/ç/g, 'c');

		novoTexto = novoTexto.replace("sbc", "bernardo");
		novoTexto = novoTexto.replace("sp",  "paulo");
		novoTexto = novoTexto.replace("scs", "caetano");
		
		if (novoTexto.indexOf(" ") == -1 && novoTexto.charAt(novoTexto.length-1) == 's') novoTexto = novoTexto.substring(0,novoTexto.length-1);

		return novoTexto;
	}
	
	function irPara(aba) {
		var items = document.getElementById("menu").childNodes;
		for (var i = 0; i < items.length; i++) 
			if (items[i].nodeType == 1) {
				document.getElementById(items[i].getAttribute("aba")).style.display = "none";
				items[i].className = "off";
			}
	
		document.getElementById(aba.getAttribute("aba")).style.display = "block";
		aba.className = "on";
		e = document.getElementById("anima");
		if (aba.getAttribute("aba") == "home") {
			e.src = "";
			e.style.display = "none";
		} else {
			e.src = "images/anima.gif";
			e.style.display = "block";
		}
	}
	
	function verDetalhes(index, titulo)
	{
		var url = baseURL+'visualiza.php?site';
		var xmlhttp = createRequestObject();
		var imagens = '';
		if(xmlhttp)
		{
			xmlhttp.open("GET", url+'&id_produto='+index, false);
			xmlhttp.send(null);
			var listaDeFotos = xmlhttp.responseXML.getElementsByTagName("foto");
			for (var i = 0; i < listaDeFotos.length; i++)
				imagens += '<img width="500" height="375" src="../images/1px.gif" style="background:url('+baseURL+'visualiza.php?id='+listaDeFotos[i].getAttribute('id')+') center no-repeat"><br><br>';
		}
		
		if (listaDeFotos.length == 0)
			return alert('Nenhuma foto para esse item');
		
		try
		{
			if (outraJanela != null)
				outraJanela.close();
			var LEFT = (screen.width/2)-(640/2);
			var TOP = (screen.height/2)-(480/2);
			outraJanela = window.open("about:blank","Detalhes","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=700,height=480,left="+LEFT+",top="+TOP);

			var result = ''
				+'<html>'
				+'<title>Detalhes</title>'
				+'<link href="styles/estilo.css" rel="stylesheet" type="text/css">'
				+'<body style="background-color:#FFFFFF;margin:10px">'
				+'  <h2 class="enfase">'+titulo+'</h2>'
				+'  <hr width="75%">'
				+'  <p align="center">'+imagens+'</p>'
				+'<div style="text-align:right;width:100%;display:block;" class="enfase">Ficou interessado? Então ligue agora<br>para: '+getPropriedade("telefone")+'</div><br>'
				+'</body></html>';
			
			outraJanela.document.writeln(result);
		}
		catch (e)
		{
			alert('Não foi possível abrir uma nova janela. Tente desabilitar o bloqueador de popups.');
		}
	}
	
	function createRequestObject(){
		var req = false;
		
		if(window.XMLHttpRequest){
			req = new XMLHttpRequest();
			
			if(req.overrideMimeType){
				req.overrideMimeType("text/xml; charset=ISO-8859-1"); //utf-8 iso-8859-1
			}
		} 
		else if(window.ActiveXObject){
			try{ req = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(e){
				try{ req = new ActiveXObject("Microsoft.XMLHTTP"); }
				catch(e){}
			}
		}
		
		if(!req){
			alert("Não foi possível executar a pesquisa. Tente habilitar javascript.");
			return false;
		}
		else{ return req; }	
	}
	
	function carregaConfig() {
		var url = baseURL+"config.php?site";
		var xmlhttp = createRequestObject();
		if(xmlhttp){
			xmlhttp.open("GET", url, false);
			xmlhttp.send(null);
			config = xmlhttp.responseXML;
		}
	}
	function getPropriedade(nome) {
		var result = null;
		if (config == null)
			carregaConfig();
		
		var listaDeProp = config.getElementsByTagName('config');
		for (var i = 0; i < listaDeProp.length; i++)
			if (listaDeProp[i].getAttribute('nome') == nome)
				result = listaDeProp[i].getAttribute('valor');
			
		if (result)
			return result;
		else
			return "";
	}
	
	function carregaDicas(cols) { // cols é o número de colunas por linha
		var result = '<tr>';
		var url = baseURL+'dica.php?site';
		var xmlhttp = createRequestObject();
		if(xmlhttp)
		{
			xmlhttp.open("GET", url, false);
			xmlhttp.send(null);
			var listaDeDicas = xmlhttp.responseXML.getElementsByTagName("dica");
			
			for (var i = 0; i < listaDeDicas.length; i++)
			{
				var dica = listaDeDicas[i];
				var Link = dica.getAttribute('link');
				
				result += '<td class="dica">'
							 + '<div class="enfase">'+dica.getAttribute('titulo')+'</div>'
							 + '<br>'+dica.getAttribute('texto')
							 + ((Link!='')?'<p align=right><a class="linkDica" href="'+((Link.indexOf('www')==0)?'http://'+Link:Link)+'">'+Link+'</p>':'')
							 + '</td>';
				
				if ((i+1)%cols == 0)
					result += '</tr><tr>';
			}
		}
		return result+'</tr>';
	}
	
	function carregaRamos(isAdmin)
	{
		//limpa o select
		/*var c = document.getElementById("filtro");
		while(c.options.length > 0) c.options[0] = null;
		c.options[0]=new Option(" -- Aguarde ... -- "," -- Aguarde ... -- ");*/
		var url = baseURL+"negocio.php?site=ramo"+(isAdmin?'&admin=true':'');
		var xmlhttp = createRequestObject();
		if(xmlhttp)
		{
			xmlhttp.open("GET", url, true);
		
			xmlhttp.onreadystatechange = function()
				{
					if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
					{
						var element = document.getElementById("filtro_ramo");
						//limpa o select
						while(element.options.length > 1) element.options[1] = null;
						var listaDeTipos = xmlhttp.responseXML.getElementsByTagName("ramo");
						for(var i = 0; i < listaDeTipos.length; i++)
						{
							var ramo = listaDeTipos[i].getAttribute("ramo"); //unescape(tipo);
							element.options[element.options.length] = new Option(ramo, ramo); //tiraAcentos(ramo)
						}
					}
				}
		
			xmlhttp.send(null);
		}
	}
	
	function carregaTipos(isAdmin)
	{
		var url = baseURL+"imovel.php?site=tipo"+(isAdmin?'&admin=true':'');
		var xmlhttp = createRequestObject();
		if(xmlhttp)
		{
			xmlhttp.open("GET", url, true);
		
			xmlhttp.onreadystatechange = function()
				{
					if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
					{
						var element = document.getElementById("filtro_ramo");
						//limpa o select
						while(element.options.length > 1) element.options[1] = null;
						var listaDeTipos = xmlhttp.responseXML.getElementsByTagName("tipo");
						for(var i = 0; i < listaDeTipos.length; i++)
						{
							var tipo = listaDeTipos[i].getAttribute("tipo");
							element.options[element.options.length] = new Option(tipo, tipo);
						}
					}
				}
		
			xmlhttp.send(null);
		}
	}
	
	function formataCampo(tipo, valor)
	{
		switch (tipo)
		{
			case 'texto': return valor;
			case 'moeda': return numero2moeda(valor);
			case 'm2': return valor + ' m<sup>2</sup>';
		}
		return valor;
	}
	
	function mostraResultados(xml)
	{
		var listaDeOfertas = xml.getElementsByTagName("oferta");
		var listaDeCampos = xml.getElementsByTagName("campo");
		var result = '';
		for (var i = 0; i < listaDeOfertas.length; i++)
		{
			result += '<table width="100%">'
				+'	<tr>'
				+'		<td class="resultadoPesquisa">'
				//+'      <a target="_blank" href="'+baseURL+'imovel.php?action=edt&id='+listaDeOfertas[i].getAttribute('id')+'">'
				+'				<span class="enfase" style="font-size:11pt">'+listaDeOfertas[i].getAttribute('anuncio_titulo')+'</span>'
				//+'      </a>'
				+'    </td>'
				+'	  <td style="text-align:right">'
				+'    	<span class="enfase">Preço: '+numero2moeda(listaDeOfertas[i].getAttribute('valor'))+'</span><br><br> '
				+'			'+(listaDeOfertas[i].getAttribute('fotos') == 0 ? '' : '<a href="javascript:void(0);" onClick="verDetalhes('+listaDeOfertas[i].getAttribute('id')+', \''+listaDeOfertas[i].getAttribute('anuncio_titulo')+'\');" class="foto"><img src="images/foto.gif" align="middle" /><br />Veja fotos</a>')
				+'	  </td>'
				+'  </tr>';
			for (var j = 2; j < listaDeCampos.length; j++) // começar do 2 (1 é a sigla, 0 é o publico)
			{
				if (listaDeOfertas[i].attributes[j].value != '')
					result += '<tr><td class="resultadoPesquisa" colspan="2"><b>'
						+listaDeCampos[j].getAttribute('nome')+'</b>: '
						+(j==2?listaDeOfertas[i].getAttribute('sigla')+'-':'')+formataCampo(listaDeCampos[j].getAttribute('tipo'), listaDeOfertas[i].attributes[j].value)+'</td></tr>';
			}
			result += '</table><hr />';
		}
		
		var target = document.getElementById('resultados');
		target.innerHTML = '<br><div>Resultados da busca</div><br><hr />';
		if (result != '')
			target.innerHTML += result + '<p>* INFORMAÇÕES FORNECIDAS PELOS PROPRIETÁRIOS VENDEDORES.</p>';
		else
			target.innerHTML += 'Nenhum resultado encontrado. Tente novamente.';
		target.style.display = 'block';
	}
	
	function pesquisar(sender)
	{
		var url = baseURL+"pesquisa_site.php";
		var xmlhttp = createRequestObject();
		var params = 'tipo_prod=' + document.getElementById('tipo_prod').value;
		if (typeof(sender) == 'number')
			params += '&filtro_id='+sender;
		else
		{
			params += '&filtro_ramo=' + escape(document.getElementById('filtro_ramo').value)
						 + '&filtro_valor=' + document.getElementById('filtro_valor').value
						 + '&filtro_valor_max=' + document.getElementById('filtro_valor_max').value
						 + '&filtro_fin=' + document.getElementById('filtro_fin').value;
						 //+ '&filtro_dorm=' + document.getElementById('filtro_dorm').value
						 //+ '&filtro_cidade=' + escape(document.getElementById('filtro_cidade').value)
						 //+ '&filtro_bairro=' + escape(document.getElementById('filtro_bairro').value);
		}
		if(xmlhttp)
		{
			xmlhttp.open("GET", url+'?'+params, true);
			xmlhttp.onreadystatechange = function()
				{
					if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
					{
						mostraResultados(xmlhttp.responseXML);
						LOG("Pesquisa concluída.");
					}
					else
						LOG("Aguarde...");
				}
			xmlhttp.send(null);
		}
	}
	
	function verDestaque(id, tipoProduto)
	{
		//var tipo = tipoProduto=='E'?'Com':'Imo'; //E=estab. com. I=imóvel
		irPara(document.getElementById('m_ofertas'+tipoProduto));
		pesq(tipoProduto);
		pesquisar(id);
		location.href = '#ofertas';
	}