// JavaScript Document
$(document).ready(function()
{
	var page = 1;	
	$('#refineBusca').hide();
	
	$('#retorno-imoveis li a,#outros-imoveis li a').css({'cursor':'pointer'})
	$('#retorno-imoveis li a').live('click',function(e){
		e.preventDefault();		
		window.location=$(this).attr('href');
	})
	
	/************* CAMPOS DE PESQUISAS *******/	
	function envia_pesquisa()
	{
		var campos = '';
    	//campos = $(this).attr('id')+'='+$(this).val();
		campos = $('#fBusca').serialize();
		$.ajax({
	       	type: 'post',
	        data: campos,
	        url: '/busca.php',
	        success:
	            function(retorno)
	            {
	                $('#busca_principal').html(retorno);
	                $('#combo_operacao,#combo_uf,#combo_bairro,#combo_cidade,#combo_tipo_imovel,#combo_valores').change(envia_pesquisa);
	            }
	        });			
	  }		
	
	$('#combo_operacao,#combo_uf,#combo_bairro,#combo_cidade,#combo_tipo_imovel,#combo_valores').change(envia_pesquisa);	
	
	$("#fBusca input[type='image'],#paginacao a,#btn-busca-refinada").live('click',function(e){
		e.preventDefault();
		//alert(e.target.nodeName);				
		var campo_scroll = '#fBusca';
		if(e.target.nodeName=='A')
		{			
			var campos = $('#fBusca').serialize();
			campo_scroll = 'h2.titulo';
			
			if($(this).attr('class')=='mais-pagina' || $(this).attr('class')=='menos-pagina')
			{
				campos += '&VAR_PAGINA_CONTINUA='+$(this).attr('rel')+'&';
				if($(this).attr('class')=='mais-pagina')
					campos += '&VAR_PAGINA='+$(this).attr('rel')+'&';
				else
				{
					pagina = Number($(this).attr('rel'))+9;
					campos += '&VAR_PAGINA='+pagina+'&';					
				}
				
			}
			else
			{
				
				campos += '&VAR_PAGINA='+$(this).html()+'&';
				campos += '&VAR_PAGINA_CONTINUA='+$(this).attr('rel')+'&';
			}
			$.ajax({
		       	type: 'post',
		        data: campos,
		        url: '/resultado_busca.php',
		        success:
		            function(retorno)
		            {
		                $('#banner').remove();
						$('#aba').html(retorno); 
						$('#refineBusca').hide();
						$('#btn-refinar').show();
						$(window).scrollTop($(campo_scroll).offset().top);
						$('#combo_operacao,#combo_uf,#combo_bairro,#combo_cidade,#combo_tipo_imovel,#combo_valores').change(envia_pesquisa);
		            }
		        });			
		}
		else
		{
			//$('#direita').load('alto_padrao.php');
			if($(this).attr('id')=='btn-busca-refinada')
			{	
				$('#btn-refinar').show();
				//$('#refineBusca').submit();
				//pesquisa.php?NM_VL_QNT_DORMITORIO=2&NM_VL_QNT_SUITE=6&NM_VL_QNT_GARAGEM=6
				window.location = /refinada/+$('#NM_VL_QNT_DORMITORIO').val()+'/'+$('#NM_VL_QNT_SUITE').val()+'/'+$('#NM_VL_QNT_GARAGEM').val();
			}
			else
			{	
				//$("#fBusca").attr('action','pesquisa.php');
				//$("#fBusca").attr('method','get');
				//$('#fBusca').submit();
				//pesquisa.php?combo_operacao=VENDA&combo_uf=1&combo_cidade=3&combo_bairro=21&combo_tipo_imovel=1&combo_valores=2
				//
				operacao = $.trim($('#combo_operacao').val().toLowerCase());
				if(operacao!='')
				{	
					cidade = $.trim($('#combo_cidade').val());
					cidade = (cidade=='')?0:cidade;
					window.location = '/pesquisa/'+$('#combo_operacao').val().toLowerCase()+'/'+$('#combo_uf').val()+'/'+cidade+'/'+$('#combo_bairro').val()+'/'+$('#combo_tipo_imovel').val()+'/'+$('#combo_valores').val();
				}
				else
					alert('Selecione a operação.');
			}			
		}
		
		/*if($(this).attr('id')=='btn-busca-refinada')
		{	
			campos += '&NM_VL_QNT_SUITE='+$('#NM_VL_QNT_SUITE').val()+'&NM_VL_QNT_DORMITORIO='+$('#NM_VL_QNT_DORMITORIO').val()+'&NM_VL_QNT_GARAGEM='+$('#NM_VL_QNT_GARAGEM').val();			
		}
		$.ajax({
	       	type: 'post',
	        data: campos,
	        url: 'resultado_busca.php',
	        success:
	            function(retorno)
	            {
	                $('#banner').remove();
					$('#aba').html(retorno); 
					$('#refineBusca').hide();
					$(window).scrollTop($(campo_scroll).offset().top);
					$('#combo_uf,#combo_bairro,#combo_cidade,#combo_tipo_imovel,#combo_valores').change(envia_pesquisa);
	            }
	        }); */
		
	 });
	$("#paginacao-dados a").live('click',function(e){
		e.preventDefault();
		var arquivo = $(this).parent().attr('rel');
		var campo_scroll = 'h2.titulo';

		
		if($(this).attr('class')=='mais-pagina' || $(this).attr('class')=='menos-pagina')
		{
			$('#VAR_PAGINA_CONTINUA').val($(this).attr('rel'));			
			if($(this).attr('class')=='mais-pagina')
				$('#VAR_PAGINA').val($(this).attr('rel'));				
			else
			{
				pagina = Number($(this).attr('rel'))+9;
				$('#VAR_PAGINA').val(pagina);
			}
			
		}
		else
		{
			$('#VAR_PAGINA').val($(this).html());
			$('#VAR_PAGINA_CONTINUA').val($(this).attr('rel'));
		}
		
		$('#fFavoritos').submit();		
	 });	
	$("#paginacao-relacionados a,#btn-relacionados a").live('click',function(e){
		e.preventDefault();
		var campos = '&cd_tipo_imovel='+$('#fRelacionados #cd_tipo_imovel').val()+'&vl_imovel='+$('#fRelacionados #vl_imovel').val()+'&cd_imovel='+$('#fRelacionados #cd_imovel').val()+'&tx_operacao='+$('#fRelacionados #tx_operacao').val()+'&cd_bairro='+$('#fRelacionados #cd_bairro').val();
		if($(this).attr('rel')=='preco' || $(this).attr('rel')=='bairro')
			campos += '&tx_relacao='+$(this).attr('rel');	
		else
		{
			campos += '&tx_relacao='+$('#fRelacionados #tx_relacao').val();
			campos += '&VAR_PAGINA='+$(this).html()+'&';
			campos += '&VAR_PAGINA_CONTINUA='+$(this).attr('rel')+'&';
		}
		$.ajax({
	       	type: 'post',
	        data: campos,
	        url: '/relacionados.php',
	        success:
	            function(retorno)
	            {
					$('#direita').html(retorno); 
					$('#combo_operacao,#combo_uf,#combo_bairro,#combo_cidade,#combo_tipo_imovel,#combo_valores').change(envia_pesquisa);
	            }
	        });			
	 });
	$('#conteudo_2 #mais-outros-imoveis a,#conteudo_2 #menos-outros-imoveis a').live('click',function(e){
		e.preventDefault(); 
		$(window).scrollTop($('#mais-imoveis').offset().top);
		$('#outros-imoveis').load('/outros.php',{'VAR_PAGINA':$(this).attr('rel')});
	});
	/************* BANNER *******/
	// setTimeout
	/*var banner = setInterval(function(){
										page++;
										page = (page>$('#VL_TOTAL_DESTAQUE').val()) ? 1 : page;
										$('#banner-destaque').load('carrega_arquivo.php',{'page':page,'AR_TITULO':$('#AR_TITULO').val(),'AR_DESCRICAO':$('#AR_DESCRICAO').val(),'AR_ARQUIVO':$('#AR_ARQUIVO').val(),'VL_TOTAL_DESTAQUE':$('#VL_TOTAL_DESTAQUE').val(),'AR_LINK':$('#AR_LINK').val()});				
									},10000); */
	var banner = null;
	banner = setTimeout(fn_banner,11000);
	
	function fn_banner()
	{
		page++;
		page = (page>$('#VL_TOTAL_DESTAQUE').val()) ? 1 : page;
		$('#banner-destaque').load('carrega_arquivo.php',{'page':page,'AR_TITULO':$('#AR_TITULO').val(),'AR_DESCRICAO':$('#AR_DESCRICAO').val(),'AR_ARQUIVO':$('#AR_ARQUIVO').val(),'VL_TOTAL_DESTAQUE':$('#VL_TOTAL_DESTAQUE').val(),'AR_LINK':$('#AR_LINK').val()});
		banner = null;
		banner = setTimeout(fn_banner,15000);
	}
	
	$('#pages li a').live('click',function(e){
		 e.preventDefault();
		 clearInterval(banner);
		 page = $(this).attr('rel');
		 $('#banner-destaque').load('carrega_arquivo.php',{'page':page,'AR_TITULO':$('#AR_TITULO').val(),'AR_DESCRICAO':$('#AR_DESCRICAO').val(),'AR_ARQUIVO':$('#AR_ARQUIVO').val(),'VL_TOTAL_DESTAQUE':$('#VL_TOTAL_DESTAQUE').val(),'AR_LINK':$('#AR_LINK').val()});
		 banner = null;
		 banner = setTimeout(fn_banner,15000);
	})
	
	
	/************* NEWSLETTER *******/
	
	$("#fNewsletter input[type='image']").live('click',function(e){
		e.preventDefault();
		var posicao = $('#newsletter_email').position();		
		$.post('/grava.php',{'VAR_SUBMIT':'OK','newsletter_email':$('#newsletter_email').val(),'VAR_GRAVA':'EMAIL'},function(retorno){
				eval(retorno);
				$("#resposta-email").css({'left':posicao.left+'px'});
				$('#newsletter_email').val('');
		});
	})
	
	/************* BUSCA REFERENCIA *******/
	$("#fReferencia input[type='image']").live('click',function(e){
		e.preventDefault();
		var posicao = $('#referencia').position();	
		var referencia = $.trim($('#referencia').val());
		if(referencia!='')
		{
			window.location='/referencia/'+referencia;
			//$("#fReferencia").submit();
		}
		else
		{			
			$("#fReferencia").prepend("<p id=\"resposta-referencia\">Informe a referência.</p>");
			$("#resposta-referencia").css({'left':posicao.left+'px'});
			setTimeout(function(){$("#resposta-referencia").remove(); $("#referencia").focus(); },3000)			
		}
	})

	/************* BUSCA BOTAO RETORNO *******/
	$("#retorno-busca").live('click',function(e){
		e.preventDefault();
		history.go(-1);
		/*var rel = $(this).attr('rel');
		if(rel=='HOME' || rel=='OUTROS')
		{	
			if(rel=='OUTROS')
				window.location = 'index.php#mais-imoveis';		
			else
			{	
				var complemento = $(this).attr('href');
				complemento = (complemento!='index.php')?'?cd='+complemento:'';				
				window.location = 'index.php'+complemento+'#aba';				
			}
		}
		else
			{
				var campos = $('#fBusca').serialize();
				$('#direita').load('alto_padrao.php');
				$.ajax({
			       	type: 'post',
			        data: campos,
			        url: 'resultado_busca.php',
			        success:
			            function(retorno)
			            {
			                $('#banner').remove();
							$('#aba').html(retorno); 
							$('#refineBusca').hide();
							$(window).scrollTop($('#fBusca').offset().top);
							$('#combo_uf,#combo_bairro,#combo_cidade,#combo_tipo_imovel,#combo_valores').change(envia_pesquisa);
			            }
			        });					
			}*/
			
	})	
	
	/************* BUSCA REFINADA *******/	
	$("#btn-refinar").live('click',function(e){
		e.preventDefault();
		$('#refineBusca').show();		
		$(this).hide();
	})
	$("#refineBusca #cancela").live('click',function(e){
		e.preventDefault();
		$('#refineBusca').hide();		
		$('#btn-refinar').show();
	})
	/************* FORMULARIOS  *******/
	
	$("#fCadastro input[id='cancela']").live('click',function(e){
		e.preventDefault();
		$("input[type='text']").val('');
		$("select").val('');
		$("textarea").val('');		
		$("input[type='checkbox']").attr('checked','');
	})	
	$("#fCadastro input[id='envia']").live('click',function(e){		
		e.preventDefault();
		var x = 0;
		$("#resposta").remove();
		$('#fCadastro .obrigatorio').each(function(e){
			   
			   $(this).parent().removeClass('obrigatorio-selecionado');	
			   
			   if($.trim($(':input',this).val())=='')
				{
					$(this).parent().addClass('obrigatorio-selecionado');
					x++;
				}	   
		   })
		$(window).scrollTop($('h2.titulo').offset().top);
		if(x>0)
		{
			$("#fCadastro").prepend("<p id=\"resposta\" class=\"retorno\">Preencha o(s) campo(s) em destaque.</p>");
		}
		else
		{			
			var campos = $("#fCadastro").serialize();
	    	campos += '&VAR_SUBMIT=OK&';    
			$.ajax({
		       	type: 'post',
		        data: campos,
		        url: '/grava.php',
		        success:
		            function(retorno)
		            {
						eval(retorno);						
		            }
		        });
		}
	})
	
	
	/************* FUNCAO FOTOS AMPLIADAS *******/	
	
	$('#fotos-imovel li a').live('click',function(e){
		e.preventDefault();
		$('#foto-ampliada').attr('src',$(this).attr('href'));
		
		$('#fotos-imovel li img').each(function(){
			 $(this).addClass('borda-foto');
		 })
		 foto = $(this).attr('rel');
		 $('img',this).addClass('foto-selecionada');		
		 $('img',this).removeClass('borda-foto');
		 if($.trim($(this).attr('title'))!='')
		 {	 
			 $('#legenda').html($(this).attr('title'));
		 	 $('#legenda').show();
		 }
		 else
			 $('#legenda').hide();
		 
		 $(window).scrollTop($('h2.titulo').offset().top);
	})	
	$('#fotos-imovel li span.proximo').live('click',function(e){
		e.preventDefault();
		var total_foto = 0;
		$('#fotos-imovel li img').each(function(){
			 $(this).addClass('borda-foto');
			 total_foto++;
		 })
		foto++; 
		total_foto--;
		foto = (foto>=total_foto)?0:foto;
		$("img","#fotos-imovel li a[rel='"+foto+"']").removeClass('borda-foto');
		$("img","#fotos-imovel li a[rel='"+foto+"']").addClass('foto-selecionada');
		$('#foto-ampliada').attr('src',$("#fotos-imovel li a[rel='"+foto+"']").attr('href'));
		 if($.trim($("#fotos-imovel li a[rel='"+foto+"']").attr('title'))!='')
		 {	 
			 $('#legenda').html($("#fotos-imovel li a[rel='"+foto+"']").attr('title'));
		 	 $('#legenda').show();
		 }
		 else
			 $('#legenda').hide();		
	})
	$('#fotos-imovel li span.anterior').live('click',function(e){
		e.preventDefault();
		var total_foto = 0;
		$('#fotos-imovel li img').each(function(){
			 $(this).addClass('borda-foto');
			 total_foto++;
		 })
		foto--; 
		total_foto--;
		foto = (foto<0)?total_foto-1:foto;
		$("img","#fotos-imovel li a[rel='"+foto+"']").removeClass('borda-foto');
		$("img","#fotos-imovel li a[rel='"+foto+"']").addClass('foto-selecionada');
		$('#foto-ampliada').attr('src',$("#fotos-imovel li a[rel='"+foto+"']").attr('href'));
		 if($.trim($("#fotos-imovel li a[rel='"+foto+"']").attr('title'))!='')
		 {	 
			 $('#legenda').html($("#fotos-imovel li a[rel='"+foto+"']").attr('title'));
		 	 $('#legenda').show();
		 }
		 else
			 $('#legenda').hide();				
	})	
	var foto = 0;
	$('#fotos-imovel li a img:first').addClass('foto-selecionada');
	if($.trim($('#legenda').html())=='')
		$('#legenda').hide();
	
	/************* FOTO MAIOR NO LIGHTBOX *******/
	
	$('#foto-ampliada').live('click',function(e){
		e.preventDefault();
		pleft=($(window).width()-650)/2;
		fn_add_tela(650,520,pleft,10);
		
		$("#CONTEUDO-JANELA").load('/foto_imovel.php',{'path':$(this).attr('src')},function(){
			 if($.trim($("#fotos-imovel li a[rel='"+foto+"']").attr('title'))!='')
			 {	 
				 $('#legenda-maior').html($("#fotos-imovel li a[rel='"+foto+"']").attr('title'));
			 	 $('#legenda-maior').show();
			 }
			 else
				 $('#legenda-maior').hide();				
			
		});	
	})
	$('#proxima-foto').live('click',function(e){
		e.preventDefault();
		var total_foto = 0;
		$('#fotos-imovel li img').each(function(){
			 $(this).addClass('borda-foto');
			 total_foto++;
		 })
		foto++; 
		total_foto--;
		foto = (foto>=total_foto)?0:foto;
		$("img","#fotos-imovel li a[rel='"+foto+"']").removeClass('borda-foto');
		$("img","#fotos-imovel li a[rel='"+foto+"']").addClass('foto-selecionada');
		var caminho_foto = $("#fotos-imovel li a[rel='"+foto+"']").attr('href');
		$('#foto-ampliada').attr('src',caminho_foto);
		caminho_foto = caminho_foto+'&LIMITE=640';
		$('#foto-lightbox').attr('src',caminho_foto);
		 if($.trim($("#fotos-imovel li a[rel='"+foto+"']").attr('title'))!='')
		 {	 
			 $('#legenda-maior,#legenda').html($("#fotos-imovel li a[rel='"+foto+"']").attr('title'));
		 	 $('#legenda-maior,#legenda').show();
		 }
		 else
			 $('#legenda-maior,#legenda').hide();			
	})
	$('#foto-anterior').live('click',function(e){
		e.preventDefault();
		var total_foto = 0;
		$('#fotos-imovel li img').each(function(){
			 $(this).addClass('borda-foto');
			 total_foto++;
		 })
		foto--; 
		total_foto--;
		foto = (foto<0)?total_foto-1:foto;
		$("img","#fotos-imovel li a[rel='"+foto+"']").removeClass('borda-foto');
		$("img","#fotos-imovel li a[rel='"+foto+"']").addClass('foto-selecionada');
		var caminho_foto = $("#fotos-imovel li a[rel='"+foto+"']").attr('href');
		$('#foto-ampliada').attr('src',caminho_foto);
		caminho_foto = caminho_foto+'&LIMITE=640';
		$('#foto-lightbox').attr('src',caminho_foto);
		 if($.trim($("#fotos-imovel li a[rel='"+foto+"']").attr('title'))!='')
		 {	 
			 $('#legenda-maior,#legenda').html($("#fotos-imovel li a[rel='"+foto+"']").attr('title'));
		 	 $('#legenda-maior,#legenda').show();
		 }
		 else
			 $('#legenda-maior,#legenda').hide();			
	})
	
	/************* FALE COM O CORRETOR *******/
	$('#fale-corretor').live('click',function(e){
		fn_carrega_tela('/form_corretor.php',e,$(this))
	})
	/************* ENVIA POR EMAIL *******/
	$('#enviar-email').live('click',function(e){
		fn_carrega_tela('/form_email.php',e,$(this))
	})
	/************* ADICIONAR AOS FAVORITOS *******/
	$('#adicionar-favoritos').live('click',function(e){
		e.preventDefault();
		var valores = fn_pega_cookie('IMOVEIS_ANTARTICO');
		//var complemento = $(this).attr('href');
		//complemento = (complemento!='/index.php')?'?cd='+complemento:'';			
		if(valores)
			{
				fn_cria_cookie('IMOVEIS_ANTARTICO',valores+','+$(this).attr('rel'),7);
				//window.location='/favoritos.php'+complemento;
				window.location='/favoritos';
			}
		else
			{
				fn_cria_cookie('IMOVEIS_ANTARTICO',$(this).attr('rel'),7);
				//window.location='/favoritos.php'+complemento;
				window.location='/favoritos';
			}
	})
	/************* REMOVER DOS FAVORITOS *******/
	$('#remover-favoritos').live('click',function(e){
		e.preventDefault();
		var valores = fn_pega_cookie('IMOVEIS_ANTARTICO');
		
		if(valores)
			{
				var novos_valores = '';
				ar_imoveis = valores.split(',');
				for(var i=0;i<ar_imoveis.length;i++)
					{
						if(ar_imoveis[i]!=$(this).attr('rel'))
							novos_valores += ar_imoveis[i] + ',' ;
					}				
				if(novos_valores!='')
				{
					novos_valores = novos_valores.substring(0,novos_valores.length-1)
					fn_cria_cookie('IMOVEIS_ANTARTICO',novos_valores,7);
					$(this).html('Adicionar imóvel aos favoritos');
					$(this).attr('id','adicionar-favoritos');
				}
				else
				{
					fn_remove_cookie('IMOVEIS_ANTARTICO');
					$(this).html('Adicionar imóvel aos favoritos');
					$(this).attr('id','adicionar-favoritos');					
				}
			}		
	})	
	$('#remover-imovel').live('click',function(e){
		e.preventDefault();
		var valores = fn_pega_cookie('IMOVEIS_ANTARTICO');
		if(valores)
			{
				var novos_valores = '';
				ar_imoveis = valores.split(',');
				for(var i=0;i<ar_imoveis.length;i++)
					{
						if(ar_imoveis[i]!=$(this).attr('rel'))
							novos_valores += ar_imoveis[i] + ',' ;
					}
				if(novos_valores!='')
				{
					novos_valores = novos_valores.substring(0,novos_valores.length-1)
					fn_cria_cookie('IMOVEIS_ANTARTICO',novos_valores,7);
					window.location='/favoritos';
				}		
				else
				{	
					fn_remove_cookie('IMOVEIS_ANTARTICO');
					window.location='/favoritos';
				}
			}			
	})
	/************* IMPRIMIR OS FAVORITOS *******/
	$('#imprimir-favoritos').live('click',function(e){
		e.preventDefault();
		var posicao = $(this).position();
		$("#aba").prepend("<p id=\"resposta-imprimir-favoritos\">Atenção! Uma nova janela será aberta, portanto verifique o seu bloqueador de pop-up.</p>");
		$("#resposta-imprimir-favoritos").css({'left':posicao.left+'px','top':Number(posicao.top-60)+'px','width':'320px'});
		setTimeout(function(){$("#resposta-imprimir-favoritos").remove(); var janela = window.open('impressao_favoritos.php','impressaoF','top=0,left=0,menubar=1,status=1,scrollbars=1,resizable=1'); janela.focus(); },4000)		
	})	
	
	/************* FORMULARIO VENDA *******/
	$('#envia-venda').bind('click',envia_venda);	
	$("#fCadastro input[id='cancela-venda']").live('click',function(e){
		e.preventDefault();
		$("input[type='text']").val('');
		$("select").val('');
		$("textarea").val('');		
		$("input[type='checkbox']").attr('checked','');
		fn_cancel_upload();
	})		
	$("#uploadify").uploadify({
		'uploader'       : 'scripts/uploadify.swf',
		'script'         : 'add_fotos.php',
		'cancelImg'      : 'images/cancel.png',
		'folder'         : 'venda',
		'queueID'        : 'fileQueue',
                'auto'           : false,
		'multi'          : true,
		'fileExt'   :      '*.jpg;*.gif;*.png',
        'fileDesc'  : '*.jpg;*.gif;*.png',
                'sizeLimit' :     3072000,
                'queueSizeLimit' : 20,
                onError          : function (evt, queueID, fileObj, errorObj)
                {
                    if(errorObj.type ==="File Size")
                    alert('Erro: '+fileObj.name+' '+' - Limite: '+Math.round(3072000/1024)+'KB');
                    else
                    alert('Erro '+errorObj.type+": "+errorObj.text);
                },
                onComplete       : function(evt, queueID, fileObj, response, data)
                {  },
                onAllComplete : function(event, uploadObj)
                {                 	 
                	 $('#venda-dados,#venda-imovel,#venda-localizacao').css({'display':'block'});
                	 $("#resposta").remove();
                	 $('#venda-fotos').css({'padding-top':'5px'});
                	 $(window).scrollTop($('h2.titulo').offset().top); 
                	 $("#fCadastro").prepend("<p id=\"resposta\" class=\"retorno\">Seus dados foram enviados com sucesso.<br />Total de fotos enviadas: "+uploadObj.filesUploaded +" - Total de erros: "+uploadObj.errors +"</p>");
                	 $('#fileQueue').hide();
                	 jQuery('#uploadify').uploadifyClearQueue();
                	 $("input[type='text']").val('');
             		 $("select").val('');
             		 $("textarea").val('');		
             		 $("input[type='checkbox']").attr('checked','');       
             		$('#envia-venda').bind('click',envia_venda);
        			$('#envia-venda').removeAttr('disabled');
                }

	});

    $('#fileQueue').hide();
    
    /******* ONCHANGE FORMULARIO *******/
    $('#NM_CD_ESTADO').change(fn_estado);   
    $('#NM_CD_CIDADE').change(fn_cidade);
    
    /******* CAMPO VALOR FORMULARIO *******/
    $('#NM_VL_IMOVEL,#NM_VL_AREA_UTIL').priceFormat({
 	    prefix: '',
 	    centsSeparator: ',',
 	    thousandsSeparator: '.',
 	    centsLimit: 2
 	});       
    
	/************* FUNCOES *******/
    function envia_venda(e)
    {    	
    		e.preventDefault();
    		$('#envia-venda').unbind('click'); 
    		$('#envia-venda').attr('disabled','disabled');
    		var x = 0;
    		$("#resposta").remove();
    		$('#fCadastro .obrigatorio').each(function(e){
    			   
    			   $(this).parent().removeClass('obrigatorio-selecionado');	
    			   
    			   if($.trim($(':input',this).val())=='')
    				{
    					$(this).parent().addClass('obrigatorio-selecionado');
    					x++;
    				}	   
    		   }) 
    		if(x>0)
    		{
    			$('#envia-venda').bind('click',envia_venda);
    			$('#envia-venda').removeAttr('disabled');
    			$(window).scrollTop($('h2.titulo').offset().top);
    			$("#fCadastro").prepend("<p id=\"resposta\" class=\"retorno\">Preencha o(s) campo(s) em destaque.</p>");
    		}
    		else
    		{	
    			$('#fileQueue').slideDown('slow');
    			var codigo_chave = '';
    		    var campos = $('#fCadastro').serialize();
    		    campos += '&VAR_SUBMIT=OK&';	
    		    $.ajax({
    		       	type: 'post',
    		        data: campos,
    		        url: 'grava.php',
    		        success:
    		            function(retorno)
    		            {
    						eval(retorno); 
    						if(codigo_chave!='')
    							{    								
    								$('#venda-dados,#venda-imovel,#venda-localizacao').css({'display':'none'});								
    								$(window).scrollTop($('h2.titulo').offset().top);	
    								$("#fCadastro").prepend("<p id=\"resposta\" class=\"retorno\">Aguarde enquanto as fotos abaixo são carregadas.</p>");
    								var campos = {'VAR_GRAVA':'FOTOS_VENDA','VAR_SUBMIT':'OK','VAR_CODIGO':codigo_chave};								
    								$('#uploadify').uploadifySettings('scriptData',campos);
    								document.getElementById('fileQueue').scrollTop=0;
    							    $('#uploadify').uploadifyUpload();    							    	
    							    $('#venda-fotos').css({'padding-top':'10px'});
    							    if($.trim($('#fileQueue').html())=='')
    							    {
    							    	 $("#resposta").remove();
    							    	 $('#venda-dados,#venda-imovel,#venda-localizacao').css({'display':'block'});
    							    	 $('#venda-fotos').css({'padding-top':'5px'});
    				                	 $(window).scrollTop($('h2.titulo').offset().top); 
    				                	 $("#fCadastro").prepend("<p id=\"resposta\" class=\"retorno\">Seus dados foram enviados com sucesso.<br />Em breve entraremos em contato!</p>");
    				                	 $('#fileQueue').hide();
    				                	 jQuery('#uploadify').uploadifyClearQueue();
    				                	 $("input[type='text']").val('');
    				             		 $("select").val('');
    				             		 $("textarea").val('');		
    				             		 $("input[type='checkbox']").attr('checked','');       
    				             		$('#envia-venda').bind('click',envia_venda);
    				        			$('#envia-venda').removeAttr('disabled');    				                	 
    							    }
    							}						        							        						
    		            }
    		        });
    		}    	    	
    }
	function fn_carrega_tela(arquivo,e,campo)
	{
		e.preventDefault();
		pleft=($(window).width()-500)/2;
		fn_add_tela(500,500,pleft,30);
		$("#CONTEUDO-JANELA").load(arquivo,{'cd_imovel':campo.attr('rel')});				
		
	}	
	function fn_add_tela(tam,alt,pleft,ptop)
	{
		var altura = $(document).height()+20;
	    //altura = (altura<$(window).height())?$(window).height():altura;
	    $(window).scrollTop(0);
	    $(document.body).append("<div id='DIV_PERM' class='impromptufade' style='height:"+(altura)+"px;opacity:0;'></div>");
	    $(document.body).prepend("<div id='CONTEUDO-JANELA' style='left:"+pleft+"px;top:"+ptop+"px;height:"+alt+"px;width:"+tam+"px'></div>");
	    $("#CONTEUDO-JANELA").hide();
	    $("#DIV_PERM").css({'opacity':0});    
	    $("#DIV_PERM").fadeTo("slow", 0.5, function(){ $("#CONTEUDO-JANELA").slideDown("slow"); }); //$("#CONTEUDO-JANELA").toggle("slow");
	    $("#DIV_PERM,.fechar-janela,#fCadastro input[id='cancela']").live('click',function(){
	            $("#DIV_PERM").remove();
	            $("#CONTEUDO-JANELA").remove();
	   });
	  
	 }	
	function fn_cria_cookie(nome,valor,qtd_dias)
	{
	    expira = "";
	    if (qtd_dias)
	        {
	            d = new Date();
	            d.setTime( d.getTime() + qtd_dias * 24 * 60 * 60 * 1000 );
	            expira = "; expires=" + d.toGMTString();
	        }
	    document.cookie = nome + "=" + valor + expira + "; path=/";
	}
	function fn_remove_cookie(nome)
	{
	    fn_cria_cookie(nome,'null','1');
	}
	function fn_pega_cookie(nome)
	{

	    var re = new RegExp( "(\;|^)[^;]*(" + nome + ")\=([^;]*)(;|$)" );
	    var res = re.exec( document.cookie );
	    if (res != null)
	    	return res[3];
	    else
	    	return false;	    
	}
	function fn_cancel_upload()
	{
	         $('#fileQueue').hide();
	         jQuery('#uploadify').uploadifyClearQueue();
	}
    function fn_estado(){
  	   $.post('seleciona.php',{'NM_CD_ESTADO':$(this).val(),'VAR_SUBMIT_E':'OK'},function(retorno){
  		   $('#NM_CD_CIDADE').html(retorno);
  		   $('#NM_CD_BAIRRO').html('<option value="">Selecione</option>');
  	   })
     }
     function fn_cidade(){
  	   $.post('seleciona.php',{'NM_CD_CIDADE':$(this).val(),'VAR_SUBMIT_C':'OK'},function(retorno){
  		   $('#NM_CD_BAIRRO').html(retorno);
  	   })
     }	

   /*     
    if($('#direita').height()>$('#esquerda').height())
    	$('#esquerda').height($('#direita').height()-20);
   */

});


function addFav(url,title){
    //var url      = "http://www.guiafornecedor.com.br";
    //var title    = "Guia Fornecedor";
    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);}
}
