
$(document).ready(function() {
	
	
	
	//$('#filtros').stickyfloat({duration: 400, offsetY: 180});


/*------------------------------------
	FANCYBOX
------------------------------------*/
	$(".wallpaper-size a").fancybox({
		overlayColor: '#000',
		overlayOpacity: 0.5,
		speedIn: 500,
		width: 760,
		height: 516,
		titleShow: false,
		autoScale: false,
		type: 'iframe',
		padding: 0
	});
	
	$("a[rel=fancybox]").fancybox({
		overlayColor: '#000',
		overlayOpacity: 0.5,
		speedIn: 500,
		titleShow: false
	});
	
	
						   
/*------------------------------------
	HOVER DOS BOTÕES
------------------------------------*/
	$(".bt-modelos, #bt-buscar, .bt-onde-comprar, .bt-compartilhe, #paginacao a, #compartilhe_submit, #searchsubmit, #submit, #contato_submit, .btn-concorrer-vaga, #voltar").hover(
		function() {
			//$(this).stop(true,true).animate({ 'background-color': '#06499c' });
			$(this).addClass("hover");
		},
		function() {
			//$(this).stop(true,true).animate({ 'background-color': '#f9df00' });
			$(this).removeClass("hover");
		}
	);
		
		
/* ANIMAÇÃO DOS DESTAQUES PRINCIPAIS - HOME
------------------------------------------------------------------*/

function anima_entrada(modelo) {

	var veja_mais = $("#destaque-"+modelo+" .bt-veja-mais-destaque").width();

	if(modelo != 'gold' || modelo != 'chronos') {
		
	var title = $("#destaque-"+modelo+" .titulo-destaque").width();
	var desc = $("#destaque-"+modelo+" .descricao-destaque .texto").width();
	
	
	
	$(".titulo-destaque, .descricao-destaque .texto, .bt-veja-mais-destaque").css("width", "0");
	$(".bt-veja-mais-destaque img").hide();
	
	$(".titulo-destaque").stop(true, true).animate({ 'width': title }, 500);
	$(".descricao-destaque .texto").stop(true, true).animate({ 'width': desc }, 500);
	$(".bt-veja-mais-destaque").stop(true, true).animate({ 'width': veja_mais }, 500, function() {  });
	$(".bt-veja-mais-destaque img").fadeIn("slow");
	
	}
	
	

}

/*------------------------------------
	BGS RANDOMICOS
------------------------------------*/

var bgs = new Array(3);
bgs[0] = 'chronos';
bgs[1] = 'cardiac';
bgs[2] = 'gold';

function randomizaBG()
{
	var ranNum= Math.floor(Math.random()*3);
	$('body').addClass(bgs[ranNum]);
	anima_entrada(bgs[ranNum]);
}



randomizaBG();



/*------------------------------------
	Comentários
------------------------------------*/
	$(".comment-form-author input, .comment-form-email input, .comment-form-comment textarea").each(
		function() {
			var text = $(this).parent().find("label").text();
			var val = $(this).val();
			
			if( val == "" ) {
				$(this).val(text);
			}
		}
	);



/* LIMPA OS CAMPOS DE FORMULÁRIOS (NEWS)
------------------------------------------------------------------*/
	swapValue = [];
	$(".text, textarea, #s").each(function(i){
		swapValue[i] = $(this).val();
		$(this).focus(function(){
			if ($(this).val() == swapValue[i]) {
				$(this).val("");
			}
			$(this).addClass("focus");
		}).blur(function(){
			if ($.trim($(this).val()) == "") {
				$(this).val(swapValue[i]);
			}
			$(this).removeClass("focus");
		});
	});



/* LÊ XML E POPULA DROPDOWN - ASSISTENCIA
------------------------------------------------------------------*/

var url_xml_assistencia = $("#logo a").attr("href") + "admin/wp-content/themes/puma-time/lib/xml/FILIAIS.xml";

$.fn.populaDropdownAssistencia = function() {
	var o = $(this[0]); // It's your element
	var args = arguments[0] || {}; // It's your object of arguments
	var estado = args.estado;
	var dropdown_name = args.dropdown_name;
	
	$.ajax({
		type: "GET",
		url: url_xml_assistencia,
		dataType: "xml",
		success: function(xml) {
			var selectbox = $("#"+dropdown_name);
			var optionsHtml = new Array();
			var liHtml = new Array();
			
			if( dropdown_name == "cidade_fi" ) {
				optionsHtml.push("<option selected='selected'>Selecione uma cidade</option>");
			} else {
				optionsHtml.push("<option selected='selected'>Selecione um estado</option>");
			}
			
			$(xml).find('tt-clientes-aux').each(function(){
				if( dropdown_name == "cidade_fi" ) {
					if( $(this).find('estado').text() == estado ) {
						var value = $(this).find('cidade').text();
					}
				} else {
					var value = $(this).find('estado').text();
				}
				
				if( value ) {
					optionsHtml.push("<option value='" + value + "'>" + value + "</option>");
				}
			});
			
			optionsHtml = optionsHtml.sort();
			optionsHtml = optionsHtml.join('');
			$(selectbox).empty().append(optionsHtml);
			
			$("#"+dropdown_name+" option").each(
				function() {
					var estado = $(this);
					var prev_estado = $(this).prev();
					var estados = $(this).length;
					
					if( prev_estado.attr("value") == estado.attr("value") ) {
						$(estado).remove();
					}
				}
			);
			//$("#"+dropdown_name).parent().jqTransform();
			//$("#"+dropdown_name).select_skin();
		}
	});
};

//$(".drop-cidade").hide();
$("#estado_fi").populaDropdownAssistencia({ dropdown_name: 'estado_fi' });
$("#estado_fi").addClass('novo_filtro_cxa'); // Caixa alta



$("#estado_fi").change(function(){
	// Corrige bug do IE	
});

$("#estado_fi").live(
	'change',
	function() {
		
		//var estado = $(this).text();
		var estado = $(this).find("option:selected").attr("value");
		$("#drop-estado").text(estado);
		$("#drop-cidade").removeClass('desativado');
		$("#cidade_fi").removeAttr("disabled").populaDropdownAssistencia({ dropdown_name: 'cidade_fi', estado: estado });
		//$("#cidade_fi").addClass('novo_filtro_cxa'); // Caixa alta
	}
);


$("#cidade_fi").change(function(){
	// Corrige bug do IE	
});
$("#cidade_fi").live(
	'change',

	function(event) {
		event.preventDefault();
		
		var cidade = $("#cidade_fi option:selected").attr("value");
		$("#lista-lojas").empty();
		$('<h2 id="tit-arquivos-mes">'+cidade+'</h2>').appendTo("#lista-lojas");
		
		$.ajax({
			type: "GET",
			url: url_xml_assistencia,
			dataType: "xml",
			success: function(xml) {
				
				$(xml).find('tt-clientes-aux').each(function(){
					if( $(this).find('cidade').text() == cidade ) {
						var cod_emit = $(this).find('cod-emitente').text();
						var nome_emit = $(this).find('nome-emit').text();
						var endereco = $(this).find('endereco').text();
						var bairro = $(this).find('bairro').text();
						var estado = $(this).find('estado').text();
						var cep = $(this).find('cep').text();
						var telefone1 = $(this).find('telefone1').text();
						var telefone2 = $(this).find('telefone2').text();
						var telefax1 = $(this).find('telefax1').text();
						var telefax2 = $(this).find('telefax2').text();
						
						var output = [];
						
						function mascara( texto, tipo ) {
							var valor = null;
							texto = texto.split(' ').join('');
							
							switch( tipo ) {
								case "telefone":
									valor = "(" + texto.substring(0,2) + ") " + texto.substr(2,4) + "-" + texto.substr(6,20);
									break;
								case "cep": 
									valor = texto.substring(0,2) + "." + texto.substring(2,5) + "-" + texto.substr(5,20);
									break;
								default: 
									valor = texto; 
									break;
							}
							return valor;
						}
						

						output += '<div id="loja-' + cod_emit + '" class="onde-comprar type-onde-comprar status-publish hentry">';
							output += '<h3 class="titulo-loja">' + nome_emit + '</h3>';
							output += '<p><div>';
							output += endereco + ', ' + bairro + ' - ' + cidade + '/' + estado + ' - CEP: '+ mascara( cep, "cep" ) +'</div>';
								if( telefone1 != null ) { output += "<div>Telefone(s): " + mascara( telefone1, "telefone" ); }
								if( telefone2 != '' ) { output += " / " + mascara( telefone2, "telefone" )+ "</div>"; }
								if( telefax1 != '' ) { output += "<div> Telefax: " + mascara( telefax1, "telefone" ); }
								if( telefax2 != '' ) { output += " / " + mascara( telefax2, "telefone" )+"</div>"; }
							output += '</p>';
						output += '</div>';
						
						$(output).appendTo("#lista-lojas");
					}
				});
			}
		});
		
	}
);



/* LÊ XML E POPULA DROPDOWN - ONDE COMPRAR
------------------------------------------------------------------*/
	var url_xml = $("#logo a").attr("href") + "admin/wp-content/themes/puma-time/lib/xml/PU.xml";
	
	$.fn.populaDropdown = function() {
		var o = $(this[0]); // It's your element
		var args = arguments[0] || {}; // It's your object of arguments
		var estado = args.estado;
		var dropdown_name = args.dropdown_name;
		
		$.ajax({
			type: "GET",
			url: url_xml,
			dataType: "xml",
			success: function(xml) {
				var selectbox = $("#"+dropdown_name);
				var optionsHtml = new Array();
				var liHtml = new Array();
				
				if( dropdown_name == "cidade" ) {
					optionsHtml.push("<option selected='selected'>Selecione uma cidade</option>");
				} else {
					optionsHtml.push("<option selected='selected'>Selecione um estado</option>");
				}
				
				$(xml).find('tt-clientes-aux').each(function(){
					if( dropdown_name == "cidade" ) {
						if( $(this).find('estado').text() == estado ) {
							var value = $(this).find('cidade').text();
						}
					} else {
						var value = $(this).find('estado').text();
					}
					
					if( value ) {
						optionsHtml.push("<option value='" + value + "'>" + value + "</option>");
					}
				});
				
				optionsHtml = optionsHtml.sort();
				optionsHtml = optionsHtml.join('');
				$(selectbox).empty().append(optionsHtml);
				
				$("#"+dropdown_name+" option").each(
					function() {
						var estado = $(this);
						var prev_estado = $(this).prev();
						var estados = $(this).length;
						
						if( prev_estado.attr("value") == estado.attr("value") ) {
							$(estado).remove();
						}
					}
				);
				//$("#"+dropdown_name).parent().jqTransform();
				//$("#"+dropdown_name).select_skin();
			}
		});
	};
	
	//$(".drop-cidade").hide();
	$("#estado").populaDropdown({ dropdown_name: 'estado' });
	$(".jqtransform").not(".lista-localidades, .lista-assistencias").jqTransform();
	
	$("#estado").change(function(){
		// Corrigir bug IE	
	});

	
	$("#estado").live(
		'change',
	/*$(".drop-estados .jqTransformSelectWrapper ul li a").live(
		'click',*/
		function() {
			
			//var estado = $(this).text();
			var estado = $(this).find("option:selected").attr("value");
			$("#drop-estado").text(estado);
			$("#drop-cidade").removeClass('desativado');
			$("#cidade").removeAttr("disabled").populaDropdown({ dropdown_name: 'cidade', estado: estado });
		}
	);
	
	
	$("#cidade").change(function(){
		// Corrigir bug IE	
	});

	
	$("#cidade").live(
		'change',
		function(event) {
			event.preventDefault();
			
			var cidade = $("#cidade option:selected").attr("value");
			$("#lista-lojas").empty();
			$('<h2 id="tit-arquivos-mes">'+cidade+'</h2>').appendTo("#lista-lojas");
			
			$.ajax({
				type: "GET",
				url: url_xml,
				dataType: "xml",
				success: function(xml) {
					
					$(xml).find('tt-clientes-aux').each(function(){
						if( $(this).find('cidade').text() == cidade ) {
							var cod_emit = $(this).find('cod-emitente').text();
							var nome_emit = $(this).find('nome-emit').text();
							var endereco = $(this).find('endereco').text();
							var bairro = $(this).find('bairro').text();
							var estado = $(this).find('estado').text();
							var cep = $(this).find('cep').text();
							var telefone1 = $(this).find('telefone1').text();
							var telefone2 = $(this).find('telefone2').text();
							var output = [];
							
							function mascara( texto, tipo ) {
								var valor = null;
								texto = texto.split(' ').join('');
								
								switch( tipo ) {
									case "telefone":
										valor = "(" + texto.substring(0,2) + ") " + texto.substr(2,4) + "-" + texto.substr(6,20);
										break;
									case "cep": 
										valor = texto.substring(0,2) + "." + texto.substring(2,5) + "-" + texto.substr(5,20);
										break;
									default: 
										valor = texto; 
										break;
								}
								return valor;
							}
							
							output += '<div id="loja-' + cod_emit + '" class="onde-comprar type-onde-comprar status-publish hentry">';
								output += '<h3 class="titulo-loja">' + nome_emit + '</h3>';
								output += '<p>';
								output += endereco + ', ' + bairro + ' - ' + cidade + '/' + estado + ' - CEP: '+ mascara( cep, "cep" ) +'</br>';
									if( telefone1 != null ) { output += "Telefone(s): " + mascara( telefone1, "telefone" ); }
									if( telefone2 != '' ) { output += " / " + mascara( telefone2, "telefone" ); }
								output += '</p>';
								output += '<a href="#" alt="mapa-' + cod_emit + '" title="'+ bairro + ' - ' + cidade + '/' + estado + ' - CEP: '+ mascara( cep, "cep" )+' - Brasil" rel="'+endereco + ', ' + bairro + ' - ' + cidade + '/' + estado + ' - CEP: '+ mascara( cep, "cep" )+'" class="bt-ver-mapa">Ver mapa</a>';
								output += '<div id="mapa-' + cod_emit + '" class="mapa hidden"></div>';
							output += '</div>';
							
							$(output).appendTo("#lista-lojas");
						}
					});
				}
			});
			
		}
	);



/* EXIBE MAPA - ONDE COMPRAR
------------------------------------------------------------------*/
	$(".mapa").hide();
	
	$(".bt-ver-mapa").live(
		'click',
		function(event) {
			event.preventDefault();
			
			var address = $(this).attr('rel');
			var address2 = $(this).attr('title');
			var mapa_gmaps = document.getElementById($(this).attr('alt'));
			var mapa = $(this).next(".mapa"); 
			
			
			var geocoder = new GClientGeocoder();
			var map;
			var directionsPanel;
			var directions;
			
			geocoder.getLatLng(
			address,
			function(point) {
				  if (!point) {
						var geocoder = new GClientGeocoder();
						var map;
						var directionsPanel;
						var directions;
						
						geocoder.getLatLng(
						address2,
						function(point) {
							if(!point)
							{
								alert('Impossivel localizar a loja');	
							}
							else
							{
								///*********** GOOGLE MAPS API V.2 *****************///					 
					 
								map = new GMap2(mapa_gmaps, { size: new GSize(745,197) });					
								map.addControl(new GLargeMapControl());					
								map.setCenter(point, 16);	
								
								var tinyIcon = new GIcon();
								tinyIcon.image = "http://pumateste.seculus.com.br/admin/wp-content/themes/puma-time/img/logo-maps.png";
								tinyIcon.iconSize = new GSize(26, 26);
								tinyIcon.iconAnchor = new GPoint(6, 20);
								tinyIcon.infoWindowAnchor = new GPoint(10, 1);
								markerOptions = {icon:tinyIcon};
								var marker = new GMarker(point, markerOptions);									
								map.addOverlay(marker);
								
								///*********** GOOGLE MAPS API V.2 *****************///	
								
							}
							
						});
					
				  } else {
					  					
					///*********** GOOGLE MAPS API V.2 *****************///					 
					 
					map = new GMap2(mapa_gmaps, { size: new GSize(745,197) });					
					map.addControl(new GLargeMapControl());					
					map.setCenter(point, 16);	
					
					var tinyIcon = new GIcon();
					tinyIcon.image = "http://pumateste.seculus.com.br/admin/wp-content/themes/puma-time/img/logo-maps.png";
					tinyIcon.iconSize = new GSize(26, 26);
					tinyIcon.iconAnchor = new GPoint(6, 20);
					tinyIcon.infoWindowAnchor = new GPoint(10, 1);
					markerOptions = {icon:tinyIcon};
					var marker = new GMarker(point, markerOptions);									
					map.addOverlay(marker);
					
					///*********** GOOGLE MAPS API V.2 *****************///	
						
				  }
				}
			);
			
			
			if( $(mapa).is(":visible") ) {				
				/* Libera memoria */
				GUnload();					
				
				$(mapa).slideUp("normal");
				$(this).removeClass("visivel");
				$(this).text("Ver mapa");					
						
			} else {
				$(mapa).slideDown("normal");
				$(this).addClass("visivel");
				$(this).text("Fechar mapa");
			}
			
			
			
			
					
			
		}
	);



/* MÁSCARA NOS CAMPOS DE FORMULÁRIO
------------------------------------------------------------------*/
	$(function(){
		$(".text").setMask();
	});



/* COMPARTILHE
------------------------------------------------------------------*/
	//$("#compartilhe-por-email").hide();
	
	
	
	$("#sm-email a").click(
		function() {
			var form = $(this).attr("href");
			
			if( $(form).is(":visible") ) {
				$(form).slideUp("fast");
			} else {
				$(form).slideDown("fast");				
			}
			
			return false;
		}
	);
	
	//****************** Implementação para ocultar o box de compartilhe ********************//
	
	$("ul#acoes").next().hide();
	$("#bt-compartilhe").css("background","none");
	
	//****************** Implementação para ocultar o box de compartilhe ********************//

	
	
	$(".bt-compartilhe").click(
		function() {
			var form = $("#compartilhe");
			
			if( $(form).is(":visible") ) {
				$(form).slideUp("normal", function() { $("#bt-compartilhe").css("background","none"); });
				//$(this).parent().stop(true, true).animate({ 'margin':'0', 'padding': '0' });
			} else {
				$(form).slideDown("normal");
				//$(this).parent().stop(true, true).animate({ 'margin':'-5px 0 0 -5px', 'padding': '5px' });
				$(this).parent().css("background","#333");
			}
			
			return false;
		}
	);




/* PAGINAÇÃO
------------------------------------------------------------------*/
	$("#paginacao a").live(
		'click',
		function(event) {
			var url = $(this).attr("href");
			var n = $(".lista-produtos:last").attr("id"); n = n.replace("n-", "");
			var id = "n-"+eval( eval(n) + eval(1) );
			
			$('<img class="loading" src="'+$("#logo a").attr("href")+'/admin/wp-content/themes/puma-time/img/loading.gif" alt="" />').insertAfter(".lista-produtos:last");
			if( $(".container").find("#"+id) ) {
				$('<div style="clear:both"></div><ul id="'+id+'" class="lista-produtos hidden"></ul>').insertAfter(".lista-produtos:last");
			}
			
			$("#"+id).load(
				url + " .lista-produtos > *",
				function() {
					$(".loading").remove();
					$("#"+id).fadeIn();
				}
			);
			
			$(this).parent().load( url + " #paginacao a" );
			
			event.preventDefault();
		} //fecha function() do .click()
	);
	
	
	$(".page-onde-comprar #paginacao a").live(
		'click',
		function(event) {
			var url = $(this).attr("href");
			var n = $(".lista-lojas:last").attr("class"); 
			n = n.replace("lista-lojas", "");
			n = n.replace("lista-", "");
			var id = eval( eval(n) + eval(1) );
			
			$('<img class="loading" src="'+$("#logo a").attr("href")+'/admin/wp-content/themes/puma-time/img/loading.gif" alt="" />').insertAfter(".lista-produtos:last");
			if( $(".container").find(".lista-"+id) ) {
				$('<div id="'+id+'" class="lista-lojas"></div>').insertAfter(".lista-lojas:last").hide();
			}
			
			$("#"+id).load(
				url + " .lista-lojas > *",
				function() {
					$(".loading").remove();
					$("#"+id).slideDown();
				}
			);
			
			$(this).parent().load( url + " #paginacao a" );
			
			event.preventDefault();
		} //fecha function() do .click()
	);
	
	



/* COMO ENCONTRAR A REFERÊNCIA
------------------------------------------------------------------*/
	$("#como-encontrar").hide();
	$("#tutorial-referencia a, .fechar").click(
		function(event) {
			var box = "#como-encontrar";
			if( $(box).is(":visible") ) {
				$(box).slideUp();
			} else {
				$(box).slideDown();
			}
			event.preventDefault();
		}
	);
	
	
	$("#banners li:last").addClass('last');



/* ZOOM IMAGE
------------------------------------------------------------------*/
	$(".zoom a, a.zoom").click(
		function(event) {
			var imagem = $(this).attr("href");
			if( $(imagem).is(":hidden") ) {
				$(imagem).fadeIn();
			}
			
			event.preventDefault();
		}
	);
	
	$(".img-zoom").mouseleave(function() {
		$(this).fadeOut("fast");
	});



/* MOSTRA/ESCONDE
------------------------------------------------------------------*/
	$(".video").hide(); // Esconde todos os boxes
	$("#videos-linha li:first .video").show();
	
	$(".titulo-video").click(
		function() {
			var resposta = $(this).siblings(".video");
			if ( $(resposta).is(':visible') ) {
				$(resposta).slideUp("slow");
			} else {
				$(".video").slideUp("slow");
				$(resposta).slideDown("slow");
			}
		}
	);
	
	var titulos = $(".referencia");
	$("#lista-estilos .imagem-produto").hide(); // Esconde todos os boxes
	
	var id_p = $(".titulo-produto").attr("id");
	if(id_p == undefined)
	{
		id_p = 'produto-capaalt';
	}
	
	var id_produto = id_p.replace("produto-","");
	
	$("#lista-estilos li:first .imagem-produto").show();
	
	$(titulos).click(
		function() {
			 var resposta = $(this).siblings(".imagem-produto");
			 
			 if ( $(resposta).is(':visible') ) {
				 $(resposta).slideUp("slow");
			 } else {
				$(".imagem-produto").slideUp("slow");
				 $(resposta).slideDown("slow");
			 }
		}
	);
	
	
	
});
