// Lisbela

//////////////////
// ScrollPages //
////////////////
$.extend({
	scrollPages: {
		defaults: {
			elementSize: 50,
			elements: 3,
			speed: "slow",
			direction: "up"
		}
	}
});
$.fn.extend({
	scrollPages: function(options){
		options = $.extend({}, $.scrollPages.defaults, options);
		return this.each(function(){
			
			// Definições de variáveis
			var total = $(".scrollMask li",this).length;
			var mask = options.elementSize * options.elements;
			var area = options.elementSize * total;
			var animation = false;
			var obj = this;
			var dimension = options.direction == "left" ? "width" : "height";
			var side = new Array();
			side[0] = options.direction;
			side[1] = options.direction == "up" ? "down" : "right";
			
			$(".scrollButtom",this).css("visibility","visible");
			if(options.elements >= total){
				$(".scrollButtom",this).css("visibility","visible");
				mask = area;
			}else{
				$(".scrollButtom[rel*='"+options.direction+"']",obj).css("visibility","hidden");
			}
			
			// Aplicação de estilos
			$(".scrollMask",this).css({"width": mask + "px", overflow: "hidden"}); // Máscara
			$(".scrollMask ul",this).css({"width": area + "px", marginTop: 0}); // UL
			$(".scrollMask li",this).css({"width": options.elementSize + "px", display: "block"}); // LI

			// Função que executa a rolagem
			var rolagem = function(direction){

				// Variáveis
				var margem = -parseInt($(".scrollMask ul",obj).css("margin-"+(options.direction == "up" ? "top" : "left")));

				var intervalo = direction == side[1]
					? ( margem + ( mask * 2 ) ) < area
						? mask
						: area - (margem + mask)
					: ( margem - mask ) < 0
						? margem
						: mask
				;
				direction = direction == side[1]
					? -margem - intervalo
					: -margem + intervalo
				;
				
				$(".scrollButtom",obj).css("visibility","visible");
				var rel = -direction == 0 ? side[0] : (-direction + mask) == area ? side[1] : null;
				if(rel != null) $(".scrollButtom[rel*='"+rel+"']",obj).css("visibility","hidden");
				
				// Animação
				animation = true;
				if(options.direction == "up"){
					$(".scrollMask ul",obj).animate({marginTop: direction + "px"},options.speed,function(){ animation = false; });
				}else{
					$(".scrollMask ul",obj).animate({marginLeft: direction + "px"},options.speed,function(){ animation = false; });
				}
			}
			
			// Aplicação de eventos
			$(".scrollButtom",this).unbind("click").click(function(){
				if(!animation){
					var direction = $(this).attr("rel");
					rolagem(direction);
				}
			});
		});
	}
});


////////////
// Select //
////////////
estiloSelect = {
	init: function(){
		var primeiro = 0;
		$("select.select").each(function(){
			var _max = $(this).attr('class').split(" max")[1];
			var html =  '<div id="' + $(this).attr("id") + '" class="' + $(this).attr("class") + '">';
				html += '	<div class="ativo"></div>';
				html += '	<input id="' + $(this).attr("id") + '_select" name="' + $(this).attr("name") + '" type="hidden" value="" />';
				html += '	<div class="options">';
				for(i=0;i<$("option",this).length;i++){
					
					var texto = $("option:eq(" + i + ")",this).text();
					if(texto.length > _max) texto = texto.substr(0,_max) + "..."
					
					html += '	<a href="';
					
					if ($(this).hasClass('selectDicas'))
						html += 'dicas-da-lisbela.php?dica=' + $("option:eq(" + i + ")",this).val();
					else
						html += 'javascript:void(0);';			
					
					html += '" title="' + $("option:eq(" + i + ")",this).text() + '" rel="' + $("option:eq(" + i + ")",this).attr("value") + '">' + texto + '</a>';
				}
				html += '	</div>';
				html += '</div>';
			
			$(this).replaceWith(html);
			$("option",this).each(function(i){
				primeiro = this.selected ? i : primeiro;
			});
		});
		$("div.select").css("visibility","visible").each(function(){
			var altura = $("a",this).length;
				altura = altura > 5 ? 5 : altura;
			$(".options",this).css({height:(altura * parseInt($("a:first",this).css("height"))) + "px", visibility:"visible", display:"none"});
			estiloSelect.change(this,primeiro);
		})
		$("div.select .ativo").unbind().click(function(){
			$(this).parent().parent().css("z-index","3");
			$(this).siblings(".options").slideDown('fast',function(){
				$("html").bind('click',estiloSelect.fecha);
			});
		});
		$("div.select").each(function(){
			$("a", this).each(function(i){
				$(this).unbind().click(function(){
					estiloSelect.change($(this).parents("div.select:eq(0)"),i);
				});
			});
		});
	},
	
	change: function(obj,option){
		$("a.optionAtivo",obj).removeClass("optionAtivo");
		$("a:eq(" + option + ")",obj).addClass("optionAtivo");
		var texto = $("a:eq(" + option + ")",obj).text();
		var valor = $("a:eq(" + option + ")",obj).attr("rel");
		$(".ativo",obj).html(texto);
		$("input",obj).val(valor);
		estiloSelect.fecha();
	},
	
	fecha: function(){
		$("div.select .options:visible").slideUp('fast',function(){$(this).parent().parent().css("z-index","2")});
		$("html").unbind('click',estiloSelect.fecha);
	}
}

/////////////////////////
//		:: Tira bordas do Flash no IE ::
//	
//		Retira as bordas pontilhadas do flash no Internet Explorer
//		Ex.: 	$("#flash").addFlash({
//					src: "swf/banner2.swf",
//					width: 584,
//					height: 201,
//					title: ""
//				});
////////////////////////////////////////////////////////////////////////
$.extend({
	addFlash: {
		defaults: {
			src: "",
			width: 100,
			height: 50,
			title: "",
			quality: "high",
			menu: "false",
			wmode: "transparent"
		}
	}
});
$.fn.extend({
	addFlash: function(options){
		options = $.extend({}, $.addFlash.defaults, options);
		return this.each(function(){
			if(options.src != ""){
				var flash = '<object type="application/x-shockwave-flash" data="'+options.src+'?clicktag=./" width="'+options.width+'" height="'+options.height+'" tabindex="0" title="'+options.title+'">'
				flash += '<param name="movie" value="'+options.src+'?clicktag=./" />'
				flash += '<param name="quality" value="'+options.quality+'" />'
				flash += '<param name="menu" value="'+options.allowFullScreen+'" />'
				flash += '<param name="wmode" value="'+options.wmode+'" />'
				flash += '<p>Para visualizar este conteúdo corretamente, é necessário ter o <a title="Clique para instalar o flash player" href="http://www.macromedia.com/shockwave/download/alternates/" rel="nofollow">Flash Player</a> instalado.</p>'
				flash += '</object>'
				$(this).html(flash);
			}
		});
	}
});

////////////
//	Função que centraliza um objeto na tela.
//	ex:
//	$("#teste").absoluteCenter({limit:[0,10,0,10]});
////////////////////////////////////////////////////
$.fn.extend({
	absoluteCenter: function(options, speed, callback){
		var defaults = {
			dellay: 100,
			limitTop: 0,
			limitRight: 0,
			limitBottom: 0,
			limitLeft: 0,
			limit: null,
			animation: true
		}
		options = $.extend({}, defaults, options);
		
		if(options.limit != null){
			if(typeof(options.limit) == "object"){
				options.limitTop = typeof(options.limit[0]) != "undefined" ? options.limit[0] : options.limitTop;
				options.limitRight = typeof(options.limit[1]) != "undefined" ? options.limit[1] : options.limitRight;
				options.limitBottom = typeof(options.limit[2]) != "undefined" ? options.limit[2] : options.limitBottom;
				options.limitLeft = typeof(options.limit[3]) != "undefined" ? options.limit[3] : options.limitLeft;
			}else{
				options.limitTop = options.limit;
				options.limitRight = options.limit;
				options.limitBottom = options.limit;
				options.limitLeft = options.limit;
			}
		}
		
		speed = typeof(speed) == "undefined" ? "fast" : speed;
		
		return this.each(function(){

			var obj = this;
			var timeOut = null;
			
			var ajustaScroll = function(){
				
				if($(obj).css("display") == "none") $(window).unbind("scroll",ajustaScroll).unbind("resize",ajustaScroll);
				
				var altura = parseInt($(obj).outerHeight());
				var largura = parseInt($(obj).outerWidth());
				
				var limiteC = parseInt($(obj).css("top"));
				var limiteB = limiteC + altura;
				var limiteE = parseInt($(obj).css("left"));
				var limiteD = limiteE + largura;
				
				var scrollTop = parseInt($(window).scrollTop());
				var scrollLeft = parseInt($(window).scrollLeft());
				var janelaAltura = parseInt($(window).height());
				var janelaLargura = parseInt($(window).width());
				
				var documentoAltura = parseInt($("body").outerHeight());
				var documentoLargura = parseInt($(document).width());
				
				var top = janelaAltura > altura
					? parseInt(scrollTop + (( janelaAltura / 2 ) - parseInt(altura / 2)))
					: scrollTop < (limiteC - options.limitTop)
						? scrollTop + options.limitTop
						: (scrollTop + janelaAltura) > (limiteB + options.limitBottom)
							? scrollTop - (altura - janelaAltura) - options.limitBottom
							: limiteC
				;
				top = (top + altura) > documentoAltura ? documentoAltura - altura : top;
				
				var left = janelaLargura > largura
					? parseInt(scrollLeft + (( janelaLargura / 2 ) - parseInt(largura / 2)))
					: scrollLeft < (limiteE - options.limitLeft)
						? scrollLeft + options.limitLeft
						: (scrollLeft + janelaLargura) > (limiteD + options.limitRight)
							? scrollLeft - (largura - janelaLargura) - options.limitRight
							: limiteE
				;
				left = (left + largura) > documentoLargura ? documentoLargura - largura : left;

				if(options.animation){
					clearTimeout(timeOut);
					timeOut = setTimeout(function(){
						$(obj).animate({top:top+"px",left:left+"px"},speed,function(){ if(typeof(callback) != "undefined") callback(); });
					},options.dellay);
				}else{
					$(obj).css({top:top+"px",left:left+"px"});
				}
			}
			ajustaScroll();
			
			if(options.animation) $(window).scroll(ajustaScroll).resize(ajustaScroll);
		});
	}
});


$(document).ready(function(){
		
	$('.miniatura').scrollPages({elementSize:162, elements:3, direction:'left'});
	$('.convitesHome').scrollPages({elementSize:195, elements:1, direction:'left'});
	$('.convitesHome .scrollMask').css('visibility','visible');
	estiloSelect.init();
	

	$("#banner").addFlash({
					src: "swf/banner.swf",
					width: 941,
					height: 229,
					title: "Lisbela - Convites e Eventos"
				})
	
	
	// Menu Dropdown
	var clearMenu;
	
	$('.redesSociais > li:eq(0)').hover(function(){
		clearTimeout(clearMenu);
		if (!$('ul',this).is(':visible')){
			$('.redesSociais > li:not(this) > ul:visible').hide('fast');
			$('ul',this).show('fast');
		}
	},function(){
		var li = $(this)
		clearMenu = setTimeout(function(){$('ul',li).hide('fast');},500)
	});
	
	
////////
///   Adiciona classe ativo na tag <a> que apontar para a página aberta
////////////////////////////////////////////////////////////////////////
	paginaAtiva = window.location+"";
	paginaAtiva = paginaAtiva.split("/").pop();
	if(paginaAtiva != "") $("a[href="+paginaAtiva+"]").addClass("ativo");


////////
///   Abas
///////////////////////////////////////
	$('.abas li a').click(function(){
		var obj = $(this).parents('div:eq(0)');
		var ul = $(this).parents('ul:eq(0)');
		var indice = $('a', ul).index(this);
		$('li a.ativo', obj).removeClass('ativo');
		$(this).addClass('ativo').css('opacity', '1');
		$('.conteudoAba > div:not(:eq('+indice+'))', obj).hide().find('input, textarea').attr('disabled', 'disabled');
		$('.conteudoAba > div:eq('+indice+')', obj).show().find('input, textarea').removeAttr('disabled');
		
		$('.conteudoAba2 > div:not(:eq('+indice+'))', obj).hide();
		$('.conteudoAba2 > div:eq('+indice+')', obj).show();
	});
	
////////
///   Slide da Aba Frotas
//////////////////////////////
	slideFrota = function(){
		var obj = $('.frotas ul');
		var margem = parseInt($(obj).css('margin-left'));
		var qt = $('li', obj).length;
		var li = 315;
		var maximo = li * qt;
		
		margem = margem - li;
		
		if (margem + maximo <= 0) margem = 0
		$(obj).width(li*qt).fadeOut(function(){
			$(this).css({marginLeft: margem + "px"}).fadeIn();
		});
	}
	
	slideTime = setInterval('slideFrota()', 10000);
	
////////
///   Slide dos Boxes Convites e Tranportes
/////////////////////////////////////////////
	divSlide = function(){
		$('.divSlide .legenda').hide();
		$('.divSlide li:not(.hide)').fadeOut(function(){
			$(this).addClass('hide')
			.siblings().fadeIn(function(){
						$(this).removeClass('hide');
						$('.divSlide .legenda').show();
			});
		})
	}
	slideTime2 = setInterval('divSlide()', 15000);

////////
///   Exibir Galeria
//////////////////////////////
	$('.verGaleria').click(function(){
		var index = $(this).attr('rel');
		var orcamento = $(this).parents('li:eq(0)').find('a.botao').attr('href');
		$("ul.ampliar a.convite_"+index).click()
		$('#bloqueio').css({height:$('body').height(), opacity:0.3}).fadeIn('fast',function(){
			$('.galeria').absoluteCenter({animation:false}).absoluteCenter().show();
			$('.galeria a.orcamento').attr('href',orcamento)
		})
	
	});
	$('.fecharGaleria').click(function(){
		$('.galeria').hide();
		$(window).unbind("scroll").unbind("resize");
		$('#bloqueio').fadeOut();
	});
	
	$('.assistir').click(function(){
		var dado = $(this).attr('rel');
		var arquivo = dado.replace('imagens','swf') + ".html"

		//if (dado.indexOf('short') == -1)
			window.open(arquivo,"Janela","height=600, width=800, menubar=no, location=no, scrollbars=no");			
		//else
			//window.open(arquivo,"Janela","height=480, width=640, menubar=no, location=no, scrollbars=no");
	})
	
//////
//  Galeria
/////////////////////////
	$(".ampliar img").css({opacity:0.5});
	
	$("ul.ampliar a").click(function(){
								 
		var obj = $(this).parents(".galeria");
		var texto = $(this).attr('title');
		var descri = $(this).siblings('span').html();
		var id = $(this).attr('class').replace('convite_','');
		
		if(!$("img", this).hasClass("ativo")){								
			$("img.ativo", obj).removeClass("ativo").animate({opacity:0.5});
			$("img", this).addClass("ativo").animate({opacity:1});
			
			
			$(".ampliada img", obj).attr("src","imagens/blank.gif");
			
			var src = $(this).attr("rel");
			var img = new Image();
			$("span strong", obj).css('visibility', 'hidden');
			$("span.texto", obj).css('visibility', 'hidden');
			$('.assistir, a.orcamento').hide();
			$(".carregando", obj).show();
			
			img.src = src;
			
			img.onload = function(){
				$(".carregando", obj).hide();
				$(".ampliada img", obj).attr("src",src);
				$("span strong", obj).css('visibility', 'visible').text(texto);
				$("span.texto", obj).css('visibility', 'visible').html(descri);
				$(".assistir", obj).attr('rel',src.split(".")[0]).show();
				var orcamento = $("a.orcamento", obj).attr('href');
				orcamento = orcamento.split('id=')[0] + 'id=' + id
				$("a.orcamento", obj).attr('href',orcamento).show();
			}
			
			
			var rolar = parseInt($("ul",obj).css("margin-left"));
			
			var valor = 1;
			var valor2 = 0
			$(".ampliar img", obj).each(function(){
				if($(this).attr("class") == "ativo"){
					valor2 = valor;
				}else{
					valor = valor + 1;
				}
			});
			
			valor2 = valor2 - 1;

			if (valor > 3){
				$(".seta[rel=left]", obj).css("visibility","visible");
				$(".seta[rel=right]", obj).css("visibility","visible");
			}
			if (valor2 > 1 && valor2 + 1 < valor){
				rolar = valor2 * 162 - 162;
			}else if(valor2 <= 1){
				rolar = 0;
				$(".seta[rel=left]", obj).css("visibility","hidden");
	
			}else if(valor2 + 1 >= valor){
				rolar = valor * 162 - 486;
				$(".seta[rel=right]", obj).css("visibility","hidden");
			}
			
			if(valor < 3){
				rolar = 0;
				$(".seta[rel=right]", obj).css("visibility","hidden");
			}
			
			$("ul", obj).animate({marginLeft : -rolar+"px"})
		}
	});

	
/////
// Função para slide de clientes
/////////////////////////////////////

	slideConvite = function(){
		var obj = $('.abaConvites > div:visible > div > div > ul');

		var margem = parseInt($(obj).css('margin-left'));
		var qt = $('li', obj).length;
		var li = 195;
		var maximo = li * qt;
		
		margem = margem - li;
		
		if (margem + maximo <= 0) margem = 0
		var div = $(obj).parent().parent() 
		$(obj).fadeOut(function(){
			$(this).css({marginLeft: margem + "px"}).fadeIn();
			$('.seta', div).css('visibility','visible');
			if (margem == 0) $('.seta[rel="left"]', div).css('visibility','hidden');
			if (margem == -maximo+li) $('.seta[rel="right"]', div).css('visibility','hidden');
		});
	}
	
	slideTime1 = setInterval('slideConvite()', 4000);
	
	$('.convitesHome').hover(function(){
		clearInterval(slideTime1)
	},function(){
		slideTime1 = setInterval('slideConvite()', 4000);
	})

	
	
	
	
/////
// Ajax para envio de newsletter
/////////////////////////////////////
	
	$('#formNews').submit(function(){
		var validar = true;
		var campos = ''
		$('input.requer', this).each(function(){
		
			if( $(this).val() == ''){
				validar = false;
				campos += '"' + $(this).attr('title') + '", '
			}
			
		});
		if (!validar){
			alert('O(s) campo(s)\n\n '+campos+'\n\n nao pode(m) ficar vazio(s).');
			$('input.requer', this).each(function(){
				if( $(this).val() == ''){
					$(this).focus();
					return false;
				}
			});
			return false;
		}
		
		
		$.ajax({
		   type: "POST",
		   url: "inc/newsletter.php",
		   data: $(this).serialize(),
		   success: function(msg){
			   	
			 	msgNew = '<div class="galeria msgNews" style="overflow: visible; top: 223px; left: 296px; display: block;">'
					+'		<a class="fecharGaleria" title="Fechar" href="javascript:void(0);">Fechar</a>'
					+'	<div class="inicio"/>'
					+'		<div class="conteudo">'
					+'	<p><strong>Cadastro efetuado com sucesso.</strong></p>'
					+'  <p>A partir de agora voc&ecirc; receber&aacute; novidades peri&oacute;dicas da Lisbela no seu email.</p>'
					+'	</div>'
					+'		<div class="fim"/>'
					+'	</div>'
					
				$('body').append(msgNew);
				
				$('#bloqueio').css({height:$('body').height(), opacity:0.3}).fadeIn('fast',function(){
					$('.msgNews').absoluteCenter({animation:false}).absoluteCenter().show();
					$('.msgNews .fecharGaleria').click(function(){
						$('.msgNews').remove();
						$(window).unbind("scroll").unbind("resize");
						$('#bloqueio').fadeOut();
					});
				});

		   }
		 });
		
		return false;
	});
	
	
	$('form:not(#formNews)').submit(function(){
		var validar = true;
		var campos = ''
		$('input.requer', this).each(function(){
		
			if( $(this).val() == ''){
				validar = false;
				campos += '"' + $(this).attr('title') + '", '
			}
			
		});
		
		$('select.requer',this).each(function(){
			if( $(this).val() == '0'){
				validar = false;
				campos += '"' + $(this).attr('title') + '", '
			}
		});
		
		if ($('#FC_quantidade:enabled').val() == '0' && $('#FC_outra_qt:enabled').val() == '' ){
			validar = false;
			campos += '"Quantidade", '
		}
		
		if (!validar){
			alert('O(s) campo(s)\n\n '+campos+'\n\n nao pode(m) ficar vazio(s).');
			$('input.requer', this).each(function(){
				if( $(this).val() == ''){
					$(this).focus();
					return false;
				}
			});
			return false;
		}
	});
	
	
	//$('ul.abas a:eq(0)').click();
	
////////
///   Efeito Sanfona 
////////////////////////////////////////////////////////////////////////						   
	$('.sanfona a').click(function(){
		if( $(this).hasClass('ativo') )
			$(this).removeClass('ativo').siblings('div').slideUp('fast');
		else{
			$('.sanfona div:visible').slideUp('fast');
			$('.sanfona a').removeClass('ativo');
			$(this).addClass('ativo').siblings('div').slideDown();
		}
	})
	
////////
///   Dropdown Modelos 
////////////////////////////////////////////////////////////////////////	
	$('.selectCateg').change(function(){
		$('.selectModelo').attr('disabled','disabled');
		$('.selectModelo option:gt(0)').remove();
		$('.selectModelo option').text('Carregando...');
		$.ajax({
			type: "POST",
			url: "inc/modelos_convites.php",
			data: $(this).serialize(),
			success: function(r){
				$('.selectModelo option').text('Selecione...');
				$('.selectModelo').append(r).removeAttr('disabled');
			},
			error: function(){
				alert('Não foi possivel carregar os modelos, tente novamente mais tarde.');
				$('.selectModelo option').text('Selecione...');
				$('.selectModelo').removeAttr('disabled');
				$('.selectCateg').val('0');
			}
		});
	
	});
	
})