//jquery
//Lightbox
var dominio = "http://adquiraimoveis.net/";

(function($){$.fn.lightBox=function(settings){settings=jQuery.extend({overlayBgColor:'#666666',overlayOpacity:0.6,fixedNavigation:false,imageLoading:dominio+'public/images/lightbox-ico-loading.gif',imageBtnPrev:dominio+'public/images/lightbox-btn-prev.gif',imageBtnNext:dominio+'public/images/lightbox-btn-next.gif',imageBtnClose:dominio+'public/images/lightbox-btn-close.gif',imageBlank:dominio+'public/images/lightbox-blank.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Foto',txtOf:'de',keyToClose:'f',keyToPrev:'a',keyToNext:'p',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<jQueryMatchedObj.length;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
_set_image_to_view();}
function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
$('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
_enable_keyboard_navigation();}
function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
function _disable_keyboard_navigation(){$(document).unbind();}
function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);

function change(a)
{
	var ul = document.getElementById('abas');
	var al = ul.getElementsByTagName('a');
	for(i=0;i<al.length;i++)
		al[i].className = '';
	a.className = 'selected';

	var mostrar = a.getAttribute('rel').toLowerCase();
	$('.ativo').slideUp('normal', function(){ $('#bairro_'+mostrar).slideDown(); });
	$('.ativo').removeClass('ativo');
	$('#bairro_'+mostrar).addClass('ativo');
}

function callback()
{
	$('#bairro_aluguel').slideDown();
}

function filtro(form)
{
	var url = window.location;
	//if (form.ed_tipo.value != '')
		url += '/tipo/'+form.ed_tipo.value;
//	if (form.ed_quartos.value != '')
		url += '/quarto/'+form.ed_quartos.value;
	//if (form.ed_vagas.value != '')
		url += '/vaga/'+form.ed_vagas.value;
		
	window.location = url;
	return false;
}

function bSimples(form)
{
	var url = dominio+'busca/simples';

	if(form.ed_ref.value != 'Código de Referência (opcional)' && form.ed_ref.value != '')
	{
		var regex = /^[0-9]{1,5}-[0-9]{1,2}/
		if(form.ed_ref.value.match(regex))
		{
			var ref = form.ed_ref.value.split('-');
			if(ref[1] != 0)
				url = dominio+'imovel/detalhes';
			else
				url = dominio+'empreendimento/detalhes';
			url += '/referencia/'+ref[0]+'/finalidade/'+ref[1];
			window.location = url;
			return false;
		} else
		{
			Dialog.show({content: 'O código de refência que você forneceu não está correto.'});
			return false;
		}
	}

	for(i=0;i<form.elements.length;i++)
	{
		with(form.elements[i])
		{
			if(type == 'image') continue;
			if(name == 'ed_ref') continue;
			var campo = '';
			var valor = '';
			if(value.trim() != '')
			{
				if(name == 'ed_estado')
					campo = '/uf';
				else
					campo = '/'+name.split('ed_')[1];

				if(name == 'ed_valor_max')
				{
					if(value == 'Valor Máximo (opcional)')
					{
						continue;
					}
					valor = value;
					//valor = value.replace('.','');
					//valor = value.replace(',','.');
				} else
					valor = value.trim();

				url += campo+'/'+valor;
			}
		}
	}
	window.location = url;
	return false;
}

function bAvancada3(form)
{
	var url = dominio+'busca/simples';
	var atributos = '';
	var estabelecimento = '';

	for(i=0;i<form.elements.length;i++)
	{
		with(form.elements[i])
		{
			if(type == 'image') continue;
			if(name == 'ed_ref') continue;
			var campo = '';
			var valor = '';
			if (type != 'checkbox')
			{
				if(value.trim() != '')
				{
					if(name == 'ed_estado')
						campo = '/uf';
					else
						campo = '/'+name.split('ed_')[1];

					if(name == 'ed_valor')
					{
						if(value == 'Valor Máximo (opcional)') continue;
						valor = value.replace('.','');
						valor = value.replace(',','.');
					} else
						valor = value.trim();

					url += campo+'/'+valor;
				}
			}
			else
			{
				if ( $("#"+name+":checked").is(":checked") )
				{
					if(name.substring(0,11)=='ed_atributo')
					{
						if(atributos == '')
							atributos = value;
						else
							atributos += '-'+value;
					}
					else if(name.substring(0,18)=='ed_estabelecimento')
					{
						if(estabelecimento == '')
							estabelecimento = value;
						else
							estabelecimento += '-'+value;
					}
				}
			}
		}
	}
	if (atributos!='')
		url =  url+'/atributo/'+atributos;
	if(estabelecimento!='')
		url = url+'/estabelecimento/'+estabelecimento;
	window.location =url;

	return false;
}

function cliqueDestaque(obj, id)
{
	url = '/busca';
	if(!obj.checked)
		url += '/retira_destaque/id/'+id;
	else
		url += '/coloca_destaque/id/'+id;

	$.get(url, function(res){
		if(res != '1')
		{
			Dialog.show({content: res});
			obj.checked = !obj.checked;
		}
	});
}

function favorito()
{
	document.fcontato.ed_favorito.value=1;
	document.fcontato.submit();
}
function ativa_compara(obj,imovel,finalidade)
{
	checkTr(obj, imovel, finalidade);
}

function buscaOver()
{
	if(document.getElementById('tabela_busca'))
	{
		var tb = document.getElementById('tabela_busca');
		var tr = tb.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
		for(i=0;i<tr.length;i++)
		{
			tr[i].onmouseover = function()
			{
				this.style.backgroundColor = '#F1FFC6';
			}
			tr[i].onmouseout = function()
			{
				if(!this.className.match('checked'))
					this.style.backgroundColor = this.getAttribute('bgcolor');
			}
		}
	}
	else
	{
		$(".im_busca").hover(
			function () {
				$(this).removeClass('im_off');
				$(this).addClass('im_on');
			},
			function () {
				if($(this).attr('checked') == 1) return;
				$(this).removeClass('im_on');
				$(this).addClass('im_off');
			}
		);
	}
}

function tooltip_home(foto, descricao)
{
	descricao += ' (clique e veja mais)';
	html = '<div class="dest_fotodesc"><img src="http://procureimovel.com.br/public/'+foto+'" alt="" />';
	html += '<p>'+descricao+'</p>';
	html += '</div>';
	Tip(html, FOLLOWMOUSE, true);
}


function buscaJson()
{
	var json_url = this.href+'/retorno/ajax';
	var reqSent = false;
	//fadeOut nos imoveis atuais
	$('.im_foto').html('<p id="flax"></p>');
	$('.im_info').fadeOut('fast');


	$.get(json_url, function(html){
		$('.im_busca').remove();
		$('#resultados').html(html);
		$('.im_info').hide();
		$('.im_info').fadeIn('fast');
	});
	return false;
}

function checkTr(input, imovel, finalidade)
{
	var div = input.parentNode.parentNode.parentNode;
	div.checked = (input.checked == true)?1:0;

	//Chama a função que adiciona um imovel para comparar por ajax
	comparar(imovel, finalidade);
}

function comparar(i, f)
{
	$.post(dominio+'busca/clique_compara', {ed_imovel: i, ed_finalidade: f}, function(res) {
		if(res == 0)
			window.location = dominio+'imovel/comparar';
	});
}

//Cadastro de imoveis, preços:
function valorImovel(el, id)
{
	document.getElementById(id).style.display = (el.checked == true)?'block':'none';
}

function blockBg()
{
	var div = document.createElement('div');
	div.style.zIndex = '98';
	div.style.width = '100%';
	div.style.height = '100%';
	div.style.position = 'absolute';
	div.style.top = '0';
	div.style.left = '0';
	div.id = 'block_bg';
	$('body').append(div);
}

function porpagina(quant, atual)
{
	var local = new String(window.location);
	local = local.substr(7, local.length);
	if(local.indexOf('paginar/') < 0)
	{
		window.location += '/paginar/'+quant+':'+atual;
		return;
	} else {
		var aux = local.split('/');
		var loc = '/';
		for(i=1;i<aux.length;i++)
		{
			if(aux[i].indexOf('paginar/') >= 0) continue;
			loc += aux[i]+'/';
		}
		loc += 'paginar/'+quant+':0';
		window.location = loc;
	}
}

function busca_cep(obj)
{
	var cep = obj.value.replace('-', '');
	if(cep.length != 8) return false;
	$.getJSON(dominio+'cep/endereco/response/json/id/'+cep, function(json){
		if(json == 0)
		{
			Dialog.show({content: 'O CEP que você digitou não foi encontrado em nossa base de dados, verifique se você digitou corretamente. Se o problema persistir, preencha manualmente o endereço. Obrigado.'});
			$('#cep_encontrado').val('0');
			$('#ed_estado').val('PR')
				.attr('disabled', false)
				.removeClass('off');
			$('#ed_cidade').val('Ponta Grossa')
				.attr('disabled', false)
				.removeClass('off');
			$('#ed_bairro').attr('disabled', false)
				.removeClass('off');
			$('#ed_endereco').attr('disabled', false)
				.removeClass('off');
			return;
		}
		
		$('#cep_encontrado').val('1');
		$('#ed_estado').val(json.uf);
		$('#ed_cidade').val(json.cidade);
		$('#ed_bairro').val(json.bairro);
		$('#ed_endereco').val(json.tipo+' '+json.rua);
	});
}

function clickImages()
{
	if(!document.getElementById('upload_fotos')) return;
	var div = document.getElementById('upload_fotos');
	var img = div.getElementsByTagName('div');
	for(i=0;i<img.length;i++)
	{
		if(img[i].className.match('foto_holder')) continue;
		img[i].onclick = function()
		{
			if(this.className.match('foto_holder')) return false;

			// Remove a borda de todas as imagens
			var todas = this.parentNode.getElementsByTagName('div');
			for(j=0;j<todas.length;j++)
			{
				if(todas[j].className.match('foto_holder')) continue;
				todas[j].style.backgroundColor = '#FFF';
			}

			//Seleciona a imagem clicada
			this.style.backgroundColor = '#009900';
			document.getElementById('ed_foto_principal').value = $(this).attr('cod_foto');
		}

		img[i].ondblclick = function()
		{
			if(this.className.match('foto_holder')) return false;
			if(!confirm('Tem certeza que deseja apagar esta foto?')) return false;


			this.style.backgroundColor = '#FF0000';
			var frm = document.getElementById('frame_upload');
			var src = dominio+'upload/remove/id/'+$(this).attr('cod_foto');

			//Se tiver a classe tb_foto, o usuario esta editando as fotos
			if(this.className.match('tb_foto'))
				src = dominio+'upload/delete/id/'+$(this).attr('cod_foto');

			frm.src = src;
		}

		img[i].onmouseover = function()
		{
			if(this.className.match('foto_holder')) return false;
			Tip('* Clique para selecionar esta foto como destaque<br />* Duplo clique para apagá-la');
		}

		img[i].onmouseout = function()
		{
			if(this.className.match('foto_holder')) return false;
			UnTip();
		}
	}
}

function clickImagesVideo()
{
	if(!document.getElementById('upload_videos')) return;
	var div = document.getElementById('upload_videos');
	var img = div.getElementsByTagName('div');
	controller = (controller != '')?controller:'imovel';
	for(i=0;i<img.length;i++)
	{
		if(img[i].className.match('video_holder')) continue;

		img[i].onclick = function()
		{
			if(this.className.match('video_holder')) return false;
			if(!confirm('Tem certeza que deseja apagar este video?')) return false;
			this.style.backgroundColor = '#FF0000';
			var frm = document.getElementById('frame_upload');
			var src = dominio+''+controller+'/delete_video/id/'+this.getAttribute('cod_video');
			frm.src = src;
		}

		img[i].onmouseover = function()
		{
			if(this.className.match('video_holder')) return false;
			Tip('* Clique para apagar este video');
		}

		img[i].onmouseout = function()
		{
			if(this.className.match('video_holder')) return false;
			UnTip();
		}
	}
}

function uploadError(mensagem)
{
	Dialog.show({content: mensagem});
	upLoading(0);
	return false;
}

function upLoading(flag)
{
	var span = document.getElementById('ico_loading');
	if(flag == 1)
	{
		if($('#ed_foto').val() == '')
		{
			Dialog.show({content: 'Selecione uma foto antes de clicar em enviar!'});
			return false;
		}

		var img = new Image();
		img.src = dominio+'public/images/loading.gif';
		span.appendChild(img);
	}
	else
	{
		span.innerHTML = '';
	}
}

function upLoadingVideo(flag)
{
	var span = document.getElementById('ico_loading_video');
	if(flag == 1)
	{
		var img = new Image();
		img.src = dominio+'public/images/loading.gif';
		span.appendChild(img);
	}
	else
	{
		span.innerHTML = '';
	}
}

function mostraCidades()
{
	$('#cidade div').show();
	$('#btn_sair').hide();
}

function escondeCidades()
{
	$('#cidade div').hide();
	$('#btn_sair').show();
}

function removeFoto(cod_foto)
{
	//Remove o hidden field do form
	if(document.getElementById('form_cadastro'))
	{
		var form_cad = document.getElementById('form_cadastro');
		var hidden = document.getElementById('cf_'+cod_foto);
		form_cad.removeChild(hidden);
	}

	//Remove a foto da tela
	var divAll = document.getElementById('upload_fotos');
	var divHolders = divAll.getElementsByTagName('div');
	for(i=0;i<divHolders.length;i++)
	{
		if(divHolders[i].cod_foto == cod_foto || divHolders[i].getAttribute('cod_foto') == cod_foto)
		{
			divHolders[i].className = 'foto_upload foto_holder';
			divHolders[i].innerHTML = '';
			divHolders[i].style.backgroundColor = '#F4F4F4';
			break;
		}
	}

	//Tira o destaque
	document.getElementById('ed_foto_principal').value = 0;

	//Atualiza os eventos
	clickImages();
}

function removeVideo(id)
{
	//Remove o video da tela
	var divAll = document.getElementById('upload_videos');
	var divHolders = divAll.getElementsByTagName('div');
	for(i=0;i<divHolders.length;i++)
	{
		if(divHolders[i].getAttribute('cod_video') == id)
		{
			divHolders[i].className = 'video_upload video_holder';
			divHolders[i].innerHTML = '';
			divHolders[i].style.backgroundColor = '#F4F4F4';
			break;
		}
	}

	//Atualiza os eventos
	clickImagesVideo();
}

function estados()
{
	//Verifica se o form existe
	if(!document.getElementById('ed_estado_json')) return;

	//Faz a requisição dos estados
	$.getJSON(dominio+'cep/estados', function(json) {
		var option = '';
		var selected = '';

		//Cria o combobox com o retorno
		for(i=0;i<json.length;i++)
		{
			selected = '';
			if(json[i].selected == true)
				selected = 'selected="selected"';
			option += '<option value="'+json[i].ufe_sg+'" '+selected+'>'+json[i].ufe_no+'</option>';
		}

		//Coloca a opção indiferente e insere no select
		option += '<option value="">Indiferente</option>';
		$('#ed_estado_json').html(option);
	});

	//Coloca o evento onchange
	$('#ed_estado_json').change(function() {
		cidades(this.value);
	});
}

function cidades(uf)
{
	//Verifica se o form existe e coloca os textos nos options
	if(!document.getElementById('ed_cidade_json')) return;
	$('#ed_cidade_json').html('<option value="" selected="selected">Aguarde...</option>');
	$('#ed_bairro_json').html('<option value="" selected="selected">Bairro</option><option value="">Selecione uma cidade</option>');

	//Faz a requisição das cidades
	$.post(dominio+'cep/cidades', {uf: uf},
		function(data)
		{
			var json = eval(data);
			var selected = '';
			var option = '';
			var id = 0;

			//Cria o combobox com o retorno
			for(i=0;i<json.length;i++)
			{
				selected = '';
				if(json[i].selected == true)
				{
					selected = 'selected="selected"';
					id = json[i].loc_nu_sequencial;
				}
				option += '<option value="'+json[i].loc_nu_sequencial+'" '+selected+'>'+json[i].loc_nosub+'</option>';
			}

			//Seleciona o primeiro caso nenhum venha selecionado
			if(json.length > 0)
				if(id == 0) id = json[0].loc_nu_sequencial;
			option += '<option value="">Indiferente</option>';
			$('#ed_cidade_json').html(option);

			//Chama os bairros da cidade selecionada
			bairros(id);
		}
	);
	$('#ed_cidade_json').change(function() {
		bairros(this.value);
	});
}

function bairros(id)
{
	if(!document.getElementById('ed_bairro_json')) return;
	$('#ed_bairro_json').html('<option value="" selected="selected">Bairro</option><option value="">Aguarde...</option>');

	//Se a cidade e/ou estado for selecionado como indiferente, não faz a requisição dos bairros
	if(id == 0)
	{
		$('#ed_bairro_json').html('<option value="" selected="selected">Bairro</option><option value="">Indiferente</option>');
		return;
	}
	$.post(dominio+'cep/bairros', {id: id},
		function(data)
		{
			var json = eval(data);
			var option = '<option value="" selected="selected">Bairro</option><option value="">Indiferente</option>';
			for(i=0;i<json.length;i++)
			{
				option += '<option value="'+json[i].bai_nu_sequencial+'">'+json[i].bai_no+'</option>';
			}
			$('#ed_bairro_json').html(option);
		}
	);
}

function playVideo(id)
{
   var flashvars = {video_id: id};
   var params = {menu: 'false'};
   swfobject.embedSWF("/public/swf/yt_video.swf", "yt_video", "365", "275", "8.0.0", null, flashvars, params, null);
}

function overframe()
{
	fadeBg();
	var frame = '<iframe frameborder="0" style="margin-top:5px;" height="580" name="frame_caixa" id="frame_caixa" scrolling="No" src="http://www8.caixa.gov.br/siopiinternet/simulaOperacaoInternet.do?method=inicializarCasoUso" width="470" />';
	$('body').append('<div id="overframe" style="display:none;"><p align="right"><a href="#" onclick="hideBg()"><img src="/public/images/btn_fechar_div.gif" alt="" /></a></p>'+frame+'</div>');
	$('#overframe').css({
		width: '480px',
		height: '610px',
		marginTop: '-305px',
		marginLeft: '-240px',
		backgroundColor: '#FFF',
		position: 'absolute',
		zIndex: '99',
		padding: '7px',
		top: '50%',
		left: '50%'
	});
	$('#overframe').fadeIn();
	window.location = '#';
}

function divErroIndicar(arquivo)
{
	fadeBg();
	var url = '/ajuda';
	switch(arquivo)
	{
		case 1:
			url += '/indicar';
			break;
		case 2:
			url += '/erro/?url='+window.location;
			break;
		case 3:
			url += '/missao_visao';
			break;
		case 4:
			url += '/quem_somos';
			break;
		case 5:
			url += '/termos_uso';
			break;
		case 6:
			url += '/privacidade';
			break;
		case 7:
			url += '/indicarImovel/?url='+window.location;
			break;
	}
	var frame = '<iframe frameborder="0" style="margin-top:5px;" height="390" name="frame_form" id="frame_form" class="fade" scrolling="No" src="'+url+'" width="530" />';
	$('body').append('<div id="overframe" style="display:none;">'+frame+'</div>');
	$('#overframe').css({
		width: '530px',
		height: '390px',
		marginTop: '-195px',
		marginLeft: '-265px',
		backgroundColor: '#FFF',
		position: 'absolute',
		zIndex: '99',
		padding: '0px',
		top: '50%',
		left: '50%'
	});
	$('#overframe').fadeIn();
	window.location = '#';
	return false;
}

function divAjuda(id)
{
	fadeBg();
	var html = '<div id="ajuda" class="fade"><p class="ajuda_tit"><img src="/public/images/tit_ajuda.jpg" alt="" /></p>';
    html += '<p class="ajuda_fechar"><a href="#" onclick="hideBg()"><img src="/public/images/btn_fechar_div.gif" alt="" /></a></p>';
    html += '<br clear="all" /><br />';
    html += '<p class="ajuda_txt"></p></div>';
    $('body').append(html);
    
    $.post('/ajuda/xml', {id: id},function(data){
       $('.ajuda_txt').html(data);
    });
	$('#ajuda').css({
		width: '530px',
		marginLeft: '-265px',
		backgroundColor: '#FFF',
		position: 'absolute',
		zIndex: '99',
		top: '200px',
		left: '50%'
	});
	$('#ajuda').fadeIn();
	window.location = '#';
}

function addFile(cod_arquivo, caminho)
{
	//Limpa o input
	$('#ed_foto').val('');

	//Cria a imagem
	var img = new Image(68, 50);
	img.src = caminho;
	img.alt = 'Clique para selecionar esta foto como destaque.';
	img.title = 'Clique para selecionar esta foto como destaque.';

	//Cria os hidden fields com as imagens
	/*
	if(document.getElementById('form_cadastro'))
	{
		var form_cad = document.getElementById('form_cadastro');
		var field = document.createElement('input');
		field.type = 'hidden';
		field.name = 'foto_imovel[]';
		field.value = cod_arquivo;
		field.id = 'cf_'+cod_arquivo;
		form_cad.appendChild(field); //Insere no form de cadastro
	}
	*/

	//coloca a Div no documento
	var divAll = document.getElementById('upload_fotos');
	var divHolders = divAll.getElementsByTagName('div');
	for(i=0;i<divHolders.length;i++)
	{
		if(divHolders[i].className.match('foto_holder'))
		{
			if(divHolders[i].className.match('tb_foto'))
				divHolders[i].className = 'tb_foto';
			else
				divHolders[i].className = '';
			divHolders[i].className += ' foto_upload';
			$(divHolders[i]).attr('cod_foto', cod_arquivo);
			divHolders[i].appendChild(img);
			break;
		}
	}

	//Tira o loading
	upLoading(0);

	//Selecionar principal
	clickImages();
}

function videoUploaded(id)
{
	//Limpa o input
	var ip = document.getElementById('ed_video');
	ip.value = '';

	//Cria a imagem
	var img = new Image(68, 50);
	img.src = 'http://img.youtube.com/vi/'+id+'/2.jpg';
	img.alt = 'Clique para apagar este video.';
	img.title = 'Clique para apagar este video.';

	//coloca a Div no documento
	var divAll = document.getElementById('upload_videos');
	var divHolders = divAll.getElementsByTagName('div');
	for(i=0;i<divHolders.length;i++)
	{
		if(divHolders[i].className.match('video_holder'))
		{
			divHolders[i].className = 'video_upload';
			divHolders[i].cod_video = id;
			divHolders[i].appendChild(img);
			break;
		}
	}

	//Tira o loading
	upLoadingVideo(0);

	//Selecionar principal
	clickImagesVideo();
}

//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de milésimos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento
//Retorno: Booleano
//Autor: Gabriel Fróes - www.codigofonte.com.br
//-----------------------------------------------------
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 0 || whichCode == 8) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

function addFav(){
    var url      = "http://adquiraimoveis.net/";
    var title    = "Procure Imóvel - A Maneira Mais Fácil e Rápida de Alugar e Vender Seus Imóveis";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}
function dropDown()
{
	//Hack para funcionar o menu dropdown no IE 6
	if(!document.getElementById('menu_adm')) return;
	if(document.all&&document.getElementById)
	{
		var span = document.getElementById('menu_adm').getElementsByTagName('span');
		for(i=0;i<span.length;i++)
		{
			span[i].onmouseover = function()
			{
				this.className += ' over';
			}
			span[i].onmouseout = function()
			{
				this.className = this.className.replace(' over', '');
			}
		}
	}
}

function excluir_imovel(cod_imovel)
{
	var html = '<p id="ex_txt"><strong>Qual é o motivo da remoção do imóvel?</strong></p><br />';
	html += '<form id="excluir_form" action="/imovel/excluirsimples" method="post"><input type="hidden" name="cod" value="'+cod_imovel+'" />';
	html += '<p><input type="radio" value="1" name="ex_resposta" id="ex_resposta_1" /> <label for="ex_resposta_1">O imóvel foi negociado através do Procure Imóvel.</label></p>';
	html += '<p><input type="radio" value="2" name="ex_resposta" id="ex_resposta_2" /> <label for="ex_resposta_2">O imóvel foi negociado através de jornais ou outros meios.</label></p>';
	html += '<p><input type="radio" value="3" name="ex_resposta" id="ex_resposta_3" /> <label for="ex_resposta_3">Cancelamento da opção por parte do proprietário.</label></p>';
	html += '<p><input type="radio" value="4" name="ex_resposta" id="ex_resposta_4" onchange="$(\'#ex_outro\').focus()" /> <label for="ex_resposta_4">Outro motivo. Qual? </label> <input type="text" id="ex_outro" name="ex_outro" size="35" maxlength="200" value="opcional" style="color:#999999" /></p>';
	html += '</form>';
	
	Dialog.show({
		content: html,
		width: 415,
		height: 210,
		hideButton: 'Cancelar',
		buttons: {
			'Confirmar Remoção': function(){
				if ($('#excluir_form input[name=ex_resposta]:checked').val() == undefined)
					$('#ex_txt strong')
						.prepend('*')
						.css('color', '#FF0000');
				else
					$('#excluir_form').submit();
			}
		}
	});
}

var Info = {
	show: function(obj)
	{
		//Bloqueia o fundo
		fadeBg({bgColor:'#666666', opacity:0.6, onclick: function(){}});

		//Cria o DIV com os dados
		var mDiv = document.createElement('div');
		mDiv.className = 'infobox';
		mDiv.id = 'infobox';
		var html = '<p class="infotitle">'+obj.Title+'</p>';
		html += '<p class="infox"><a href="javascript:;" title="Fechar Janela" onclick="Info.hide()"><img src="http://procureimovel.com.br/public/images/btn_x.jpg" alt="" /></a></p>';
		html += '<br clear="all" /><br />';
		html += '<p class="infotxt">'+obj.Message+'</p>';
		html += '<p class="infobtn"><input type="button" value="OK" style="width:80px" onclick="Info.hide()" /></p>';
		mDiv.innerHTML = html;

		//Insere o DIV no documento
		$('body').append(mDiv);
		window.location = parent.window.location+'#top';
	},

	hide: function()
	{
		$('div#infobox').remove();
		hideBg();
	}
};

//Pré-carregamento de imagens importantes:
var img = Array();
img[0] = new Image();
img[0].src = dominio+'public/images/box.png';

//Chama o IE6 Hack
$(function(){
	dropDown();
	estados();
	cidades('');
});

function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {
				xScroll = window.innerWidth + window.scrollMaxX;
				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
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth;
				} else {
					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 = xScroll;
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
}

function fadeBg(config)
{
	$('body').append('<div id="overlay" style="display:none;"></div>');
	var arrSizes = ___getPageSize();
	$('#overlay').css({
		height: arrSizes[1],
		width: arrSizes[0],
		backgroundColor: (config == null)?'#666666':config.bgColor,
		position: 'absolute',
		zIndex: '98',
		left: '0px',
		top: '0px',
		opacity: (config == null)?0.6:config.opacity
	});
	$('select').hide();
	$('object').hide();
	$('embed').hide();
	$('#overlay').fadeIn();

	var oncl = (config == null)?hideBg:config.onclick;
	$('#overlay').click(oncl);
}

function hideBg()
{
	$('#overlay').remove();
	$('#overframe').remove();
    $('.fade').remove();

	$('select').show();
	$('object').show();
	$('embed').show();
	//window.location = '#';
}

var Dialog = {

	show: function (obj)
	{
		
		if (obj == undefined)
			var obj = {};
		
		this.title       = (obj.title != undefined) ? obj.title : 'Aten&ccedil;&atilde;o!';
		this.content     = (obj.content != undefined) ? obj.content : '';
		this.width       = (obj.width != undefined) ? obj.width : 330;
		this.height      = (obj.height != undefined) ? obj.height : 160;
		this.hideButton  = (obj.hideButton != undefined) ? obj.hideButton : 'OK';
		this.buttons     = (obj.buttons != undefined) ? obj.buttons : {};
		
		this.render();
	},

	render: function ()
	{
		var html = '';
		var btn = '';
		
		var height = ($(document).height() >= $(window).height()) ? $(document).height() : $(window).height();
			
		html += '<div id="dialog_div">';
		html += '<div id="block_bg" style="height:'+height+'px;"></div>';
		html += '<div id="dialog" style="width:'+this.width+'px;height:'+this.height+'px;margin-left:-'+parseInt(this.width/2)+'px;margin-top:-'+parseInt(this.height/2)+'px;">';
		html += '<div class="dialog-top">';
		html += '<h1>'+this.title+'</h1>';
		html += '<div class="dialog-content" style="width:'+(this.width-20)+'px;">';
		html += this.content;
		html += '</div>';
		html += '<div class="dialog-buttons">';
		html += '<p></p>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
			
		$('select').css({visibility: 'hidden'});
		$('body').append(html);
		
		$.each(this.buttons, function(name, fn) {
			$('<input type="button" value="'+name+'"></input>')
				.click(fn)
				.appendTo('.dialog-buttons');
		});
		
		if(this.hideButton != false)
			$('<input type="button" value="'+this.hideButton+'" onclick="Dialog.hide()" />').appendTo('.dialog-buttons');
	},
	
	hide: function ()
	{
		$('select').css({visibility: 'visible'});
		$('#dialog_div').remove();
	}

}

function trim(s) {
  return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

function mascara_global(mascara, valor){
	tvalor = "";
	ret = "";
	caracter = "#";
	separador = "|";
	mascara_utilizar = "";
	valor = trim(valor);
	if (valor == "")return valor;
	temp = mascara.split(separador);
	dif = 1000;
	
	valorm = valor;
	//tirando mascara do valor já existente
	for (i=0;i<valor.length;i++){
		if (!isNaN(valor.substr(i,1))){
			tvalor = tvalor + valor.substr(i,1);
		}
	}
	valor = tvalor;
	
	//formatar mascara dinamica
	for (i = 0; i<temp.length;i++){
		mult = "";
		validar = 0;
		for (j=0;j<temp[i].length;j++){
			if (temp[i].substr(j,1) == "]"){
				temp[i] = temp[i].substr(j+1);
				break;
			}
			if (validar == 1)mult = mult + temp[i].substr(j,1);
			if (temp[i].substr(j,1) == "[")validar = 1;
		}
		for (j=0;j<valor.length;j++){
			temp[i] = mult + temp[i];
		}
	}
	
	//verificar qual mascara utilizar
	if (temp.length == 1){
		mascara_utilizar = temp[0];
		mascara_limpa = "";
		for (j=0;j<mascara_utilizar.length;j++){
			if (mascara_utilizar.substr(j,1) == caracter){
				mascara_limpa = mascara_limpa + caracter;
			}
		}
		tam = mascara_limpa.length;
	}else{
		//limpar caracteres diferente do caracter da máscara
		for (i=0;i<temp.length;i++){
			mascara_limpa = "";
			for (j=0;j<temp[i].length;j++){
				if (temp[i].substr(j,1) == caracter){
					mascara_limpa = mascara_limpa + caracter;
				}
			}
			if (valor.length > mascara_limpa.length){
				if (dif > (valor.length - mascara_limpa.length)){
					dif = valor.length - mascara_limpa.length;
					mascara_utilizar = temp[i];
					tam = mascara_limpa.length;
				}
			}else if (valor.length < mascara_limpa.length){
				if (dif > (mascara_limpa.length - valor.length)){
					dif = mascara_limpa.length - valor.length;
					mascara_utilizar = temp[i];
					tam = mascara_limpa.length;
				}
			}else{
				mascara_utilizar = temp[i];
				tam = mascara_limpa.length;
				break;
			}
		}
	}
	
	//validar tamanho da mascara de acordo com o tamanho do valor
	if (valor.length > tam){
		valor = valor.substr(0,tam);
	}else if (valor.length < tam){
		masct = "";
		j = valor.length;
		for (i = mascara_utilizar.length-1;i>=0;i--){
			if (j == 0) break;
			if (mascara_utilizar.substr(i,1) == caracter){
				j--;
			}
			masct = mascara_utilizar.substr(i,1) + masct;
		}
		mascara_utilizar = masct;
	}
	
	//mascarar
	j = mascara_utilizar.length -1;
	for (i = valor.length - 1;i>=0;i--){
		if (mascara_utilizar.substr(j,1) != caracter){
			ret = mascara_utilizar.substr(j,1) + ret;
			j--;
		}
		ret = valor.substr(i,1) + ret;
		j--;
	}
	return ret;
}

function mostrarTelefone(telefone, imovel)
{
	$('#ver_telefone').html(telefone);
	$.get('/imovel/telefone/id/'+imovel);
}

function validar(form)
{
	if(form.ed_mensagem.value == '')
	{
		alert('Por favor, descreva o erro.');
		return false;
	}
}

function validarContato(form)
{
	if(form.ed_nome.value == '' || form.ed_email.value == '' || form.ed_telefone.value == '' || form.ed_mensagem.value == '')
	{
		Dialog.show({content: 'Por favor, preencha todas as informações pedidas. Obrigado.'});
		return false;
	}
	
	if(form.ed_email.value.indexOf('@') < 2)
	{
		Dialog.show({content: 'O e-mail digitado está incorreto, verifique.'});
		return false;
	}
	
	return true;
}

function validarIndicacao(form)
{
	with(form)
	{
		if(ed_nome.value == '' || ed_email.value == '')
		{
			alert('Preencha o seu nome e o seu e-mail.');
			return false;
		}
		
		if(ed_nome_amigo.value == '' || ed_email_amigo.value == '')
		{
			alert('Preencha o nome e o e-mail do seu amigo.');
			return false;
		}
		
		if(ed_mensagem.value == '')
		{
			alert('Preenche a mensagem para evitar que o e-mail seja interpretado como spam pelo seu amigo.');
			return false;
		}
		
		return true;
	}
}