$.extend({
	getUrlVars: function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});
$(function() {

	// Links externos
	$("a[rel=external]").attr("target", "_blank");
	$("a[rel=external nofollow]").attr("target", "_blank");
	$("input[type=submit]").css("cursor", "pointer");
	$("input[type=button]").css("cursor", "pointer");
	$(".facebox-active").facebox();
	$('a.lightbox').lightBox();

	$(".content-link").click();

	//Botão voltar
	$(".bt-imprimir").click(function(){
		//window.print();
		//var calho = $(".bt-imprimir").attr("rev");
		//$("#frame-print").append("<iframe id='frameprint' class='none' src='req/imprimir.php?" + calho + "'></iframe>");
	});

	$(".open-telephones").click(function(){
		var pegaId = $(this).attr("href");
		$(this).slideUp();
		$(pegaId).slideDown();

		var cmd = $.getUrlVars()['cmd'];
		var id = $(this).attr("href");


		id = id.replace('#abre-','');

//		alert (cmd + ' ' + id);
		clickTelephoneView(cmd,id);
		return false;
	});

	$(".open2-telephones").click(function(){
		var pegaId = $(this).attr("href");
		$(this).slideUp();
		$(pegaId).slideDown();

		var cmd = $.getUrlVars()['cmd'];
		var id = $(this).attr("href");


		id = id.replace('#abre-','');

//		alert (cmd + ' ' + id);
		clickTelephoneView(cmd,id);
		return false;
	});

	$(".texto-editor font").each(function(index){
		var fontsize = $(this).attr("size");
		if(fontsize == "1") {
			$(this).addClass("xx-small");
		} else if(fontsize == "2") {
			$(this).addClass("x-small");
		} else if(fontsize == "3") {
			$(this).addClass("small");
		} else if(fontsize == "4") {
			$(this).addClass("medium");
		} else if(fontsize == "5") {
			$(this).addClass("large");
		} else if(fontsize == "6") {
			$(this).addClass("x-large");
		} else if(fontsize == "7") {
			$(this).addClass("xx-large");
		} else {}
	});

	$(document).bind('reveal.facebox', function() {

		$('.menu-spam li a').click(function(){
			if ($('.menu-spam li a').hasClass("sel")) {
				$('.menu-spam li a').removeClass("sel");
				$(this).addClass("sel");
			} else {
				$(this).addClass("sel");
			}
			var agaref = $(this).attr("href");
			if($(agaref).hasClass('evento-aberto2')){
			} else {
				$('.box-escolhe2').removeClass('evento-aberto2');
				$(agaref).addClass('evento-aberto2');
				$('.box-escolhe2').slideUp('500');
				$(agaref).slideDown('500');
			}
			$('.menu-passos li:first-child a').addClass("sel");
			return false;
		});

		$('.menu-passos li a').click(function(){
			if ($('.menu-passos li a').hasClass("sel")) {
				$('.menu-passos li a').removeClass("sel");
				$(this).addClass("sel");
			} else {
				$(this).addClass("sel");
			}
			var agaref = $(this).attr("href");
			if($(agaref).hasClass('evento-aberto')){
			} else {
				$('.box-escolhe').removeClass('evento-aberto');
				$(agaref).addClass('evento-aberto');
				$('.box-escolhe').slideUp('500');
				$(agaref).slideDown('500');
			}
			return false;
		});

	});

	// Transparencia
	$(".opac").css("opacity", "0.5");

	// Anunciante
	$("#bt-anunciante").hover(
		function(){
			$("#nav-sec").show();
		},function(){
			$("#nav-sec").hide();
		}
	);

	// Seleção
	$(document).bind("beforeReveal.facebox", function(){
		$("select").hide();
	});

	$(document).bind("close.facebox", function(){
		$("select").show();
	});

	// Frase
	$('#grande-e-maravilhoza-frase-publicitaria').flash({
	    src: 'swf/frase.swf',
	    width: 510,
	    height: 18,
		wmode: 'transparent',
		expressInstall: true
	});


	// Ativa busca
	$(".bt-buscar").click(function() {
		if ($(this).hasClass("bt-buscar-active")) {
			$(this).removeClass("bt-buscar-active");
			$("#busca-suspensa").slideUp(100);
			$("#form-busca-imovel select").css("visibility","visible");
		} else {
			$(this).addClass("bt-buscar-active");
			$("#busca-suspensa").slideDown(100);
			$("#form-busca-imovel select").css("visibility","hidden");
		}
	});

	// Galeria de imagens imóveis
	$('#imovel .thumbs .holder a').click(function(){
		var imagem  = $(this).attr('href');
		var legenda = $(this).attr('title');
		$('#imovel .image-full .image a').attr('href', imagem + "&w=800&h=800&p=W&c=N&pm=DB");
		$('#imovel .image-full .image a img').attr('src', imagem + "&w=437&h=297&p=W&c=S&pm=DB");
		$('#imovel .legenda').html(legenda);
		return false;
	});

	// Mascara
	$(".telefone").mask("(99)9999-9999");
	$(".cpf").mask("999.999.999-99");
	$(".cep").mask("99999-999");
	$(".masc_data").mask("99/99/9999");

	// Cycle
	if (typeof $.fn.cycle != "undefined") {
		// Slides home
		$("#imovel .thumbs .holder").cycle({
			fx: "scrollHorz",
			prev: ".bt-prev",
			next: ".bt-next",
			speed: 300,
			timeout: 0
		});
		$("#imovel .thumbs .holder a").click({
		});
	}

	// Tables
	$('#proxima-1').click(function() { // Vai para o SEGUNDO passo do cadastro
		if (validaForm('form_venda_rapida_passo1')) {
			$('#ds_cpf').val($('#cpf').val());
			$('#ds_nome').val($('#nome').val());
			$('#ds_telefone').val($('#tel').val());
			$('#ds_operadora_telefone').val($('#operadora_tel').val());
			$('#ds_celular').val($('#cel').val());
			$('#ds_operadora_celular').val($('#operadora_cel').val());
			$('#ds_email').val($('#email').val());

			$('#aba-cadastro-1').removeClass("habilitada");
			$('#aba-cadastro-1').addClass("desabilitada");

			$('#aba-cadastro-2').removeClass("desabilitada");
			$('#aba-cadastro-2').addClass("habilitada");

			$('#aba-1').hide("fast");
			$('#aba-2').show("slow");
		}
	});

	// Script do google maps
	var textodomapa = $("a.mapa-fale").attr("rel");
	var urldomapa = $("a.mapa-fale").attr("title");

	// Script do google maps
	$("a.mapa-fale").teste({
		// Background Color
		bgColor: "#000",
		// Background Opacity
		bgOpacity: 0.8,
		// Map Width
		mapWidth: 700,
		// Map Height
		mapHeight: 500,
		// The text below the map
		mapText: textodomapa,
		// The map URL that come with the iFrame that you can generate at google.com/maps
		mapUrl: urldomapa
	});
	
});

	function abreSimuladorVendas(){
		$("#bt-simulador").click();
	}
	
	function abreSimuladorLocacao(){
		$("#bt-simulador").click();
	}
	
/**
  * Versão do navegador
  * @param nada
  * @return Int Versão
  **/
function getInternetExplorerVersion() {
	var rv = -1;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null) {
			rv = parseFloat( RegExp.$1 );
		}
	}
	return rv;
}


/**
  * Função Validar Formulário
  * @param form Identificador do form
  * @return Boolean
  **/
function validaForm(form) {
	//$.getErro(document.getElementById(form).elements.length);
    for (var i = 0; i < document.getElementById(form).elements.length; i++) {
        var nomeObj = document.getElementById(form).elements[i].name;
        var idObj 	= document.getElementById(form).elements[i].id;
		var relObj 	= document.getElementById(form).elements[i].getAttribute("rel");
		var ver = getInternetExplorerVersion();
		if ((relObj == "email")) {
			expressao = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
			if (!expressao.test(document.getElementById(form).elements[i].value)) {
				if ((navigator.appName == "Microsoft Internet Explorer") && (ver == 6)) {
					$.getErro(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					//document.getElementById(form).elements[i].focus();
					return false;
				} else {
					$.getErro(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			}
		} else if (relObj == "required") {
			if ((document.getElementById(form).elements[i].value == null) || (document.getElementById(form).elements[i].value == "")) {
				if ((navigator.appName == "Microsoft Internet Explorer") && (ver == 6)) {
					$.getErro(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					//document.getElementById(form).elements[i].focus();
					return false;
				} else {
					$.getErro(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			}
		}
    }
    return true;
}


/**
  * Função Validar Formulário
  * @param form Identificador do form
  * @return Boolean
  **/
function validaFormAlerta(form) {
    for (var i = 0; i < document.getElementById(form).elements.length; i++) {
        var nomeObj = document.getElementById(form).elements[i].name;
        var idObj 	= document.getElementById(form).elements[i].id;
		var relObj 	= document.getElementById(form).elements[i].getAttribute("rel");
		var ver = getInternetExplorerVersion();
		if ((relObj == "email")) {
			expressao = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
			if (!expressao.test(document.getElementById(form).elements[i].value)) {
				if ((navigator.appName == "Microsoft Internet Explorer") && (ver == 6)) {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					//document.getElementById(form).elements[i].focus();
					return false;
				} else {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].value = "";
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			}
		} else if (relObj == "required") {
			if ((document.getElementById(form).elements[i].value == null) || (document.getElementById(form).elements[i].value == "")) {
				if ((navigator.appName == "Microsoft Internet Explorer") && (ver == 6)) {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					//document.getElementById(form).elements[i].focus();
					return false;
				} else {
					alert(document.getElementById(form).elements[i].title);
					document.getElementById(form).elements[i].style.backgroundColor = "#666";
					document.getElementById(form).elements[i].style.color = "#FFF";
					document.getElementById(form).elements[i].focus();
					return false;
				}
			}
		}
    }
    return true;
}

/**
  * Função validar contato
  * @param nada
  * @return nada
  **/
function validarContato() {
	if (validaForm("form-contato")) {
		var str = $("#form-contato").serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-contato.php",
			data: str,
			beforeSend: function() {
			},
			success: function(txt) {
				if(getTrim(txt)=='captcha'){

					$.getErro("Erro: Código de segurança não confere.");
				}else{
					$.getSucesso("Mensagem enviada com sucesso! Obrigado!");
					document.getElementById("form-contato").reset();
				}
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}


/**
  * Função validar
  * @param form: id do form
  * @return nada
  **/
function validarComPost(form) {
	if (validaForm(form)) {
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-" + form + ".php",
			data: str,
			beforeSend: function() {
			},
			success: function(txt) {
				$.getSucesso("Mensagem enviada com sucesso! Obrigado!");
				document.getElementById(form).reset();
				$.facebox.close();
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}

/**
  * Função limpa espaço
  * @param str String
  * @return nada
  **/
function getTrim(str) {
	return str.replace(/^\s+|\s+$/g, "");
}

/**
  * Função monta caixa de seleção
  * @param div DIV
  * @param id Identificador
  * @return nada
  **/
function montaCaixa(div, id) {
	$.ajax({
		type: "POST",
		url: "lib/acao-monta-caixa.php",
		data: 	"" + "div=" + div + "&" + "id=" + id + "&" + "",
		beforeSend: function() {
		},
		success: function(txt) {
			$("#" + div).html(txt);
		},
		error: function(txt) {
			//alert("Erro: " + txt);
		}
	});
}

/**
  * Função validar cliente
  * @param nada
  * @return nada
  **/
function validarCliente() {
	if (validaForm("form-cliente")) {
        $(document).ready(function() {
			$("#form-cliente").ajaxForm(function(txt) {
				/**
				   * 0 - Não foi possível cadastrar o cliente, tente novamente!
				   * 1 - Cadastro alterado com sucesso!
				   * 2 - Login já cadastrado, tente novamente!
				   * 3 - Senha e Confirma senha não conferem!
				   * 4 - CPF inválido!
				   * 5 - Cadastro realizado com sucesso!
				   **/
				if (getTrim(txt) == 0) {
					$.getErro("Não foi possível cadastrar o cliente, tente novamente!");
				} else if (getTrim(txt) == 1) {
					$.getSucesso("Cadastro alterado com sucesso!");
					window.location = "index.php?cmd=restrita-cadastro";
				} else if (getTrim(txt) == 2) {
					$.getErro("Login já cadastrado, tente novamente!");
				} else if (getTrim(txt) == 3) {
					$.getErro("Senha e Confirma senha não conferem!");
				} else if (getTrim(txt) == 4) {
					$.getErro("CPF inválido!");
				} else if (getTrim(txt) == 5) {
					$.getSucesso("Cadastro realizado com sucesso!");
					window.location = "index.php?cmd=restrita-inserir";
				} else {
					$.getErro("Não foi possível cadastrar o cliente, tente novamente!");
				}
			});
		});
	}
}

/**
  * Função validar login home
  * @param nada
  * @return nada
  **/
function validarLoginHome() {
	if (validaForm("form-login-home")) {
		var str = $("#form-login-home").serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-restrita-login-home.php",
			data: str,
			beforeSend: function() {
			},
			success: function(txt) {
				if (getTrim(txt) == 1) {
					window.location = "index.php?cmd=restrita-relatorios";
				} else if (getTrim(txt) == 2) {
					$.getErro("Seu cadastrado foi bloqueado. Por favor entre em contato com administração do Navegue Imóveis.");
				} else {
					alert("Login ou senha inválido!");
					window.location = "index.php?cmd=restrita-login";
					return false;
				}
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}

/**
  * Função validar login
  * @param nada
  * @return nada
  **/
function validarLogin() {
	if (validaForm("form-login")) {
		var str = $("#form-login").serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-restrita-login.php",
			data: str,
			beforeSend: function() {
			},
			success: function(txt) {
				if (getTrim(txt) == 1) {
					window.location = "index.php?cmd=restrita-relatorios";
				} else if (getTrim(txt) == 2) {
					$.getErro("Seu cadastrado foi bloqueado. Por favor entre em contato com administração do Navegue Imóveis.");
				} else {
					$.getErro("Login ou senha inválido!");
				}
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}

/**
  * Função validar lembrar senha
  * @param nada
  * @return nada
  **/
function validarLembrarSenha() {
	if ($("#lem_login").val() == "") {
		$.getErro("Digite seu login");
		document.getElementById("lem_login").style.backgroundColor = "#666";
		document.getElementById("lem_login").style.color = "#FFF";
		document.getElementById("lem_login").focus();
		return false;
	} else {
		$.ajax({
			type: "POST",
			url: "lib/acao-restrita-lembar-senha.php",
			data: "login=" + $("#lem_login").val(),
			beforeSend: function() {
			},
			success: function(txt) {
				/**
				   * 0 - Senha alterada com sucesso!
				   * 1 - Não foi possível trocar sua senha, tente novamente!
				   * 2 - Login incorreto!
				   **/
				if (getTrim(txt) == 0) {
					$.getSucesso("Nova senha enviada para seu e-mail!");
					document.getElementById("div_login").style.display = "";
					document.getElementById("div_lembrar_senha").style.display = "none";
					document.getElementById("form-login").reset();
				} else if (getTrim(txt) == 1) {
					$.getErro("Não foi possível trocar sua senha, tente novamente!");
				} else if (getTrim(txt) == 2) {
					$.getErro("Login incorreto!");
				} else if (getTrim(txt) == 3) {
					$.getErro("Seu cadastrado foi bloqueado. Por favor entre em contato com administração do Navegue Imóveis.");
				} else {
					$.getErro("Não foi possível trocar sua senha, tente novamente!");
				}
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}

/**
  * Função envia dados
  * @param form Identificador do form
  * @return nada
  **/
function enviaDados(form) {
	if (validaForm(form)) {
        $(document).ready(function() {
            $("#"+form).ajaxForm(function(txt) {
				if(getTrim(txt)=='captcha'){
					$.getErro("Erro: Código de segurança não confere.");
				}else{
					$.getSucesso("Mensagem enviada com sucesso!");
					document.getElementById(form).reset();
					$("input:file").MultiFile("reset");
					if (form == "form-encontramos") {
						window.location = "index.php?cmd=encontramos-por-voce";
					}
				}
            });
        });
	}
}

/**
  * Função envia dados
  * @param form Identificador do form
  * @return nada
  **/
function enviaDadosImovel(form) {
	if (validaFormAlerta(form)) {
        $(document).ready(function() {
            $("#"+form).ajaxForm(function(txt) {
				if(getTrim(txt) == 'captcha'){
					alert("Erro: Código de segurança não confere.");
				}else{
					//$.getSucesso("Proposta enviada com sucesso!");
					alert("Proposta enviada com sucesso!");
					window.location = "index.php?cmd=imovel&id=" + $("#id").val();
					return false;
					//document.getElementById(form).reset();
					//$("input:file").MultiFile("reset")
				}
            });
        });
	}
}

/**
  * Função envia dados
  * @param form Identificador do form
  * @return nada
  **/
function enviaDados2(form,id) {
	if (validaForm(form)) {
		$('#' + form).submit();
        $(document).ready(function() {
            $("#" + form).ajaxForm(function() {
				$('#' + id).html("Anúncio enviado com sucesso!");
				document.getElementById(form).reset();
				$("input:file").MultiFile("reset")
            });
        });
	}
}

/**
  * Função envia dados
  * @param form Identificador do form
  * @return nada
  **/
function enviaDadosVendaRapida(form,id) {

	if (validaForm(form)) {
        $(document).ready(function() {
            $("#"+form).ajaxForm(function(txt) {
				if(getTrim(txt)=='captcha'){
					$.getErro("Erro: Código de segurança não confere.");
				}else{

					$('#venda_rapida_mensagem_retorno').html("Dados enviados com sucesso!");
					$.getSucesso("Mensagem enviada com sucesso!");
					document.getElementById(form).reset();
					$("input:file").MultiFile("reset");

					$('#aba-cadastro-2').removeClass("habilitada");
					$('#aba-cadastro-2').addClass("desabilitada");

					$('#aba-cadastro-3').removeClass("desabilitada");
					$('#aba-cadastro-3').addClass("habilitada");

					$('#aba-2').hide("fast");
					$('#aba-3').show("slow");
				}
            });
        });


	}

	/*
	if (validaForm(form)) {
        $(document).ready(function() {
            $("#" + form).ajaxForm(function() {
				$('#' + id).html("Anuncio enviado com sucesso!");
				document.getElementById(form).reset();
				$("input:file").MultiFile("reset")
            });
        });

		$('#aba-cadastro-2').removeClass("habilitada");
		$('#aba-cadastro-2').addClass("desabilitada");

		$('#aba-cadastro-3').removeClass("desabilitada");
		$('#aba-cadastro-3').addClass("habilitada");

		$('#aba-2').hide("fast");
		$('#aba-3').show("slow");

	}*/
}

/**
  * Função abilita lembrar senha
  * @param form Identificador do form
  * @return nada
  **/
function abilitaLembrarSenha() {
	document.getElementById("div_login").style.display = "none";
	document.getElementById("div_lembrar_senha").style.display = "";
}

/**
  * Função excluir imovel
  * @param nada
  * @return nada
  **/
function excluirImovel(id) {
	if(confirm('Confirma a exclusao?')){
		$.ajax({
			type: "GET",
			url: "lib/acao-restrita-excluir-imovel.php",
			data: "id=" + id,
			beforeSend: function() {
			},
			success: function(txt) {
				/**
				   * 0 - Imóvel excluido com sucesso!
				   * 1 - Não foi possível excluir o imóvel, erro com a conexão de banco de dados, tente novamente!
				   * 2 - Imóvel não encontrado, tente novamente!
				   * 3 - Você não está logado, tente novamente!
				   * 4 - Não foi possível excluir o imóvel, tente novamente!
				   **/
				if (getTrim(txt) == 0) {
					$.getSucesso("Imóvel excluido com sucesso!");
				} else if (getTrim(txt) == 1) {
					$.getErro("Não foi possível excluir o imóvel, erro com a conexão de banco de dados, tente novamente!");
				} else if (getTrim(txt) == 2) {
					$.getErro("Imóvel não encontrado, tente novamente!");
				} else if (getTrim(txt) == 3) {
					$.getErro("Você não está logado, tente novamente!");
				} else if (getTrim(txt) == 4) {
					$.getErro("Não foi possível excluir o imóvel, tente novamente!");
				} else {
					$.getErro("Não foi possível excluir o imóvel, tente novamente!");
				}
				window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}

/**
  * Formata número
  * @param $campo int id
  * @param $event Evento
  * @return String
  **/
function formataNumero(campo, e) {
	t = typeof window.event != "undefined" ? window.event.keyCode : e.which;
	if((isNaN(String.fromCharCode(t)) || (t == 32)) && (t != 8 && t != 0)) {
		return false;
	}
}

/**
  * Formata a número decimal máscara
  * @param obj String campo que será atualizado
  * @return void
  **/
function mascara_num(obj) {
	valida_num(obj)
	valor = obj.value.replace("-","");
	valor = valor.replace(",","");
	if (valor.length >= 3) {
		valor = poe_ponto_num(valor.substring(0,valor.length-2))+","+valor.substring(valor.length-2, valor.length);
	}
	obj.value = valor;
}

/**
  * Formata a número decimal colocando os pontos
  * @param valor String campo que será atualizado
  * @return void
  **/
function poe_ponto_num(valor) {
	valor = valor.replace(/\./g,"");
	if (valor.length > 3) {
		valores = "";
		while (valor.length > 3) {
			valores = "."+valor.substring(valor.length-3,valor.length)+""+valores;
			valor = valor.substring(0,valor.length-3);
		}
		return valor+""+valores;
	} else {
		return valor;
	}
}

/**
  * Formata a número decimal valida número
  * @param obj String campo que será atualizado
  * @return void
  **/
function valida_num(obj) {
	numeros = new RegExp("[0-9]");
	while (!obj.value.charAt(obj.value.length-1).match(numeros)) {
		if(obj.value.length == 1 && obj.value == "-") {
			return true;
		}
		if(obj.value.length >= 1) {
			obj.value = obj.value.substring(0,obj.value.length-1);
		} else {
			return false;
		}
	}
}

/**
  * Função envia dados
  * @param form Identificador do form
  * @return nada
  **/
function validarImovel() {
	if (validaForm("form-imovel")) {

		$("#bt-imovel-inserir").attr("style", "visibility:hidden;");
		$("#msg-inserir-imovel").attr("style", "visibility:visible;");


		$(document).ready(function() {
            $("#form-imovel").ajaxForm(function(txt) {
				//alert(txt);
				/**
				   * 0 - Não foi possível cadastrar o imóvel, tente novamente!
				   * 1 - Imóvel cadastrado com sucesso!
				   * 2 - Escolha o plano de divulgação!
				   * 3 - Imóvel alterado com sucesso!
				   **/
				/*if (getTrim(txt) == 0) {
					//alert("Não foi possível cadastrar o imóvel, tente novamente!");
					//$("#bt-imovel-inserir").attr("style", "visibility:visible;");
					//$("#msg-inserir-imovel").attr("style", "visibility:hidden;");
					//return false;
					alert("Imóvel cadastrado com sucesso!");
					window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
				} else*/ if (getTrim(txt) == 1) {
					alert("Imóvel cadastrado com sucesso!");
					window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
				} else if (getTrim(txt) == 2) {
					alert("Escolha o plano de divulgação!");
					$("#bt-imovel-inserir").attr("style", "visibility:visible;");
					$("#msg-inserir-imovel").attr("style", "visibility:hidden;");
					return false;
				} else if (getTrim(txt) == 3) {
					alert("Imóvel alterado com sucesso!");
					window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
				} else {
					
					document.getElementById("div-barinsul").innerHTML = txt;
					//$("#div-barinsul").html(txt);
					//document.getElementById("form-banrisul").target = "_blank";
					
					if (document.getElementById("tp_pagamento_cartao").checked) {
						if (confirm("Imóvel cadastrado com sucesso!\n\nA forma de pagamento irá abrir em uma nova janela.\n\nO mesmo esta sendo enviado para seu e-mail.")) {
							//document.getElementById("form-banrisul").submit();
							$("#bt_enviar").click();
							window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 8000);
						} else {
							window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 8000);
						}
					} else {
						if (confirm("Imóvel cadastrado com sucesso!\n\nO boleto irá abrir em uma nova janela.\n\nO mesmo esta sendo enviado para seu e-mail.")) {
							//document.getElementById("form-banrisul").submit();
							$("#bt_enviar").click();
							window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 8000);
						} else {
							window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 8000);
						}
					}					
				}
            });
        });
	}
}

/**
  * Função define valor para um elemento
  * @param id do elemento
  * @param valor para o elemento
  * @return nada
  **/
function defineValor(id, valor) {
	$("#finalidade").val(valor);
}

/**
  * Função excluir imóvel foto
  * @param id Identificador
  * @return nada
  **/
function excluirFotoImovel(id) {
	if (confirm('Confirma a exclusao?')) {
		$.ajax({
			type: "GET",
			url: "lib/acao-restrita-excluir-imovel-foto.php",
			data: "id=" + id,
			beforeSend: function() {
			},
			success: function(txt) {
				/**
				   * 0 - Foto removida com sucesso!
				   * 1 - Não foi possível excluir a foto do imóvel, tente novamente!
				   **/
				if (getTrim(txt) == 0) {
					$.getSucesso("Foto removida com sucesso!");
					window.setTimeout('window.location = "index.php?cmd=restrita-inserir&id='+ $("#id").val() + '"', 1000);
				} else if (getTrim(txt) == 1) {
					$.getErro("Não foi possível excluir a foto do imóvel, tente novamente!");
				} else {
					$.getErro("Não foi possível excluir a foto do imóvel, tente novamente!");
				}
			},
			error: function(txt) {
				//$.getErro("Erro: " + txt);
			}
		});
	}
}

/**
  * Preferência de busca
  * @param id Identificador do imovel
  * @param acao Ação Inserir/Excluir
  * @return nada
  **/
function preferenciaBusca(id, acao) {
	$.ajax({
		type: "POST",
		url: "lib/acao-restrita-preferencia-busca.php",
		data: "id=" + id + "&acao=" + acao,
		beforeSend: function() {
		},
		success: function(txt) {
			if (getTrim(txt) == 1) {
				$.getSucesso("Preferência de busca realizada com sucesso!");
				window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
			} else if (getTrim(txt) == 2) {
				$.getSucesso("Preferência de busca excluida com sucesso!");
				window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
			} else {
				$.getErro(txt);
			}
		},
		error: function(txt) {
			//$.getErro("Erro: " + txt);
		}
	});
}

/**
  * Preferência de busca
  * @param img Imagem
   * @return nada
  **/
function trocaFoto(img) {
	$("#div_imagem_anunciante").attr("src", img);
}

/**
  * Destaque
  * @param id Identificador do imovel
  * @param acao Ação Inserir/Excluir
  * @return nada
  **/
function destaque(id, acao) {
	$.ajax({
		type: "POST",
		url: "lib/acao-restrita-destaque.php",
		data: "id=" + id + "&acao=" + acao,
		beforeSend: function() {
		},
		success: function(txt) {
			if (getTrim(txt) == 1) {
				alert("Destaque inserido sucesso!");
				window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
			} else if (getTrim(txt) == 2) {
				alert("Destaque excluido com sucesso!");
				window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
			} else {
				alert(txt);
			}
		},
		error: function(txt) {
			alert("Erro: " + txt);
		}
	});
}

/**
  * Faixa de valores
  * @param opcao
  * @return nada
  **/
function getSelecionaBuscaSuspensa(opcao) {
	if (opcao == 1) {
		$("#finalidade").val("1");
		$("#finalidade_d").val("1");
		$("#busca-suspensa").removeClass("bg-busca-suspensa");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-2");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-3");
		$("#busca-suspensa").addClass("bg-busca-suspensa-1");
	} else if (opcao == 2) {
		$("#finalidade").val("2");
		$("#finalidade_d").val("2");
		$("#busca-suspensa").removeClass("bg-busca-suspensa");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-1");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-3");
		$("#busca-suspensa").addClass("bg-busca-suspensa-2");
	} else if (opcao == 3) {
		$("#finalidade").val("3");
		$("#finalidade_d").val("3");
		$("#busca-suspensa").removeClass("bg-busca-suspensa");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-1");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-2");
		$("#busca-suspensa").addClass("bg-busca-suspensa-3");
	} else {
		$("#finalidade").val("2");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-1");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-2");
		$("#busca-suspensa").removeClass("bg-busca-suspensa-3");
		$("#busca-suspensa").addClass("bg-busca-suspensa");
	}
}

/**
  * Faixa de valores
  * @param opcao
  * @return nada
  **/
function getFaixaValores(opcao) {

	getSelecionaBuscaSuspensa(opcao);

	if (opcao == 2) {
		html = '<option value="">Valor</option>';
		html += '<option value="1">Até 100 mil</option>';
		html += '<option value="2">100 mil a 200 mil</option>';
		html += '<option value="3">200 mil a 300 mil</option>';
		html += '<option value="4">300 mil a 400 mil</option>';
		html += '<option value="5">400 mil a 500 mil</option>';
		html += '<option value="6">500 mil a 600 mil</option>';
		html += '<option value="7">600 mil a 700 mil</option>';
		html += '<option value="8">700 mil a 800 mil</option>';
		html += '<option value="9">800 mil a 900 mil</option>';
		html += '<option value="10">900 mil a 1 milhão</option>';
		html += '<option value="11">Acima de 1 milhão</option>';
	} else {
		html = '<option value="">Valor</option>';
		html += '<option value="1">R$ 0,00 a R$ 250,00</option>';
		html += '<option value="2">R$ 250,00 a R$ 500,00</option>';
		html += '<option value="3">R$ 500,00 a R$ 1.000,00</option>';
		html += '<option value="4">R$ 1.000,00 a R$ 1.500,00</option>';
		html += '<option value="5">R$ 1.500,00 a R$ 2.000,00</option>';
		html += '<option value="6">R$ 2.000,00 a R$ 2.500,00</option>';
		html += '<option value="7">R$ 2.500,00 a R$ 3.000,00</option>';
		html += '<option value="8">Acima de R$ 3.000,00</option>';
	}

	$("#select_valor").html(html);
}

/**
  * Validar busca suspensa
  * @param nada
  * @return Int Versão
  **/
function validarBuscaSuspensa() {
	if (($("#finalidade").val() != "") || ($("#cod_navegue").val() > 0)) {
		document.getElementById("form-busca").submit();
	} else {
		$.getErro("Selecione a finalidade: Aluguel, Venda ou Temporada.");
	}
}

/**
  * Atualiza statusm imovel
  * @param id Identificador do imovel
  * @param acao Ação
  * @return nada
  **/
function atualizaStatusImovel(id, acao) {
	$.ajax({
		type: "GET",
		url: "lib/acao-restrita-atualiza-status-imovel.php",
		data: "id=" + id + "&acao=" + acao,
		beforeSend: function() {
		},
		success: function(txt) {
			if (getTrim(txt) == 1) {
				$.getSucesso("Status atualizado com sucesso!");
				window.setTimeout('window.location = "index.php?cmd=restrita-lista"', 1000);
			} else {
				$.getErro("Não foi possível atualizar o status, tente novamente!");
			}
		},
		error: function(txt) {
			//$.getErro("Erro: " + txt);
		}
	});
}

/**
  * Faixa de valores
  * @param opcao
  * @return nada
  **/
function getFaixaValoresEncontramos(opcao) {
	if (opcao == 2) {
		html = '<option value="">Valor</option>';
		html += '<option value="Até 100 mil">Até 100 mil</option>';
		html += '<option value="100 mil a 200 mil">100 mil a 200 mil</option>';
		html += '<option value="200 mil a 300 mil">200 mil a 300 mil</option>';
		html += '<option value="300 mil a 400 mil">300 mil a 400 mil</option>';
		html += '<option value="400 mil a 500 mil">400 mil a 500 mil</option>';
		html += '<option value="500 mil a 600 mil">500 mil a 600 mil</option>';
		html += '<option value="600 mil a 700 mil">600 mil a 700 mil</option>';
		html += '<option value="700 mil a 800 mil">700 mil a 800 mil</option>';
		html += '<option value="800 mil a 900 mil">800 mil a 900 mil</option>';
		html += '<option value="900 mil a 1 milhão">900 mil a 1 milhão</option>';
		html += '<option value="Acima de 1 milhão">Acima de 1 milhão</option>';
	} else {
		if (opcao != "") {
			html = '<option value="">Valor</option>';
			html += '<option value="R$ 0,00 a R$ 250,00">R$ 0,00 a R$ 250,00</option>';
			html += '<option value="R$ 250,00 a R$ 500,00">R$ 250,00 a R$ 500,00</option>';
			html += '<option value="R$ 500,00 a R$ 1.000,00">R$ 500,00 a R$ 1.000,00</option>';
			html += '<option value="R$ 1.000,00 a R$ 1.500,00">R$ 1.000,00 a R$ 1.500,00</option>';
			html += '<option value="R$ 1.500,00 a R$ 2.000,00">R$ 1.500,00 a R$ 2.000,00</option>';
			html += '<option value="R$ 2.000,00 a R$ 2.500,00">R$ 2.000,00 a R$ 2.500,00</option>';
			html += '<option value="R$ 2.500,00 a R$ 3.000,00">R$ 2.500,00 a R$ 3.000,00</option>';
			html += '<option value="Acima de R$ 3.000,00">Acima de R$ 3.000,00</option>';
		} else {
			html = '<option value="">Valor</option>';
		}
	}

	$("#ds_valor_de_venda").html(html);
}

function btsBusca(id){

	if(id == "bt-aluguel"){
		$("#bt-aluguel").attr("class","bt-aluguel-active");
		$("#bt-vendas").attr("class","bt-vendas");
		$("#bt-temporada").attr("class","bt-temporada");
	}else if(id == "bt-vendas"){
		$("#bt-aluguel").attr("class","bt-aluguel");
		$("#bt-vendas").attr("class","bt-vendas-active");
		$("#bt-temporada").attr("class","bt-temporada");
	}else if(id == "bt-temporada"){
		$("#bt-aluguel").attr("class","bt-aluguel");
		$("#bt-vendas").attr("class","bt-vendas");
		$("#bt-temporada").attr("class","bt-temporada-active");
	}

}

function clickTelephoneView(cmd,id){
	$.ajax({
		type: "POST",
		url: "lib/acao-cliente-telefone-view.php",
		data: "id=" + id + "&cmd=" + cmd,
		beforeSend: function() {
		},
		success: function(txt) {
		},
		error: function(txt) {
		}
	});

}

/**
  * Função validar resposta
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarResposta(form) {
	if (validaForm(form)) {
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-resposta.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				} else if (getTrim(txt) == "1") {
					alert("Mensagem enviada com sucesso.");
					document.getElementById(form).reset();
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar resposta
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarFinanciamento(form) {
	if (validaForm(form)) {
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-financiamento.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				} else if (getTrim(txt) == "1") {
					alert("Em breve entraremos em contato sobre sua solicitação de financiamento.");
					document.getElementById(form).reset();
					if (document.getElementById("fin_imovel")) {
						window.location = "index.php?cmd=imovel&id=" + document.getElementById("fin_imovel").value;
					} else {
						window.location = "index.php?cmd=financiamento";
					}
					return false;
				} else if(getTrim(txt) == "captcha") {
					alert("Erro: Código de segurança não confere.");
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}

/**
  * Função validar resposta
  * @param form Identificador do form
  * @return mensagem de erro
  **/
function validarSeguroAluguel(form) {
	if (validaForm(form)) {
		var str = $("#" + form).serialize();
		$.ajax({
			type: "POST",
			url: "lib/acao-form-seguro-aluguel.php",
			data: str,
			success: function(txt) {
				if (getTrim(txt) == "0") {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				} else if (getTrim(txt) == "1") {					
					alert("Em breve entraremos em contato sobre sua solicitação de seguro aluguel.");
					document.getElementById(form).reset();
					if (document.getElementById("fin_imovel")) {
						window.location = "index.php?cmd=imovel&id=" + document.getElementById("fin_imovel").value;
					} else {
						window.location = "index.php?cmd=seguro-aluguel";
					}
					return false;
				} else if(getTrim(txt) == "captcha") {
					alert("Erro: Código de segurança não confere.");
				} else {
					alert("Não foi possível enviar a mensagem, tente novamente.");
				}
			}
		});
	}
}
