var pasta = '';

function selectFoto(elemento){

	$("#foto").html('<img src="'+$("img",elemento).attr("src").replace("thumb-","")+'" />');

	$("#count").html(elemento.attr("data-numero")+ ' de '+$("#fotoList li").length);

	$("#fotoList li img").removeClass("sel");
	$("img",elemento).addClass("sel");
	$("#legenda").html($("img",elemento).attr("alt"));

	}
var geocoder;
var map;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 16,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function codeAddress(address,cep) {
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);

    } else if(cep) {
    	codeAddress(cep);
    } else {
    	$("#map_canvas").hide();
    }
  });
}

function countImoveis(){
	var filtros = "";
	$(".formulario input, .formulario select").each(function(){   
		if($(this).attr("id") != '') {

				filtros += $(this).attr("id")+"="+$(this).val()+"&";
		}
	});
	
	$.ajax({
		type: "POST",
		data: filtros,
		url: pasta+'/includes/get-imoveis.php',
		cache: false,
		async: false,
		timeout: 3000, 
		dataType:   "text/html",
		success: function(msg){ 
			$("#nimo").html(msg);
		}
		});
	
}

$(function(){
	
	$(".thumb img").load(function(){
		if($(this).width() > 0 && $(this).width() < $(this).height()) $(this).css({ "margin-left": ((126 - $(this).width()) / 2)+"px", "height": "140px" } );
		else if($(this).height() > 0 &&  $(this).height() < $(this).width()) $(this).css({ "margin-top": ((126 - $(this).height()) / 2)+"px", "width": "140px" } );
	
	});

	$(".listaImoveis li").mouseover(function(){ if($(this).parents("ul").attr("class") != "config") $(this).addClass("on") });
	$(".listaImoveis li").mouseleave(function(){ if($(this).parents("ul").attr("class") != "config") $(this).removeClass("on") });
	$(".listaImoveis li").click(function(){ window.location = $(this).find("a").attr("href"); });
	
//	setTimeout(function(){$(".thumb img").load();},300);
	
	$("#fotoList img").click(function(){
		$("#fotoList img").removeClass("sel");
		$(this).addClass("sel");
		
		/*$("#foto img")
			.attr("src",$(this).attr("src").replace("thumb-",""))
			.attr("alt",$(this).attr("alt"))
			.attr("title",$(this).attr("title"));*/
	});
	
	$("#anterior").unbind()
	.click(function(){

	    var atual = $("#fotoList .sel").parents("li").attr("data-numero");

	    atual--;

	    if($("li[data-numero="+atual+"]").length == 1){
	        selectFoto($("li[data-numero="+atual+"]"));       
	    } else {
	        selectFoto($("li[data-numero="+$("#fotoList li").length+"]")); 
	    }

	});
	
	$("#proximo").unbind()
	.click(function(){

	    var atual = $("#fotoList .sel").parents("li").attr("data-numero");

	    atual++;

	    if($("li[data-numero="+atual+"]").length == 1){
	        selectFoto($("li[data-numero="+atual+"]"));       
	    } else {
	        selectFoto($("li[data-numero=1]")); 
	    }

	});
	
	$("#nego1,#nego2").click(function(){
		$("#tipo option").remove();
		$("#tipo").append("<option>Carregando...</option>");
		
		$.ajax({ 
            type: "POST",
	        data: { negociacao: ($(this).attr("id") == "nego1"?'1':'2') },
            dataType: "json",
            cache: false,
            url: pasta+'/includes/get-tipos.php',
            success: function(data) {
                if(data.length == 0){ alert("Não há imóveis nesta configuração."); } else {
                	$("#tipo option").remove();
                	$("#tipo").removeAttr("disabled");
                	$("#tipo").append("<option value=''>Selecione o tipo de imóvel</option>")
                	
                	$.each(data, function(i, j){
	                	$("#tipo").append("<option value='"+j.url+"'>"+j.nome+"</option>");
	                });
      
                }
            }
        });
	});
	
	$("#tipo").change(function(){
		
		$("#preco option").remove();
		$("#preco").append("<option>Carregando...</option>");
		
		$.ajax({ 
            type: "POST",
	        data: { tipo: $(this).val(), negociacao: $("[name=negocio]:checked").val() },
            dataType: "json",
            cache: false,
            url: pasta+'/includes/get-valores.php',
            success: function(data) {
              
                	$("#preco option").remove();
                	$("#preco").removeAttr("disabled");
                	$("#preco").append("<option value=''>Selecione o valor</option>")
                	
                	$.each(data, function(i, j){
	                	$("#preco").append("<option value='"+j.gama+"'>"+j.valor+"</option>");
	                });
          
            }
        });
	});
	
	$("#negocio1").change(function(){
		$("#TipoImovel2 option").remove();
		$("#TipoImovel2").append("<option>Carregando...</option>");
		
		$.ajax({ 
            type: "POST",
	        data: { negociacao: $(this).val() },
            dataType: "json",
            cache: false,
            url: pasta+'/includes/get-tipos.php',
            success: function(data) {
              
                	$("#TipoImovel2 option").remove();
                	$("#TipoImovel2").removeAttr("disabled");
                	$("#TipoImovel2").append("<option value=''>Selecione o tipo de imóvel</option>")
                	
                	$.each(data, function(i, j){
	                	$("#TipoImovel2").append("<option value='"+j.url+"'>"+j.nome+"</option>");
	                });
                	$("#TipoImovel2").removeAttr("disabled");
                	recount();
            		countImoveis();
            }
        });
		
	});
	
	$("#TipoImovel2").change(function(){
		
		countImoveis();
		
		$("#Cidade option").remove();
		$("#Cidade").append("<option>Carregando...</option>");
		
		$.ajax({ 
            type: "POST",
	        data: { tipo: $(this).val(), negociacao: $("#negocio1").val() },
            dataType: "json",
            cache: false,
            url: pasta+'/includes/get-cidades.php',
            success: function(data) {
              
                	$("#Cidade option").remove();
                	$("#Cidade").removeAttr("disabled");
                	$("#Cidade").append("<option value=''>Selecione a cidade</option>")
                	
                	$.each(data, function(i, j){
	                	$("#Cidade").append("<option value='"+j.url+"'>"+j.nome+"</option>");
	                });
                	$("#Cidade").removeAttr("disabled");
            }
        });
	});
	
	$("#Cidade").change(function(){
		
		countImoveis();
		
		$("#Bairro option").remove();
		$("#Bairro").append("<option>Carregando...</option>");
		
		$.ajax({ 
            type: "POST",
	        data: { cidade: $(this).val(), tipo: $("#TipoImovel2").val(), negociacao: $("#negocio1").val() },
            dataType: "json",
            cache: false,
            url: pasta+'/includes/get-bairros.php',
            success: function(data) {
              
                	$("#Bairro option").remove();
                	$("#Bairro").removeAttr("disabled");
                	$("#Bairro").append("<option value=''>Selecione o bairro</option>")
                	
                	$.each(data, function(i, j){
	                	$("#Bairro").append("<option value='"+j.url+"'>"+j.nome+"</option>");
	                });
                	$("#Bairro").removeAttr("disabled");
            }
        });
	});
	
	$("#Bairro").change(function(){
		
		$("#valor").removeAttr("disabled");
		$("#dorm").removeAttr("disabled");
		$("#suites").removeAttr("disabled");
		$("#vagas").removeAttr("disabled");
		$("#banh").removeAttr("disabled");
	});
	
	$("#submitInfo").click(function(){
		$.ajax({ 
            type: "POST",
	        data: { referencia: $("#ref").val(), nome: $("#nome").val(), email: $("#email").val(), telefone: $("#telefone").val(), msg: $("#msg").val() },
            dataType: "text/html",
            cache: false,
            url: pasta+'/imoveis/contato.php',
            success: function(msg) {
                alert(msg);
                if(msg.indexOf("sucesso") >= 0){
                	$("#infoForm").slideUp();
                }
            }
        });
		
		return false;
	});
	
	$(".busca-avancada-de-imoveis #Bairro," +
		".busca-avancada-de-imoveis #dorm," +
		".busca-avancada-de-imoveis #banh," +
		".busca-avancada-de-imoveis #vagas," +
		".busca-avancada-de-imoveis #suites," +
		".busca-avancada-de-imoveis #valor").change(function(){ countImoveis(); });
	
	$("#preco").change(function(){
		var multiplo = $("[name=negocio]:checked").val() == '2' ? 1000 : 100000;
		window.location = "http://"+location.host+pasta+"/"+$("#tipo").val()+"-"+($("#nego1").attr("checked")?"a-venda":"para-alugar")+"/todas-as-cidades?"+($("#preco").val() > 1?"&valor_min="+($("#preco").val()-1)*multiplo:"")+($("#preco").val() < 11?"&valor_max="+$("#preco").val()*multiplo:"");
		
		
	});

	
});
