
//==================================================================================================================//
//jQuery personalizado

(function($) {
	$.fn.extend({
	//--------------------------------------------------------------------------------------------------------------//
	//Inputs com valor de legenda
		
		legenda : function() {
		
			$(this).each(function() {
		
				//salvar legenda
				var legenda = $(this).val();
				
				//eventos
				$(this)
				.focus(function() { if($(this).val() == legenda) { $(this).val(""); } })
				.blur(function() { if($(this).val() == "") { $(this).val(legenda); } });
			
			});
			
			//retornar seletor
			return this;

		},
		
	//--------------------------------------------------------------------------------------------------------------//
	//Criar hack para PNG transparente no IE6
	
		hackPng : function(tipo) {
		
			var tipo = tipo || "crop";
			
			//caso seja IE6
			if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
	
				//para cada item
				this.each(function() {
				
					//caminho da imagem
					var png = $(this).css("background-image").split('"')[1];
					
					//adicionar filter
					$(this).css({
						"background-image" : "none",
						"filter" : "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=" + tipo + ", src='" + png + "')"
					});
					
				});
			
			}
			
			//seletor
			return this;
		}
		
	//--------------------------------------------------------------------------------------------------------------//
	});
})(jQuery);

//==================================================================================================================//
//onLoad

$(document).ready(function() {

	//Variáveis da página
	var request = new getQuery();
	
	//Class da seção
	$("body").attr("class",request.secao);

	//Inputs com valor de legenda
	$("input:text[value!=''], input:password[value!='']").legenda();
	
	//Abas de índices
	$(".abas Dt, .abas b").click(function() { indices.aba(this); } );
	
	//Mapa do contato
	if($("body").hasClass("contato")) { mapsApi(); }
	
	//Thumbs do detalhe
	if($("#conteudo .fotos").size() > 0) { fotos.thumb(request.secao, request.imovel_id, request.npg, request.container_id); }
	
	//PNG no IE6
	$("#topo .abas .tempo dt").hackPng();
	
});

//==================================================================================================================//
//Retornar querystring

function getQuery() {
	
	//buscar querystring
	this.queryText = window.location.search.replace("?","");
	var queryArray = this.queryText.split("&");
	
	//valores esperados
	this.secao = "home";
	
	//para cada valor
	for (var i = 0; i < queryArray.length; i++) {
		if(queryArray[i]) {
			var inQuery = queryArray[i].split("=");
			eval("this." + inQuery[0] + " = " +  "'" + inQuery[1] + "'");
		}
	}
	
}

//==================================================================================================================//
//Validar e enviar formulários

function enviaForm(quem) {
	
	var formulario = $(quem).parent();
	var labels = formulario.find("label");

	//verificar campos
	labels.filter(".check, .erro, .ok").each(function() {
		var classe = ($(this).next().val().length > 0) ? "ok" : "erro";
		$(this).add($(this).next()).attr("class", classe);
	});
	
	//se estiver ok, enviar
	if(!labels.is(".erro")) {
		$(quem).text("enviando");
		formulario.submit();
	}

}

//==================================================================================================================//
//Índices do topo

var indices = {

	//abrir e fechar abas
	aba: function(quem) { $(quem).parents("Dl").find("dt, dd").slideToggle(); },
	
	//formulário de login
	logar: function() {
	
		var check = true;
		var campos = $(".abas .restrita input");
		
		//validar campos
		campos.each(function(){
		
			if($(this).val() == $(this).attr("name") || $(this).val() == "") {
				check = false;
				$(this).attr("class","erro");
			}
			else { $(this).attr("class","ok"); }
		
		});
		
		//campos preenchidos, acionar login
		if(check) {
		
			//valor dos campos
			var dados = {
				"logar" : campos.eq(0).val(),
				"login" : campos.eq(1).val(),
				"senha" : campos.eq(2).val()
			};
		
			//aciona ajax
			//$.get("conteudo/server/login.html", dados, function(data) {
			$.get("admin/index.php", dados, function(data) {
				//resposta do login
				if(data != "false") { 
					window.location.href = 'admin/index.php?locar='+dados.logar+'&login='+dados.login+'&senha='+dados.senha+'&secao=imovel'; 
					//window.location.href = data; 
				} else { 
					indices.msg("login ou senha incorretos"); 
				}
			
			});
		
		}
		//mensagem de erro
		else { indices.msg("preencha os campos corretamente"); }
		
	},
	
	//aviso
	msg: function(txt) {
	
		var target = $(".abas .restrita dd");
		var msgDiv = (target.find(".msg").length > 0) ? target.find(".msg") : $("<div />").addClass("msg").appendTo(target) ;
		
		//exibir mensagem
		msgDiv.text(txt).fadeIn().click(function() { $(this).fadeOut(); });
		
		//fechar após 3 segundos
		if(indices.tempo) { indices.tempo = window.clearTimeout(indices.tempo); }
		indices.tempo = window.setTimeout(function() { msgDiv.trigger("click"); }, 3000);
	
	}

}

//==================================================================================================================//
//Fotos

var fotos = {
	
	//ver foto ampliada
	zoom : function(quem) {
		$("#conteudo .fotos > Img").attr("src", $(quem).attr("src").replace("114", "442").replace("81", "315"));

		/*
		// Aciona um titulo e u texto específico para cada imagem
		var s = document.getElementById(quem.id).parentNode.getElementsByTagName('span');
		document.getElementById('tituloGaleria').innerHTML = s[0].innerHTML;
		document.getElementById('textoGaleria').innerHTML = s[1].innerHTML;
		*/
	},
	
	//carregar thumbs
	thumb : function(engine, imovel_id, pagina, container_id) {
		
		engine = engine || "imoveis"
		pagina = pagina || 0;
		
		//criar div
		var thumbs = ($("#conteudo .fotos .thumbs").size() > 0) ? $("#conteudo .fotos .thumbs") :
		$("<div class='thumbs' />").appendTo($("#conteudo .fotos"));
		
		//acionar ajax
		thumbs.load("thumb.php?secao=" + engine + "&npg=" + pagina + '&imovel_id=' + imovel_id + '&container_id=' + container_id);
		
	}
	
};

//==================================================================================================================//
//Contato

function mapsApi() {
	
	//inserir iframe
	$("<iframe />").attr("id","mapa").attr("name", "api").attr("src","templates/server/mapa.html")
	.insertAfter("#conteudo .cabecalho")
	
}

//==================================================================================================================//





