// Função para CARREGAR todas as IMAGENS ANTES DE SEREM VISUALIZADAS no site
function loadImages()
{
    var img1 = new Image();
    img1.src="img/bt_buscar_clique.gif";
    var img2 = new Image();
    img2.src="img/aviso.gif";
    var img3 = new Image();
    img3.src="img/aviso_ok.gif";
    var img4 = new Image();
    img4.src="img/bt_parar_slideshow.gif";
}

//--------------------------------------------------------------------------------------//
/* administra os eventos dos botões do site */
//--------------------------------------------------------------------------------------//
var btn =
{
	/* aplica uma transparencia no botão quando o mouse estiver em cima dele */
	'sobre_btn': function(id)
	{
		document.getElementById(id).style.opacity = '0.9';
		/* para IE */
		document.getElementById(id).style.filter = 'alpha(opacity=90)';
	},
	
	/* retira a transparencia do botão quando o mouse estiver fora dele */
	'fora_btn': function(id)
	{
		document.getElementById(id).style.opacity = '1';
		/* para IE */
		document.getElementById(id).style.filter = 'alpha(opacity=100)'; 
	},
	
	//Função chamado no EVENTO ONMOUSEDOWN do BOTÃO BUSCAR
	'clica_buscar': function()
	{
		document.getElementById('bt_buscar').src='img/bt_buscar_clique.gif';
		document.getElementById('bt_buscar').style.marginLeft='1px';
		document.getElementById('bt_buscar').style.marginTop='1px';
	},
	
	//Função chamado no EVENTO ONMOUSEUP do BOTÃO BUSCAR
	'solta_clique_buscar': function()
	{
		document.getElementById('bt_buscar').src='img/bt_buscar.gif';
		document.getElementById('bt_buscar').style.marginLeft='0px';
		document.getElementById('bt_buscar').style.marginTop='0px';
	},
	
	/*Função chamada no EVENTO ONMOUSEOVER do botão BUSCA(na página de resultado de pesquisa esse botão abre a box para fazer nova pesquisa)*/
	'sobre_novaBusca': function()
	{
		document.getElementById('nova_busca').style.textDecoration = 'underline';
	},

	/*Função chamada no EVENTO ONMOUSEOUT do botão BUSCA(na página de resultado de pesquisa esse botão abre a box para fazer nova pesquisa)*/
	'fora_novaBusca': function()
	{
		document.getElementById('nova_busca').style.textDecoration = 'none';
	},
	
	/*Função chamada no EVENTO ONCLICK do botão BUSCA(abre a box para realizar nova pesquisa na página de resultados de alguma pesquisa)*/
	'abre_novaBusca': function ()
	{
		document.getElementById('nova_busca_box').style.display = 'block';
	},
	
	//Função para ENVIAR FORMULÁRIO quando CLICAR em um BOTÃO (só precisa ser passado no PARÂMETRO ID do FORM)
	'acao_subm': function (idform)
	{
		document.getElementById(idform).submit();
	}

}

//--------------------------------------------------------------------------------------//
//administra os eventos da busca de imóveis
//--------------------------------------------------------------------------------------//
var busca = 
{
	//Função para DESABILITAR o SELECT de DORMITÓRIOS DEPENDENDO do TIPO DE IMÓVEL SELECIONADO
	'desabilita_dorm' : function ()
	{
		if(document.getElementById('tipo').value == '2' || document.getElementById('tipo').value == '5' || document.getElementById('tipo').value == '6' || document.getElementById('tipo').value == '8' || document.getElementById('tipo').value == '9' || document.getElementById('tipo').value == '10' || document.getElementById('tipo').value == '11' || document.getElementById('tipo').value == '12' || document.getElementById('tipo').value == '13' || document.getElementById('tipo').value == '14' || document.getElementById('tipo').value == '17' || document.getElementById('tipo').value == '18' )
		{
			document.getElementById('dorm').disabled = "disabled";
			document.getElementById('dorm').value = "";
		}
		else
		{
			document.getElementById('dorm').disabled = "";
		}
	}
}

//--------------------------------------------------------------------------------------//
// administra os eventos do formulário de contato
//--------------------------------------------------------------------------------------//
var contato =
{
		//Função de VALIDAÇÃO do FORMULÁRIO DE CONTATO	
		'validar' : function () 
		{
			
			//se nome estiver vazio
			if(document.getElementById('nome').value == "") 
			{
				document.getElementById('respostaContato').style.display='block';
				document.getElementById('respostaContato').innerHTML= 'Você precisa digitar o seu nome!';
				document.getElementById('nome').style.backgroundColor='#FDF9EF';
				document.getElementById('email').style.backgroundColor='#FFFFFF';
				document.getElementById('mensagem').style.backgroundColor='#FFFFFF';
				document.getElementById('respostaContato').style.backgroundImage= 'url(img/aviso.gif)';
				document.getElementById('nome').focus();
				return false;
			}
			
			if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById('formContato').email.value))
			{
			}else
			{
				//se email estiver vazio
				if(document.getElementById('email').value == "") 
				{
					document.getElementById('respostaContato').style.display='block';
					document.getElementById('respostaContato').innerHTML= 'Você precisa digitar o seu email!';
					document.getElementById('email').style.backgroundColor='#FDF9EF';
					document.getElementById('nome').style.backgroundColor='#FFFFFF';
					document.getElementById('mensagem').style.backgroundColor='#FFFFFF';
					document.getElementById('respostaContato').style.backgroundImage= 'url(img/aviso.gif)';
					document.getElementById('email').focus();
					return false;
				} else
				{
					document.getElementById('respostaContato').style.display='block';
					document.getElementById('respostaContato').innerHTML= 'Você não digitou corretamente o seu email!';
					document.getElementById('email').style.backgroundColor='#FDF9EF';
					document.getElementById('nome').style.backgroundColor='#FFFFFF';
					document.getElementById('mensagem').style.backgroundColor='#FFFFFF';
					document.getElementById('respostaContato').style.backgroundImage= 'url(img/aviso.gif)';
					document.getElementById('email').focus();
					return false;
				}
			 					
			}
			
			
			//se mensagem estiver vazio
			if(document.getElementById('mensagem').value == "" ) 
			{
				document.getElementById('respostaContato').style.display='block';
				document.getElementById('respostaContato').innerHTML= 'Você precisa digitar a mensagem!';
				document.getElementById('mensagem').style.backgroundColor='#FDF9EF';
				document.getElementById('nome').style.backgroundColor='#FFFFFF';
				document.getElementById('email').style.backgroundColor='#FFFFFF';
				document.getElementById('respostaContato').style.backgroundImage= 'url(img/aviso.gif)';
				document.getElementById('mensagem').focus();
				return false;
			}
			else
			{
				//envia formulário
				document.getElementById('formContato').submit();
			}
			
		},
		
		
		//função para limpar o formulário
		'limpar': function ()
		{
			$('#formContato')[0].reset();
			document.getElementById('nome').style.backgroundColor='#FFFFFF';
			document.getElementById('email').style.backgroundColor='#FFFFFF';
			document.getElementById('telefone').style.backgroundColor='#FFFFFF';
			document.getElementById('cidade_uf').style.backgroundColor='#FFFFFF';
			document.getElementById('mensagem').style.backgroundColor='#FFFFFF';
			document.getElementById('respostaContato').innerHTML= ' ';
			document.getElementById('respostaContato').style.backgroundImage='none';
		},
		
		
		'msg_enviada': function()
		{
		    document.getElementById('respostaContato').innerHTML= 'E-mail enviado com sucesso!';
		    document.getElementById('respostaContato').style.backgroundImage='url(img/aviso_ok.gif)';
			return true;
		},
		
		'msg_nao_enviada': function()
		{
		    document.getElementById('respostaContato').style.display='block';
		    document.getElementById('respostaContato').innerHTML= 'Ocorreu um erro no envio do email!';
		    document.getElementById('respostaContato').style.backgroundImage='url(img/aviso.gif)';
		}
		
}


var Menu = {
	
	'loadCH': function(tipo){
		if(tipo==3 || tipo==5 || tipo==8){
			document.getElementById('ch').disabled = false;
		
		}
		else{
			document.getElementById('ch').checked = false;
			document.getElementById('ch').disabled = true;
		}
		if(tipo==1 || tipo==3 || tipo==4){
			document.getElementById('dorm').disabled = false;
		
		}
		else{
			document.getElementById('dorm').disabled = true;
		}
		
	},
	
	'loadTipos' : function (finalidade,tipoSelecionado)
	{
		$("#div_tipos").load('load_tipos.php?f=' + finalidade + '&t=' + tipoSelecionado);
	}
}

var menuHeader = {

	'Buscar': function(url){
		
		loadAjax('result.php?cmd=buscar&' + url, 'column-rigth', null, null);
		
	}
	
}

//--------------------------------------------------------------------------------------//
//ADMINISTRA os EVENTOS de MAIS DETALHES de IMÓVEL
//--------------------------------------------------------------------------------------//
var maisDetalhes =
{
	//Função para DESTACAR foto(MINIATURA) quando o mouse estiver sobre ela(ONMOUSEOVER)
	'destacaThumb': function (id)
	{
		document.getElementById(id).style.borderColor = '#F05000';
		document.getElementById(id).style.opacity = '1';
		/* para IE */
		document.getElementById(id).style.filter = 'alpha(opacity=100)';
	},
	
	//Função para normalizar foto(MINIATURA) quando o mouse estiver fora dela(ONMOUSEOUT)
	'normalizaThumb': function (id)
	{
		document.getElementById(id).style.borderColor = '#A9A9A9';
		document.getElementById(id).style.opacity = '0.7';
		/* para IE */
		document.getElementById(id).style.filter = 'alpha(opacity=70)';
	},
	
	/*Função para AMPLIAR uma foto(MINIATURA), evento ONCLICK. 
	  PARÂMETROS: SRC da imagem, legenda e sua posição(contador)  */ 
	'amplia_foto': function (src,legenda,pos)
	{
		document.getElementById('legenda').innerHTML = legenda;
		document.getElementById('img_ampliada').src=src;
		$('#img_ampliada').attr({ name:pos }); 
		// adiciona a classe com a posição da imagem em img_ampliada
	}
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth - 18;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

$(document).ready
(
	function()
	{
		$("#telefone").mask("(99) 9999-9999");
	}
)

///AJAX GERAL
var reqs = new Array();

function uncache(url)
{
	var d = new Date();
	var time = d.getTime();

	if (new String(url).indexOf("?") < 0)
		strurl = "?";
	else
		strurl = "&";

	url = url + strurl + 'timecache=' + time;
	return url;
} 

function CXMLReq(type, xmlhttp, target, func)
{
	this.type = type;
	this.xmlhttp = xmlhttp; 
	this.target = target;
	this.func = func;
}

function mostraLog(msg)
{
	if ($('logErros'))
		$('logErros').innerHTML += msg + '<br>';
}

function jah(url, target, func, msg) {
   mostraLog('jah: url->' + url + ', target->' + target + ', func->' + func + ', msg->' + msg);
   var xhr = false;
   // native XMLHttpRequest object
	if (msg)
		mensagem = msg;
	else
		mensagem = 'Aguarde, carregando...';
   // $(target).innerHTML = mensagem;
   if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {jahDone();};
        xhr.open("GET", url, true);
        xhr.send(null);
    // IE/Windows ActiveX version
   } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
        if (xhr) {
            xhr.onreadystatechange = function() {jahDone();};
            xhr.open("GET", uncache(url), true);
            xhr.send();
        }
   }
   
   var xmlreq = new CXMLReq('', xhr, target, func);
   reqs.push(xmlreq);
}    

function loadAjax(url, target, msg, func) {
	mostraLog('jah: url->' + url + ', target->' + target + ', func->' + func + ', msg->' + msg);
	var xhr = false;
	// native XMLHttpRequest object
	if(msg !== null){
		if(msg)
			mensagem = '<div id="loading" style="font-size:12px;"><img src="img/ajax-loader.gif" align="absmiddle">&nbsp;' + msg + '</div>';
		else
			mensagem = '<div id="loading"><img src="img/ajax-loader.gif" align="absmiddle">&nbsp;Aguarde, carregando...</div>';
		$(target).innerHTML = mensagem;
	}
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() {jahDone();};
		xhr.open("GET", url, true);
		xhr.send(null);
		// IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
		if (xhr) {
			xhr.onreadystatechange = function() {jahDone();};
			xhr.open("GET", uncache(url), true);
			xhr.send();
		}
	}
	
	var xmlreq = new CXMLReq('', xhr, target, func);
	reqs.push(xmlreq);
}    

function jahDone() {
	if (typeof(window['reqs']) == "undefined") return;
	// only if req is "loaded"
	for (var req=0; req<reqs.length; req++)
	{
		if (reqs[req].xmlhttp.readyState == 4) {
			// only if "OK"
			results = reqs[req].xmlhttp.responseText;
			target = reqs[req].target;
			func = reqs[req].func;
			statusText = reqs[req].xmlhttp.statusText;
			if (reqs[req].xmlhttp.status == 200 || reqs[req].xmlhttp.status == 304) {
				reqs.splice(req,1); req --;
				o = $(target);
				o.innerHTML = results;
				if (haveJS(o))
					execJS(o);
				if (func)
					eval(func);
			} else {
				$(target).innerHTML="jah erro:\n" + statusText;
				reqs.splice(req,1); req --;
			}
		}
	}
}

var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bMoz = (navigator.appName == 'Netscape');

function haveJS(node)
{
  var st = node.getElementsByTagName('SCRIPT');
  if (st.length > 0)
  	return true;
  else
    return false;
}

function execJS(node) 
{
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;
  for(var i=0;i<st.length; i++) {
	if (bSaf) {
	  strExec = st[i].innerHTML;
	}
	else if (bMoz) {
	  strExec = st[i].textContent;
	}
	else {
	  strExec = st[i].text;
	}
	try {
	  //mostraLog('chamando isso:' + strExec);
	  eval(strExec);
	} catch(e) {
	  alert(strExec);
	  if (window.ActiveXObject)
		  alert(e.description);
	  else
	  	  alert(e);
	}
  }
}