$(function() {
	not_slide = 0;
	
	// Máscaras
	$(".formatFone").mask("(99) 9999-9999");
	$(".formatCep").mask("99999-999");
	$(".formatCpf").mask("999.999.999-99");
	$(".formatData").mask("99/99/9999");
	$('.numeroFormat').keypress(function(event) {
		var code = event.charCode?event.charCode:event.keyCode;
		if (code && (code < 48 || code > 57)) {
		   event.preventDefault();
		}
	});
	
	$('.letrasFormat').keypress(function(event) {
		var code = event.charCode?event.charCode:event.keyCode;
		if (code && (code < 48 || code > 57)) { }else{
			event.preventDefault();
		}
	});
	
	$('.retiraacentosmaiusculo').keypress(function(event) {
		retirarAcentos($(this));
		$(this).val($(this).val().toUpperCase());
	});
	$('.retiraacentosmaiusculo').live("blur",function() {
		retirarAcentos($(this));
		$(this).val($(this).val().toUpperCase());
	});
	
	// Carrega mapas
	if($(".googleMaps").length){
		$(".googleMaps").each(function(){
			loadGoogleMaps($(this).attr('id'));
		});
	}
	
	// Busca pedido por data
	$('.bt_procurar').live('click',function(){
		if($("#mes_inicio").val()||$("#ano_inicio").val()||$("#mes_fim").val()||$("#ano_fim").val())
			$("#por_mes_ano").attr('checked', 'checked');
	});
	
	// Seleciona estado - carrega cidade
	$("#estado").live('change', function(){ 
		var estado = $(this).val();
		
		$.ajax({
			url: "/cadastro/jsonCidades/estado/"+estado,
			beforeSend: function(){
				topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde, carregando...');
		    },
		    complete: function(){
		    	topBox();
		    },
			success: function(result){
				$("select#cidade").html(result);
			},
			dataType: 'html'
		});
	});
	
	// Ver todos os comentários
	$("#comentario_ver_todos").live('click', function(){
		$(".comentario_ver_todos").slideDown('fast');
		$(this).fadeOut('fast',function(){
			$(this).remove();
		});
	});
	
	// Menu categorias / Sub-categorias
	$("ul.dropdown li").hover(function(){
		$(this).addClass("hover");
		$('ul:first',this).css('visibility', 'visible');
    
    }, function(){
    	$(this).removeClass("hover");
    	$('ul:first',this).css('visibility', 'hidden');		
    });
	
	// Filtro - ordem
	$('.ordem_produtos').change(function(){
		if($(this).val()!='escolha'){
			var url = document.location.href;	
			
			if(url.substr(-1) == '/')
				url = url.substr(0, url.length - 1)
	
			var ordem = url.replace('/ordem/', '').replace('ordem/menor/', '').replace('ordem/maior/', '').replace('maior', '').replace('menor', '').replace('/post/product', '');
			location.href  = ordem + '/ordem/' + $(this).val();
		}else{
			return false;
		}
	});
	
	// Banners
	if($('#banner_g').length){
		$('#banner_g').cycle({
			timeout: 10000,
			fx: 'fade' ,// tipos de efeitos: blindX, blindY, blindZ, cover, curtainX, curtainY, fade, fadeZoom, growX, growY, none, scrollUp, scrollDown, scrollLeft, scrollRight, scrollHorz, scrollVert, shuffle, slideX, slideY,toss,turnUp,turnDown,turnLeft,turnRight,uncover,wipe,zoom
			pager: '#banner_mini'
		});
	}
	
	// Produtos - Pegando produto irmão - COR
	$('.getProdutoCor').live("click",function() {
		var idproduto = $(this).attr('idproduto');
		$(this).html('<img src="/img/loading_bicolor.gif" border="0" style="margin: 5px 0 0 12px"/>');
		$.ajax({
			url: '/produtos/detalhesirmao/idproduto/'+idproduto,
			success: function(result){
				$("#block_produto > div").fadeOut('medium',function(){
					$("#block_produto").html(result?result:'<div class="titulo_interno"><ul id="menu_cat"><li>Erro inesperado</li></ul></div><div class="padding_20 fonte_cinza fonte_normal" align="center">Nenhum registro foi encontrado!</div>');
					if(!result)
						setTimeout('redirect("'+window.location+'")',2000);
					
					$("#block_produto").fadeIn('medium');
				});
				
				return false;
			},
			dataType: 'html'
		});		
		return false;
	});
	
	// Formulário contato
	$("#form_contato").validate({
		rules: {
			nome_contato: "required",
			email_contato: {
				required: true,
				email: true
			},
			assunto_contato: "required",
			mensagem_contato: "required"
		},
		messages: {
			nome_contato: "Campo obrigatório",
			email_contato: "Digite um e-mail válido",
			assunto_contato: "Campo obrigatório",
			mensagem_contato: "Campo obrigatório"
		},
		submitHandler: function(form) {
			ajaxForm(form);
		}
	});
	
	// Add ao carrinho
	$("#formAdicionarProduto").validate({
		rules: {
			
		},
		messages: {
			
		}
	});
	
	// Formulário newsletter
	$("#form_newsletter").validate({
		rules: {
			nome_news: "required",
			email_news: {
				required: true,
				email: true
			}
		},
		messages: {
			nome_news: "Digite seu nome",
			email_news: "Digite um e-mail válido"
		},
		submitHandler: function(form) {
			ajaxForm(form);
		}
	});
	
	// Formulário cadastro
	$("#form_cadastro").validate({
		rules: {
			nome: "required",
			sobrenome: "required",
			email: {
				required: true,
				email: true
			},
			dtnascimento: {
				required: true,
				dateBR: true
			},
			cpfcnpj: {
				required: true,
				cpf: true
			},
			sexo: "required",
			cep: "required",
			tipo_endereco: "required",
			identifique_end: "required",
			nomeendereco: "required",
			sobrenomeendereco: "required",
			endereco_cadastro: "required",
			numero: "required",
			complemento: "required",
			bairro: "required",
			estado: "required",
			cidade: "required",
			telefone1: "required",
			email_entrega: {
				required: true,
				email: true
			}
		},
		messages: {
			nome: "Campo obrigatório",
			sobrenome: "Campo obrigatório",
			email: "Digite um e-mail válido",
			dtnascimento: "Digite um e-mail válido",
			cpfcnpj: "Digite um CPF válido",
			sexo: "Obrigatório",
			cep: "Repete a mesma senha",
			tipo_endereco: "Obrigatório",
			identifique_end: "Campo obrigatório",
			nomeendereco: "Campo obrigatório",
			sobrenomeendereco: "Campo obrigatório",
			endereco_cadastro: "Campo obrigatório",
			numero: "Campo obrigatório",
			complemento: "Campo obrigatório",
			bairro: "Campo obrigatório",
			estado: "Campo obrigatório",
			cidade: "Campo obrigatório",
			telefone1: "Campo obrigatório",
			email_entrega: "Digite um e-mail válido"
		}
	});
	
	// Formulário entrega
	$(".form_entrega").validate({
		rules: {
			cep: "required",
			tipo_endereco: "required",
			identifique_end: "required",
			nomeendereco: "required",
			sobrenomeendereco: "required",
			endereco_cadastro: "required",
			numero: "required",
			complemento: "required",
			bairro: "required",
			estado: "required",
			cidade: "required",
			telefone1: "required",
			email_entrega: {
				required: true,
				email: true
			}
		},
		messages: {
			cep: "Repete a mesma senha",
			tipo_endereco: "Obrigatório",
			identifique_end: "Campo obrigatório",
			nomeendereco: "Campo obrigatório",
			sobrenomeendereco: "Campo obrigatório",
			endereco_cadastro: "Campo obrigatório",
			numero: "Campo obrigatório",
			complemento: "Campo obrigatório",
			bairro: "Campo obrigatório",
			estado: "Campo obrigatório",
			cidade: "Campo obrigatório",
			telefone1: "Campo obrigatório",
			email_entrega: "Digite um e-mail válido"
		}
	});
	
	// Novo
	if($("#form_cadastro.c_novo").length){
		$("#senha").rules("add", {
			 required: true,
			 messages: {
			   required: "Campo obrigatório"
			 }
		});
		$("#repitaSenha").rules("add", {
			 required: true,
			 messages: {
			   required: "Repete a mesma senha"
			 }
		});
		
		return false;
	}
	
	// Formulário Identificação - login
	$(".form_login").validate({
		rules: {
			email: {
				required: true,
				email: true
			},
			senha: "required"
		},
		messages: {
			email: "Digite um e-mail válido",
			senha: "Campo obrigatório"
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				dataType: 'json',
				cache: false,
				beforeSubmit: function(){
					topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde, enviando formulário.');
				},
				success: function(result){
					topBox(1,result.msg);
					setTimeout('topBox()',5000);
					
					if(result.cliente)
						setTimeout('redirect('+result.redirect+')',1000);
			    }
			});
		}
	});
	
	// Formulário Identificação - Cadastrar
	$(".form_ident_cadastrar").validate({
		rules: {
			email_cadastro: {
				required: true,
				email: true
			}
		},
		messages: {
			email_cadastro: "Digite um e-mail válido"
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				dataType: 'json',
				cache: false,
				beforeSubmit: function(){
					topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde, enviando formulário.');
				},
				success: function(result){
					if(result.redirect)
						redirect(result.redirect);
						
					topBox(1,result.msg);
					setTimeout('topBox()',5000);
			    }
			});
		}
	});
	
	// Message box page	
	$(".box_message").fancybox({
		padding					: 5,
		overlayOpacity			: 0.8,
		'transitionIn'			: 'fade',
		'transitionOut'			: 'fade',
		'autoScale'         	: false,
		'autoDimensions'    	: true,
		centerOnScroll          : true,
		hideOnContentClick		: false,
		enableEscapeButton		: true,
		titleShow				: false,
		overlayShow				: true,
		scrolling				: false,
		onComplete				: function(){
			$.fancybox.resize();
		}
	});
	
	// Message box page	
	$(".box_clipping").fancybox({
		padding					: 5,
		overlayOpacity			: 0.8,
		'transitionIn'			: 'fade',
		'transitionOut'			: 'fade',
		'hideOnContentClick'	: true,
		'autoScale'         	: true,
		'autoDimensions'    	: true,
		centerOnScroll          : false,
		enableEscapeButton		: true,
		titleShow				: true,
		titlePosition			: 'inside',
		overlayShow				: true,
		onComplete				: function(){
			$.fancybox.resize();
		}
	});
	
	// Submit form busca
	$(".search_mini_form").submit(function() {
		var q = $('#q', this);
		var cat = $(this).children('ul').children('li').next('li').children('select');
		if(!q.val()&&!cat.val()){
			q.focus();
			return false;
		}
	});
	
	// Pedido - Quantidade
	$('.campo_quantidade, .campo_carrinho').live("blur",function() {
		if(isNaN($(this).val())||!$(this).val().length)
			$(this).val($(this).attr('value_old')?$(this).attr('value_old'):'1');
		else
			$(this).attr('value_old', $(this).val());
	});	
	$('.campo_quantidade, .campo_carrinho').live("focus",function() {
		if($(this).val()==1)
			$(this).val('');
	});
	
	// Pedido - Embalagem de presente
	$('.setEmbalagemPresente').live("click",function() {
		if($(this).is(':checked')){
			$(this).next('input').fadeIn('fast');
			$(this).next('input').focus();
		}else{
			$(this).next('input').fadeOut('fast');
		}
	});
	
	$('.info_pedido .excluir').live("click",function() {
		if(confirm('Deseja mesmo excluir este item?'))
			return true;
		
		return false;
	});
	
	// Cupom de desconto
	$('#btn_usar_cupom').live("click",function() {
		var codigocupomdesconto = $("#codigocupomdesconto").val();
		
		if(codigocupomdesconto==''){
			$("#codigocupomdesconto").focus();
		}else{
			$.ajax({
				url: '/cupomdesconto/usarcupom/ajax/1/codigo/'+codigocupomdesconto,
				beforeSend: function(){
					topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde, verificando cupom de desconto!');
			    },
				success: function(result){
			    	// Valor do desconto
			    	$("#valor_cupomdesconto").html(result.desconto);
			    	
			    	// Total
			    	if(result.total)
			    		$(".totalpedido").html(result.total);
			    	
			    	// Msg de retorno
			    	topBox(1,result.msg);
			    	
			    	// Dados total
		    		$("#valor_frete").html(result.valor_frete);
					$(".totalpedido").html(result.total);
					
					// Dadas parcelamento - boleto
					if(result.totalboleto){
						$("#totalpedido_boleto").parent('tr').fadeIn('fast');
						$("#totalpedido_boleto").html(result.totalboleto);
						$("#desc_boleto_vista").html(result.desc_boleto_vista);
					}else{
						$("#totalpedido_boleto").parent('tr').fadeOut('fast');
					}
					if(result.totalcartao){
						$("#totalpedido_cartao").parent('tr').fadeIn('fast');
						$("#totalpedido_cartao").html(result.totalcartao);
						$("#desc_cartao_vista").html(result.desc_cartao_vista);
					}else{
						$("#totalpedido_cartao").parent('tr').fadeOut('fast');
					}
					if(result.valor_parcela_cc){
						$("#valor_parcela_cc").parent('tr').fadeIn('fast');
						$("#valor_parcela_cc").html(result.valor_parcela_cc);
						$("#n_parcelas_cc").html(result.n_parcelas_cc);
					}else{
						$("#valor_parcela_cc").parent('tr').fadeOut('fast');
					}
					
			    	if(result.ok){
			    		$("#remover_cupomdesconto").fadeIn('fast');
			    		$("#codigocupomdesconto").attr('val_old', codigocupomdesconto);
			    	}else{
			    		$("#valor_cupomdesconto").html('--');
						$("#codigocupomdesconto").attr('val_old', '--');
						$("#remover_cupomdesconto").fadeOut('fast');
						$("#codigocupomdesconto").focus();
			    	}
			    	
			    	setTimeout('topBox()',5000);
				},
				dataType: 'json'
			});
		}		
		return false;
	});
	
	// Cupom de desconto 
	$('#codigocupomdesconto').live("blur",function() {
		if($(this).attr('val_old')!='--'&&$(this).attr('val_old')=='')
			$(this).val($(this).attr('val_old'));
		
		return false;
	});
	
	// Remover cupom de desconto
	$('#remover_cupomdesconto').live("click",function() {
		if(confirm('Deseja realmente remover o cupom de desconto?')){
			$.ajax({
				url: '/cupomdesconto/remover/ajax/1/',
				beforeSend: function(){
					topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde...');
			    },
				success: function(result){
		    		// Total
			    	if(result.total)
			    		$(".totalpedido").html(result.total);
			    	
		    		$("#valor_cupomdesconto").html('--');
					$("#codigocupomdesconto").val('');
					$("#codigocupomdesconto").attr('val_old', '--');
					$("#remover_cupomdesconto").fadeOut('fast');
					
					// Dadas parcelamento - boleto
					if(result.totalboleto){
						$("#totalpedido_boleto").parent('tr').fadeIn('fast');
						$("#totalpedido_boleto").html(result.totalboleto);
						$("#desc_boleto_vista").html(result.desc_boleto_vista);
					}else{
						$("#totalpedido_boleto").parent('tr').fadeOut('fast');
					}
					if(result.totalcartao){
						$("#totalpedido_cartao").parent('tr').fadeIn('fast');
						$("#totalpedido_cartao").html(result.totalcartao);
						$("#desc_cartao_vista").html(result.desc_cartao_vista);
					}else{
						$("#totalpedido_cartao").parent('tr').fadeOut('fast');
					}
					if(result.valor_parcela_cc){
						$("#valor_parcela_cc").parent('tr').fadeIn('fast');
						$("#valor_parcela_cc").html(result.valor_parcela_cc);
						$("#n_parcelas_cc").html(result.n_parcelas_cc);
					}else{
						$("#valor_parcela_cc").parent('tr').fadeOut('fast');
					}
			    	
			    	// Msg de retorno
			    	topBox(1,result.msg);
					setTimeout('topBox()',5000);
				},
				dataType: 'json'
			});
		}else{
			
		}
		return false;
	});
	
	// Cep - Calcular frete
	$('#btn_calcular_frete').live("click",function() {
		var cep = $("#cepdest").val();
		var btn_f = $(this);
		
		if(cep==''||cep=='00000-000'){
			$("#cepdest").focus();
		}else{
			$.ajax({
				url: '/frete/consultarfrete/ajax/1/cepdest/'+cep,
				beforeSend: function(){
					btn_f.before('<img style="margin: 9px 49px 0 40px;" src="/img/loading_bicolor.gif" border="0" />');
					btn_f.hide();
			    },
			    complete: function(){
			    	btn_f.prev('img').remove();
			    	btn_f.show();
			    },
				success: function(result){
			    	if($("#block_notvisible_fretes").length)
			    		$("#block_notvisible_fretes").html('<div id="block_fretes">'+result.html+'</div><a href="#block_fretes" id="show_frete"></a>');
			    	else
			    		btn_f.after('<div style="display: none;" id="block_notvisible_fretes"><div id="block_fretes">'+result.html+'</div><a href="#block_fretes" id="show_frete"></a></div>');
			    	
			    	$("#show_frete").fancybox({
			    		padding					: 5,
			    		overlayOpacity			: 0.8,
			    		'transitionIn'			: 'fade',
			    		'transitionOut'			: 'fade',
			    		'autoScale'         	: false,
			    		'autoDimensions'    	: true,
			    		centerOnScroll          : true,
			    		hideOnContentClick		: false,
			    		enableEscapeButton		: true,
			    		titleShow				: false,
			    		overlayShow				: true,
			    		scrolling				: false
			    	});
			    	
			    	$("#show_frete").trigger('click');
				},
				dataType: 'json'
			});
		}
		return false;
	});	
	
	// Message box page
	$(".message_box_page").fancybox({
		padding					: 5,
		overlayOpacity			: 0.8,
		'transitionIn'			: 'fade',
		'transitionOut'			: 'fade',
		'autoScale'         	: false,
		'autoDimensions'    	: true,
		centerOnScroll          : true,
		hideOnContentClick		: false,
		enableEscapeButton		: true,
		titleShow				: false,
		overlayShow				: true,
		scrolling				: false
	});
});

function loadingSetFrete(){
	$('.setFrete').live("change",function() {
		var cep = $("#cepdest").val();
		var cod = $(this).val();
		
		$.ajax({
			url: '/frete/setfrete/ajax/1/cepdest/'+cep+'/opc_frete/'+cod,
			beforeSend: function(){
				topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde, enviando formulário.');
		    },
			success: function(result){
				if(result.error){
					$("#valor_frete").html('--');
					if($("#block_error").length)
						$("#block_error").html(result.html);
					else
						$("#block_fretes .caixa_box .cb_tit").after('<div id="block_error">'+result.html+'</div>');
					
					setTimeout('topBox()',0);
					
					$.fancybox.resize();
				}else{
					$("#calcule_frete").remove();
					$.fancybox.close();
					
					$("#valor_frete").html(result.valor_frete);
					$(".totalpedido").html(result.total);
					
					// Dadas parcelamento - boleto
					if(result.totalboleto){
						$("#totalpedido_boleto").parent('tr').fadeIn('fast');
						$("#totalpedido_boleto").html(result.totalboleto);
						$("#desc_boleto_vista").html(result.desc_boleto_vista);
					}else{
						$("#totalpedido_boleto").parent('tr').fadeOut('fast');
					}
					if(result.totalcartao){
						$("#totalpedido_cartao").parent('tr').fadeIn('fast');
						$("#totalpedido_cartao").html(result.totalcartao);
						$("#desc_cartao_vista").html(result.desc_cartao_vista);
					}else{
						$("#totalpedido_cartao").parent('tr').fadeOut('fast');
					}
					if(result.valor_parcela_cc){
						$("#valor_parcela_cc").parent('tr').fadeIn('fast');
						$("#valor_parcela_cc").html(result.valor_parcela_cc);
						$("#n_parcelas_cc").html(result.n_parcelas_cc);
					}else{
						$("#valor_parcela_cc").parent('tr').fadeOut('fast');
					}
						
			    	topBox(1,result.msg);
					setTimeout('topBox()',5000);
				}
			},
			dataType: 'json'
		});
	});
}

function redirect(url){
	location.href = url;
}

function ajaxForm(form){
	$(form).ajaxSubmit({
		dataType: 'json',
		cache: false,
		beforeSubmit: function(){
			topBox(1,'<img src="/img/loading_bicolor.gif" alt="">&nbsp;&nbsp;Aguarde, enviando formulário.');
		},
		success: function(result){
			if(result.enviado)
				$(form).resetForm();
			
			topBox(1,result.msg);
			setTimeout('topBox()',5000);
	    }
	});
}

function avaliacao(){
	$("#produto_avaliacao > img").css('cursor', 'pointer');
	$("#produto_avaliacao > img").hover(function(){
		$("#produto_avaliacao > img").attr('src', $("#produto_avaliacao img").attr('src').replace('on', 'off'));
		var i = $(this).attr('i');
		for(x=0;x<=i;x++){
			$("#produto_avaliacao > img[i="+x+"]").attr('src', $("#produto_avaliacao > img[i="+x+"]").attr('src').replace('off', 'on'));
		}
    }, function(){
    	$("#produto_avaliacao > img").attr('src', $("#produto_avaliacao img").attr('src').replace('on', 'off'));
    	$("#produto_avaliacao > img").each(function(){
    		$(this).attr('src', $(this).attr('src').replace('off', $(this).attr('on')==1?'on':'off'));
    	});
    });
}

function loadingProduto(){	
	// Message box page
	$(".message_box_page").fancybox({
		padding					: 5,
		overlayOpacity			: 0.8,
		'transitionIn'			: 'fade',
		'transitionOut'			: 'fade',
		'autoScale'         	: false,
		'autoDimensions'    	: true,
		centerOnScroll          : true,
		hideOnContentClick		: false,
		enableEscapeButton		: true,
		titleShow				: false,
		overlayShow				: true,
		scrolling				: false
	});
	
	$('.img_zoom').jqzoom({
		zoomWidth: 440,
	    zoomHeight: 440,
	    xOffset: 0,
        title: false,
        showEffect: 'show',
        hideEffect: 'fadeout',
        fadeoutSpeed: 'slow',
        preloadImages :false,
        lens:false
	});
	
	$('.mini-img').live("click", function() {
		$('.img_zoom').replaceWith('<a class="img_zoom" href="'+$(this).attr('rel')+'"><img class="produto_g" src="'+$(this).attr('rel_normal')+'" border="0" /></a>');
		$('.img_zoom').jqzoom({
		    zoomWidth: 440,
		    zoomHeight: 440,
		    xOffset: 0,
	        title: false,
	        showEffect: 'show',
	        hideEffect: 'fadeout',
	        fadeoutSpeed: 'slow',
	        preloadImages :false,
	        lens:false
		});
		
		return false;
	});
	
	// Carrosel album
	$('#carrosel_thumb_produto').mousewheel(function(objEvent, intDelta){
		if(!not_slide){
			intDelta>0?$('#set_album_esquerda').trigger('click'):$('#set_album_direita').trigger('click');
		}
			
		objEvent.preventDefault();
	});
	
	$('#carrosel_thumb_produto').cycle({
		fx: 'fade',
		timeout: 0,
		next: '#set_album_esquerda',
	    prev: '#set_album_direita',
		before: before_slide_album,
	    after: after_slide_album
	});
}

function before_slide_album(){
	not_slide = 1;	
}

function after_slide_album(){
	not_slide = 0;
}

function topBox(n,m){
	if(!$("#top_box_inside").length)
		$("body").append('<div align="center" id="top_box"><div id="top_box_inside"></strong></div></div>');
	
	if(n){
		if(m)
			$("#top_box_inside").html(m);
			
		if($("#top_box").is(":hidden")){
			$("#top_box").fadeIn('medium');
		}
	}else{
		$("#top_box").fadeOut('medium',function(){$("#top_box_inside").html('');});
	}
}

function pagarPedido(URL) {
	var width = 980;
	var height = 550;

	var left = 99;
	var top = 99;
	  
	window.open(URL,'janela', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
}

function loadGoogleMaps(identificador) {
    var endereco = $('#' + identificador + '_endereco').val();
	var utilizar = parseInt($('#' + identificador + '_utilizar_lat_lng').val());
	
	var myOptions = {
			  zoom: 16,
			  scrollwheel: false,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	map = new google.maps.Map(document.getElementById(identificador), myOptions);
    
	/*var icone = new google.maps.MarkerImage('/img/map_logo.gif',
						  // This marker is 20 pixels wide by 32 pixels tall.
						  new google.maps.Size(35, 41),
						  // The origin for this image is 0,0.
						  new google.maps.Point(0,0),
						  // The anchor for this image is the base of the flagpole at 0,32.
						  new google.maps.Point(4, 39));
	*/ 
	if(utilizar){
		var latlng = new google.maps.LatLng($('#' + identificador + '_latitude').val(), $('#' + identificador + '_longitude').val());

		map.setCenter(latlng);
		  
		var marker = new google.maps.Marker({
			position: latlng,
			map: map/*,
			icon: icone*/
		});
		  
		google.maps.event.addListener(marker, 'click', function() {
			map.setZoom(16);
			map.setCenter(latlng);
		});
	}else{	
		geocoder = new google.maps.Geocoder();
   
		if(geocoder){
			geocoder.geocode( { 'address': endereco}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					  latlng = results[0].geometry.location;
					  
					  map.setCenter(latlng);
					  
					  var marker = new google.maps.Marker({
						position: latlng,
						map: map/*,
						icon: icone*/
					  });
					  
					  google.maps.event.addListener(marker, 'click', function() {
						  map.setZoom(16);
						  map.setCenter(latlng);
					  });
				}
			});
		}
	}
}

function retirarAcentos(objResp) {  
	var varString = new String($(objResp).val());  
	
	var stringAcentos = new String('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ´`^¨~;._-[]}{º°?/*%!$#@()+§=ª,');  
	var stringSemAcento = new String('aaeouaoaeioucuAAEOUAOAEIOUCU');  
	  
	var i = new Number();  
	var j = new Number();  
	var cString = new String();  
	var varRes = '';  
	  
	for (i = 0; i < varString.length; i++) {  
		cString = varString.substring(i, i + 1);  
		for (j = 0; j < stringAcentos.length; j++) {  
			if (stringAcentos.substring(j, j + 1) == cString){  
				cString = stringSemAcento.substring(j, j + 1);  
			}  
		}  
		varRes += cString;  
	}  
	$(objResp).val(varRes);  
} 
