$(document).ready(function(){

	isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	isIE7 = /msie|MSIE 7/.test(navigator.userAgent); 

	$(".question").click(function(){
		$(".reply").each(function(){
			$(this).slideUp();
			$(this).prev().children("img").attr("src", "images/seta_direita.gif");
		});
		
		$(this).next(".reply").slideDown();
		$(this).children("img").attr("src", "images/seta_abaixo.gif");
	});
	
	$('#destaques_alugueis').hide();
	$('#destaques_lancamentos').hide();
	$(".favorito").click(function(e){
		e.preventDefault();
		var e = $(this);
		$.ajax({
			url: 'favoritos/favoritos.php', 
			dataType: 'html',
			type: 'POST',
			data: {id_imovel: e.attr('id')},
			timeout: 5000,
			success: function(data){
				if(data == true) {
					var o = $('#favoritosSpanQtd');
					if(o.length > 0) {
						getQuantidadeFavoritos(o);
					}
					e.attr('src','destaques/images/favoritos_over.png');
				}
			}		
		});
	});

	$("#imovel_tipo .tipo").change(function(){
		tipo = $(this).attr("name").replace("tipo","");
		if ($(this).val() == 32 || $(this).val() == 33){
			$("#dormitorios"+tipo).show();
		} else {
			$("#dormitorios"+tipo).find('option:first').attr('selected', 'selected').parent('select');
			$("#dormitorios"+tipo).hide();
		}
	});
	
	$(".favorito_det").click(function(e){
		e.preventDefault();
		var e = $(this);
		$.ajax({
			url: 'favoritos/favoritos.php', 
			dataType: 'html',
			type: 'POST',
			data: {id_imovel: e.attr('id')},
			timeout: 5000,
			success: function(data){
				if(data == true) {
					var o = $('#favoritosSpanQtd');
					if(o.length > 0) {
						getQuantidadeFavoritos(o);
					}
					e.attr('src','busca-imoveis/images/bot_favoritos_over.gif');
				}
			}		
		});
	});	
	$("#favoritos_clean").click(function(e){
		e.preventDefault();
		$.ajax({
			url: 'favoritos/favoritosclean.php', 
			dataType: 'html',
			type: 'POST',
			timeout: 5000,
			success: function(data){
				if(data == true) {
					var o = $('#favoritosSpanQtd');
					if(o.length > 0) {
						getQuantidadeFavoritos(o);
						window.location.href = 'index.php?secao=favoritos';
					}
				}
			}		
		});
	});
	//FUNCTION PARA VERIFICAR QUAL FORMULÁRIO ESTÁ VISÍVEL
	function verificaContext() {
		var context = null;
		if($('#busca_vendas').is(':visible')) {
			context = '#busca_vendas';
		} else {
			context = '#busca_alugueis';
		}
		return context;
	}

	var flag = false;		
	//BUSCA BAIRROS
	$(".busca_cidades").change(function(){
		var tmp = verificaContext();
		var id = $(this).val();
		var tipo = $(this).next().val();
		
		$(".div_all_tipos",tmp).hide();
		
		if((id > 0) || (id != '')) {
			$.ajax({
				type: 'POST',
				dataType: 'json',
				timeout: 10000,
				url: 'busca/ajax/bairro.php',
				data: {'cidade' : id, 'tipo': tipo},
				success: function(data){
					var j = 0;
					var colunas = 0;
					var altura = 'auto';
					var size = data['s'];
					var tag_name = (tipo == 0) ? 'busca_aluguel_bairros[]' : 'busca_venda_bairros[]';
					var html = "<table border='0' cellspacing='0' cellpadding='0' class='textos' style='background: none;'>"+
								"<tr>"+
								"<td class='canto_busca_esq'></td>"+
								"<td class='menu_topo_listra'></td>"+
								"<td class='menu_topo_canto_dir' style='background: none;'></td>"+
								"</tr>"+
								"<tr bgcolor='#FFFFFF'>"+
								"<td class='menu_centro_esq' valign='top'></td>"+
								"<td class='textos' valign='top'>"+
								"<img src='busca/images/titu_bairros.gif' />"+
								"<div class='estica' style='margin-bottom: 5px;'></div>"+
								"<div id='content_bairros'>";
					
					for(i = 0; i < size; i++) {
						if(j == 0) {
							html += "<div class='ret_check'>";	
						}
						html += "<div class='item_busca'><input type='checkbox' value='"+data['k'][i]+
								"' name='"+tag_name+"' class='busca_bairros'/><label for='"+tag_name+"'>"+data['v'][i]+
								"</label></div>";	
						
						j++;
						if(j == 12) {
							html += "</div>";	
							j = 0;
							colunas++;
						}
					}
															
					if (j < 12){ 
						html += "</div>";
					}
													
					html += "<div class='estica'></div>"+
							"<img src='busca/images/bot_escolher.gif' class='btEscolherBairro' style='float:right; margin-top: 5px; margin-right: 3px;' alt='Escolher' />"+
							"<div class='btTodosBairro none'></div>"+
							"</td>"+
							"<td valign='top' style='background:url(busca/images/listra_fecha_busca.gif) no-repeat; height: 115px;'></td>"+
							"</tr>"+
							"<tr>"+
							"<td class='menu_rodape_canto_left'></td>"+
							"<td class='menu_rodape_listra'></td>"+
							"<td class='menu_rodape_canto_right'></td>"+
							"</tr>"+
							"</table>"+
							"</div>";
									
					if(colunas > 0) {
						altura = '190';
					}

					largura = isIE6 ? 12 : 192;
					$(".div_all_bairros",tmp).css({'width': (colunas + 1) * 150 + 15,'height': altura, 'right': largura}).html(html);

					$("#content_bairros",tmp).css({'width': (colunas + 1) * 150}).html();
					$(".listra_titulos",tmp).css({'width': ((colunas + 1) * 150) - 147}).html();
					flag = true;
					$(".lbl_bairros").bind('click', handlerClickLblBairros).removeClass('lbl_bairros_off').addClass('lbl_bairros_on');
				},
				error: function(xhr,erro){
					flag = false;
				}	
			});
		} else {
			$(".div_all_bairros",tmp).hide();
			$(".lbl_bairros").unbind('click', handlerClickLblBairros).removeClass('lbl_bairros_on').addClass('lbl_bairros_off');
		}
	});		
	
	//INTERAÇÃO BAIRROS
	var handlerClickLblBairros = function() {
		var tmp = verificaContext();
		$(".div_all_tipos",tmp).hide();
		var comp = $(".div_all_bairros",tmp);
		var n = comp.children().children().length;
		var j = $(".busca_cidades",tmp).val();
		if((n > 0) && (j > 0 || j != '') && (flag == true)){
			if(comp.is(':hidden')) {
				larg = comp.css('width');
				comp.css('width',0).show().animate({ width: larg }, { queue:false, duration:250 });	
			}
		}
	};
	
	//INTERAÇÃO TIPOS DE IMÓVEIS
	$(".lbl_tipos").click(function(){
		var tmp = verificaContext();
		$(".div_all_bairros",tmp).hide();
		var comp = $(".div_all_tipos",tmp);
		var n = comp.children().length;
		var j = $("input.busca_tipos",tmp).val();
		if((n > 0) && (j > 0 || j != '')){
			if(comp.is(':hidden')) {
				comp.css({'width': 0, 'height': 186, 'right': 195, 'top': 74}).show().animate({'width': 155, 'height': 186}, { queue:false, duration:250 });
			}
		}
	});		

	//ABAS DOS FORMULÁRIOS
	$(".tabs").click(function(){
		var tmp = verificaContext();
		
		$(".busca_form",tmp)[0].reset();
		$(".div_all_bairros").hide().empty();
		$(".div_all_tipos").hide();
		$(".div_dormitorios:eq(0)",tmp).slideUp();
		
		if($('#busca_vendas').is(':visible')) {
			$("#busca_vendas").hide();
			$("#busca_alugueis").show();
		} else {
			$("#busca_alugueis").hide();
			$("#busca_vendas").show();
		}
	});
	
	//BTFECHAR DIV BAIRROS
	$(".btEscolherBairro").live('click',function(){
		var tmp = verificaContext();
		$(".div_all_bairros",tmp).fadeOut('150');
	});
	
	//SELECIONAR/DESELECIONAR TODOS/NENHUM BAIRROS
	$(".btTodosBairro").live('click',function(){
		var tmp = verificaContext();
		var obj = $(this);
		if (obj.hasClass('all')) {
			obj.removeClass('all').addClass('none').css('background-position','-66px 0');
			$("input.busca_bairros", tmp).attr('checked', false);
		} else {
			obj.removeClass('none').addClass('all').css('background-position','0 0');
			$("input.busca_bairros", tmp).attr('checked', true);
		}
	});				
	
	//BTFECHAR DIV TIPOS DE IMÓVEIS
	$(".btEscolherTipo").click(function(){
		var tmp = verificaContext();
		$(".div_all_tipos",tmp).fadeOut('150');
	});		
	
	//SELECIONAR/DESELECIONAR TODOS/NENHUM TIPOS DE IMÓVEIS
	$(".btTodosTipo").click(function(){
		var tmp = verificaContext();
		var obj = $(this);
		if (obj.hasClass('all')) {
			obj.removeClass('all').addClass('none').css('background-position','-66px 0');
			$("input.busca_tipos", tmp).attr('checked', false);
		} else {
			obj.removeClass('none').addClass('all').css('background-position','0 0');
			$("input.busca_tipos", tmp).attr('checked', true);
		}
		var ch1 = $("input.busca_tipos", tmp).prev(":contains('Apartamento'):eq(0)").next('input.busca_tipos').attr('checked');
		var ch2 = $("input.busca_tipos", tmp).prev(":contains('Casa'):eq(0)").next('input.busca_tipos').attr('checked');
		if(ch1 || ch2) {
			$(".div_dormitorios:eq(0)",tmp).slideDown();
		} else {
			if(!(ch1) && !(ch2)) {
				$(".div_dormitorios:eq(0)",tmp).slideUp();	
			}
		}
	});		
	
	//BUTTON FOR FORM SUBMIT
	$(".bt_procurar").click(function(){
		$(".busca_form", verificaContext())[0].submit();
	});		
			
	//INTERAÇÃO CASO INPUT SEJA DO TIPO APTO OU CASA
	$("input.busca_tipos").click(function(){
		var tmp = verificaContext();
		var ch1 = $("input.busca_tipos",tmp).prev(":contains('Apartamento'):eq(0)").next('input.busca_tipos').attr('checked');
		var ch2 = $("input.busca_tipos",tmp).prev(":contains('Casa'):eq(0)").next('input.busca_tipos').attr('checked');
		if(ch1 || ch2) {
			$(".div_dormitorios:eq(0)",tmp).slideDown();
		} else {
			if(!(ch1) && !(ch2)) {
				$(".div_dormitorios:eq(0)",tmp).slideUp();	
			}
		}
	});

	//CASO O USUÁRIO FAÇA UMA BUSCA POR CÓDIGO
	$(".busca_codigo").keyup(function() {
		var tmp = verificaContext();
		var j = $(this).val();
		var n = $(".busca_form",tmp);
		if (j.length > 0 && j != 'Cód. do Imóvel') {
			$('input:gt(2), select', n).attr("disabled", "disabled");
		} else {
			$('input:gt(2), select', n).attr("disabled", "");		
		}
	});	
	$("input[name='bt_enviar']").click(function(e){
			e.preventDefault();
			if(verificaForm('newsletter')){
					var dados = $("#form_newsletter").serialize()
					$.ajax({
							url: 'newsletter/ajax/cadastro.php', 
							dataType: 'html',
							type: 'POST',
							data: dados,
							timeout: 5000,
							success: function(data){
									$("#newsletter").fadeOut('1000', function(){
											$(this).empty().html(data).fadeIn(1000);
									});
							},
							error: function(xhr,er) {
									alert(er+xhr);
							}		
					});
			} else {
					alert('Por favor preencha todos os campos');
			}
	});

	function verificaForm(form){
			var flag = true;
			var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
			
			$("form[name='"+form+"'] input").each(function(i){
					if(($(this).val().length <= 0) && ($(this).css('background-color') != '#fff')) {
							$(this).css('border-color','#bde1e1');
							flag = false;
					} else {
							if ($(this).attr('name') == $(this).val()){
									$(this).parent().parent().children('div.input_left').addClass('input_left_red');	
									$(this).parent('div.input_bg').addClass('input_bg_red');
									$(this).parent().parent().children('div.input_right').addClass('input_right_red');	
									flag = false;
							}
							else{
									if (($(this).attr('name') == 'e-mail') && (!regmail.test($(this).val()))){
											$(this).parent().parent().children('div.input_left').addClass('input_left_red');	
											$(this).parent('div.input_bg').addClass('input_bg_red');
											$(this).parent().parent().children('div.input_right').addClass('input_right_red');	
											flag = false;
									} else {
											$(this).parent().parent().children('div.input_left').removeClass('input_left_red');	
											$(this).parent('div.input_bg').removeClass('input_bg_red');
											$(this).parent().parent().children('div.input_right').removeClass('input_right_red');
									}
							}
					}	
			});
			return flag;
	}
});

	function getQuantidadeFavoritos(obj) {
		$.ajax({
			url: 'favoritos/favoritosqtd.php', 
			dataType: 'html',
			type: 'POST',
			timeout: 5000,
			success: function(data){
				if(data != undefined) {
					obj.text(data);
					if($(".favoritos_resultado").length > 0) {
						$(".favoritos_resultado").text(data+' resultados');
					}
					if(data <= 0) {
						$('#bar_esconde').before('<div class="textos" id="favoritosVazio">Voc&ecirc; n&atilde;o possui nenhum im&oacute;vel cadastrado em seu favorito.</div>');
					}
				}
			},
			error: function(xhr,er) {
			}		
		});
	}

function show_fields(field){
	if (field == "fisica"){
		$("#form_cli_empresa").attr("req", "");
		$("#form_cli_cnpj").attr("req", "");
		$("#form_cli_cpf").attr("req", "true");
		$("#pessoa_juridica").slideUp();
		$("#pessoa_fisica").slideDown();
	} else {
		$("#form_cli_empresa").attr("req", "true");
		$("#form_cli_cnpj").attr("req", "true");
		$("#form_cli_cpf").attr("req", "");
		$("#pessoa_fisica").slideUp();
		$("#pessoa_juridica").slideDown();
	}
}

function clean(element, value, original_value)
{
  //alert(element+value);
  if (value == original_value)
  {
    var aux = document.getElementById(element);
    aux.value = '';
  }
}

function fill(element, original_value)
{
  var aux = document.getElementById(element);
  if (aux.value == '')
  {
    aux.value = original_value;
  }
}

function tabs(var1, var2, var3)
{
	$("#"+var1).show();	
	$("#"+var2).hide();
	
	if (var3 != undefined){
		$("#"+var3).hide();
	}

}
function verificaForm(obj)
{
    radiochk = false;

    for ( n = 0; n < obj.opt_id.length; n++ )
    {
        el = obj.opt_id[n];
        radiochk = radiochk || el.checked;
    }

    if ( !radiochk ) {
        alert("Nenhuma opção da enquete foi escolhida!");
        return false;
    }
    
    return true;
}

function vota()
{
    if(verificaForm(document.form_enquete))
    {
        var nwin = window.open('', 'winEnquete', 'location=no, width=435, height=330, scrollbars=yes');
        document.form_enquete.submit();
        nwin.focus();
    }
}
  
function verResultado(id)
{
    var nwin = window.open('enquete/enquete_resultado.php?acao=ver_resultado&enq_id='+id, 'winEnquete', 'location=no, width=435, height=330, scrollbars=yes');
    nwin.focus();
}

function limparPadrao(campo) {
        if (campo.value == campo.defaultValue) {
                campo.value = "";
        }
}

function escreverPadrao(campo) {
        if (campo.value == "") {
                campo.value = campo.defaultValue;
        }
}

function favoritos(url, title) { 
	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 vertical() {
 
   var navItems = document.getElementById("menu_dropdown").getElementsByTagName("li");
    
   for (var i=0; i< navItems.length; i++) {
      if(navItems[i].className == "submenu")
      {
         if(navItems[i].getElementsByTagName('ul')[0] != null)
         {
            navItems[i].onmouseover=function() {this.getElementsByTagName('ul')[0].style.display="block";this.style.backgroundColor = "#f9f9f9";}
            navItems[i].onmouseout=function() {this.getElementsByTagName('ul')[0].style.display="none";this.style.backgroundColor = "#FFFFFF";}
         }
      }
   }
}

