var Fepra = (function(){
	//var mask, logo;

	return {
		SECTIONS: {
			'clubes': function(){
				Fepra.Clubes.init();
				Fepra.Pista.init();
			},
			'home': function(){
				var $banners = $("#banners"), to = 5000,
					$time = $('#banner-time span').animate({'width': 50}, to, 'linear');
				$banners.find('li').show();
				if ($banners.find('li').size() > 1){
					$banners.carousel({
						pagination: true,
						direction: 'vertical',
						prevBtnInsert: 'appendTo',
						effect: 'fade',
						animSpeed: 'slow',
						autoSlide: true,
						autoSlideInterval: to,
						callback: function(step){
							$time.stop(true).width(0).animate({'width': 50}, to, 'linear');
						}
					});
				}
				$banners.find('a').attr('target', '_blank');
				$('<div class="banner-top">').appendTo($banners).css('opacity', .2);
				$('<div class="banner-bottom">').appendTo($banners).css('opacity', .6);
			},
			'paginas': function(){
				$('#pagina-documentos .documentos').not(':first').hide();
				var documentos = $('#pagina-documentos .documentos');
				var triggers = $('#pagina-documentos h5 a');
				$('#pagina-documentos h5 a:first').addClass('active');
				triggers.click(function(){
					if ($(this).hasClass('active')){
						return false;
					}
					triggers.not(this).removeClass('active');
					$(this).addClass('active');

					var d = $(this).parent().next('.documentos');
					documentos.not(d).slideUp('fast');
					d.slideDown('fast');

					return false;
				});
			},
			'eventos': function(){
				$('.evento .close .evento-info').hide();
				$('.evento h3 a').addClass('closed').click(function(){
					var $el = $(this);
					var $info = $el.parent().nextAll('.evento-info');

					if ($info.is(':visible')){
						$el.removeClass('open').addClass('closed');
						$info.slideUp('fast');
					}else{
						$el.removeClass('closed').addClass('open');
						$info.slideDown('fast');
					}
					return false;
				});
			}
		},
		init : function(){
			this.setup();

			var mask = $('#page-mask');
			if ($.cookie('visita')){
				mask.remove();
				return;
			}
			$.cookie('visita', '1', {path: '/'});

			$('h1').css({
				'opacity': 0,
				'position': 'absolute',
				'z-index': 102
			});

			var logo = $('<img id="logotipo" class="pngfix">').appendTo('body').hide().load(function(){
				var top = ($(window).height() - logo.height()) / 2,
					left = ($(window).width() - logo.width()) / 2;
				logo.css({
					'top': top,
					'left': $(window).width() + logo.width()
				}).show().animate({
					'left': left
				}, 2000, 'easeInOutBounce', function(){
					mask.animate({'opacity': 0}, 400, function(){
						mask.remove();
						var pos = $('h1').offset();
						logo.animate({
							'left': pos.left,
							'top': 0,
							'width': 220,
							'height': 76
						}, 1200, 'easeOutQuad', function(){
							$('h1').animate({
								'opacity': 1
							}, function(){
								logo.remove();
							});
						});
					});
				});

			});
			logo.attr('src', MEDIA_URL + 'static/img/logo-grande.png');
		},

		setup : function(){
			if (window.setupZoom){
				setupZoom();
			}

			var section = $('body').attr('class');
			if (this.SECTIONS[section]){
				this.SECTIONS[section]();
			}

			Cufon.replace('#nav a', {
				textShadow: '#FFF 1px 1px',
				hover: true
			});

			Cufon.replace('.content-wrap h2', {
				color: '-linear-gradient(0.5=#C00, #600)'
			});

			$('#nav-column li ul').each(function(){
				if ($('li a.current', this).size() == 0){
					$(this).hide();
				}
			});
			$('#nav-column li>a').click(function(){
				var ul = $(this).parent().children('ul').get(0);
				$('#nav-column li ul').not(ul).slideUp(300);
				$(ul).slideDown(300);
				return false;
			});

			$('#form-username-el, #form-password-el').each(function(){
				//$(this).val($(this).prev().html());
				$(this).parent()[$(this).val() ? 'addClass' : 'removeClass']('active');
			}).bind('focus', function(){
				$(this).parent().addClass('focus');
			}).bind('blur', function(){
				$(this).parent()[$(this).val() ? 'addClass' : 'removeClass']('active');
				$(this).parent().removeClass('focus');
			});

			this.renderEventos();
		},

		renderEventos : function(){
			var selected = [];
			for (data in EVENTOS){
				selected.push(data)
			}
			var calendario = new YAHOO.widget.Calendar('calendario', {
				start_weekday: 1,
				navigator: {
					strings : {
						month: "Escolha o M&ecirc;s",
						year: "Introduza o Ano",
						submit: "OK",
						cancel: "Cancelar",
						invalidYear: "Por favor introduza o ano correcto"
					},
					monthFormat: YAHOO.widget.Calendar.LONG,
					initialFocus: "Ano"
				},
				pagedate: TODAY,
				selected: selected.join(',')
			});
			calendario.cfg.setProperty("MONTHS_LONG", [
				"Janeiro",
				"Fevereiro",
				"Março",
				"Abril",
				"Maio",
				"Junho",
				"Julho",
				"Agosto",
				"Setembro",
				"Outubro",
				"Novembro",
				"Dezembro"
			]);
			calendario.cfg.setProperty("WEEKDAYS_SHORT", ["D", "S", "T", "Q", "Q", "S", "S"]);
			calendario.renderEvent.subscribe(function(){
				$('#calendario td.selected a').each(function(){
					if ($(this).data('qtip')) return;

					var cell = $(this).parent().get(0);
					var data = calendario.getDateByCellId(cell.id);
					var data_key = [data.getMonth()+1, data.getDate(), data.getFullYear()].join('/');

					var tooltip = [], len = EVENTOS.length;
					$.each(EVENTOS[data_key], function(){
						tooltip.push(
							'<div class="cal-evento">' +
								'<a href="' + this.url + '">' + this.nome + ' / ' + this.ambito + '</a>' +
								'<span>' + this.tipo + ' / ' + this.escala + '</span>' +
							'</div>'
						);
					});
					$(this).qtip({
						content: tooltip.join(''),
						position: {
							corner: {
								tooltip: 'bottomMiddle',
								target: 'topMiddle'
							}
						},
						hide: {
							fixed: true
						},
						style: {
							background: '#282828',
							border: {
								width: 3,
								radius: 6,
								color: '#282828'
							},
							textAlign: 'left',
							tip: true,
							name: 'dark'
						}
					});
				});

			}, calendario, true);
			calendario.renderCellDefault = function(data, cell){
				var label = this.buildDayLabel(data);

				if (!$(cell).hasClass('selected')){
					$(cell).removeClass('selectable').text(label);
				}else{
					cell.innerHTML = '<a href="#" class="selector">'+label+'</a>';
					this.renderCellStyleSelected(data, cell);
				}

				//return YAHOO.widget.Calendar.STOP_RENDER;
			};
			calendario.render();
		}
	}
})();

Fepra.Clubes = (function(){
	return {
		init : function(){
			if (window['google']){
				google.load('maps', '2', {
					'locale': 'pt',
					'callback': this.onMapsLoaded
				});
			}
		},

		onMapsLoaded : function(){
    		var INITIAL_LAT = 39.487084981687495;
			var INITIAL_LON = -8.0419921875;

			if (GBrowserIsCompatible()) {
	            var map = new GMap2($('#mapa').get(0));
	            map.setCenter(new GLatLng(INITIAL_LAT, INITIAL_LON), 7);
	            map.addControl(new GSmallZoomControl());
	            map.addControl(new GMapTypeControl());

				$.each(CLUBES, function(i, clube){
					var marker = new GMarker(new GPoint(clube.longitude, clube.latitude));
	    			GEvent.addListener(marker, "click", function() {
		                marker.openInfoWindowHtml([
		                	'<div><strong><a href="', clube.url, '">',
		                	clube.nome, '</a></strong><br />', clube.distrito, '</div>'
		                ].join(''));
		            });
	            	map.addOverlay(marker);
	            });
	        }
		}
	}
})();

Fepra.Pista = (function(){
	var self, foto;

	return {
		init : function(){
			self = this;
			foto = $('#foto img');
			$('#fotos img').css('opacity', .5);
			$('#fotos a').hover(function(){
				$(this.firstChild).stop(true).animate({'opacity': 1});
			}, function(){
				$(this.firstChild).stop(true).animate({'opacity': .5});
			}).click(self.onFotoClick);

			if ($('#fotos').size() > 0){
				$('#fotos').append([
					'<a class="carousel-prev" href="#" title="Anterior">Anterior</a>',
					'<a class="carousel-next" href="#" title="Seguinte">Seguinte</a>'
				].join('')).carousel({
					visible: 5,
					selectors: {
						scroller: 'ul',
						item: 'li',
						prev: '#fotos .carousel-prev',
						next: '#fotos .carousel-next'
					}
				});
			}
		},

		onFotoClick : function(){
			var img = new Image(), src = this.rel;
			$(img).bind('load', function(){
				foto.attr('src', this.src);
				foto.animate({'opacity': 1});
			});
			foto.animate({'opacity': 0}, function(){
				img.src = src;
			});
			return false;
		}
	}
})();

$(function(){
	$('html').addClass('js');

	Fepra.init();
});

