$(function(){
	//fix para FF:
	if($.browser.mozilla) $("ol", $("#menuHBlock .menublock .menuHItem")).css("white-space", "nowrap");
	if($.browser.safari) $(".menuHItem").css("display", "inline-block");
		
	//submenus:
	$("#menuHBlock .menublock .menuHItem").each(function(){
		//abre só os submenus que existirem
		if($("OL",this).size()>0 && $("a.menuHItemLink", this).attr('class').indexOf('active')<0){		
			$(this).hover(
			function(){
				$("a.menuHItemLink", this).addClass("menuHItemHover");
				$("OL",this).show();
			},
			function(){
				$("a.menuHItemLink", this).removeClass("menuHItemHover");
				$("OL",this).hide();
			});
		}
	});
	
	// calendários pesquisa
	$(".btOpenCalendario").css("cursor", "pointer").attr("title", "Abrir Calendário").click(function(){
		$(".calendario").hide();
		$(".calendario", $(this).parent()).show();
	});
	$(".close").bind("click",function(event){
		event.preventDefault();
		$(".calendario").hide();
	})
	
	$(".pesquisaAvancadaTopBar").css("cursor", "pointer").attr("title", "Abrir Pesquisa Avançada").toggle(function(){
			$(this).attr("title", "Fechar Pesquisa Avançada");
			$("#contentProcedimentosPesquisaAvancada").show();
			$("#btPesquisaAvancada").attr("src", "/images/bt_close.gif");
		}, function(){
			$(this).attr("title", "Abrir Pesquisa Avançada");
			$("#contentProcedimentosPesquisaAvancada").hide();
			$("#btPesquisaAvancada").attr("src", "/images/bt_inscricao.gif");
	});
	
	// abir caixa formandos
	$(".agendamentoForm .btAddSmall img").css("cursor", "pointer").toggle(function(){
			$(this).attr({title: "Fechar caixa de adição de Formandos", src: "/images/bt_close.gif"});
			$(".addFormandosBlock").show();
		}, function(){
			$(this).attr({title: "Abrir caixa de adição de Formandos", src: "/images/bt_add.gif"});
			$(".addFormandosBlock").hide();			
	});
	
	// adicionar formandos
	var formandosList = new Array;
	
	$(".addFormandosBlockButtonBlock img").css("cursor", "pointer").bind("click", function(event){
		event.preventDefault();
		//pega nos dados preenchidos e junta à lista:
		//apenas se todos os obrigatórios estão preenchidos!
		if($("#nome").val().length != 0 && $("#email").val().length != 0 && ((valida_email($("#email").val()))==true)){
			//adiciono à lista temporária:
			newContent = $("#nome").val() + "; " + $("#email").val() + "; " + $("#funcao").val();
			formandosList.push(newContent); //não é preciso...
			//envio para a caixa de baixo:
			$(".formandosBlock").append("<div class='formandosIndividual' id='formandosIndividual'><div class='btRemoveSmall'><img src='/images/bt_remove.gif' alt='Remover' title='Remover' /></div><div class='formandosIndividualDados'>" + newContent + "</div><div class='clear_both'></div>");
			
			//preparar o botão para remover
			bindRemoveAction()
			
			//apaga containers:
			$("#nome").val('');
			$("#email").val('');
			$("#funcao").val('');
			
			//retira o mandatory:
			$($(".addFormandosBlock label .mandatory").parent()).removeClass("mandatory");
			$(".formandosLabel").removeClass("mandatory");
		}
	});
	
	//remover formandos
	bindRemoveAction();
	
	//submit do form de agendamento:
	$(".btEnviarFormAgendamento").bind("click", function(event){
		event.preventDefault();
		
		//valida os campos:
		nomeEmpresa = $("#nomeEmpresa").val();
		nomeContacto = $("#nomeContacto").val();
		tel = $("#tel").val();
		numFormandos = $("#numFormandos").val();
		numeroFormandos = $(".formandosBlock .formandosIndividual").length;
		
		if(nomeEmpresa == 0 || nomeContacto == 0 || tel == 0 || numFormandos == 0 || numeroFormandos == 0){
			//mostra a caixa de aviso:
			$(".avisoCampos").show();
			//coloca a class do mandatory:
			//vai aos casos em que tem o mandatory e o val() == 0, assim é automático:
			//primeiro retiro a class:
			$($("label .mandatory").parent(), $("input").siblings()).removeClass("mandatory");
			
			//em cada input, se estiver vazio, vai colocar a class do mandatory
			//(ATENÇÃO QUE TEM QUE SE FAZER OS CASOS EXCEPCIONAIS! - ex: validar email, etc)
			$($("label .mandatory").parent(), $("input").siblings()).each(function(){
				if($("input", $(this).parent()).val() == 0){
					$(this).addClass("mandatory");
				}
				if(numeroFormandos == 0){
					$(".formandosLabel").addClass("mandatory");
				} else if(isNaN(numeroFormandos)) {
					$(".formandosLabel").removeClass("mandatory");
					$($(".addFormandosBlock label .mandatory").parent()).removeClass("mandatory");
				} else {
					$(".formandosLabel").addClass("mandatory");
				}
				//$($("label .mandatory").parent(), $("input").siblings()).addClass("mandatory");
			});
			
		} else {
			//todos os campos obrigatórios estão preenchidos :)
			$(".avisoCampos").hide();
			$($("label .mandatory").parent(), $("input").siblings()).removeClass("mandatory");
			
			//vai buscar os outros campos:
			outrosCampos = "Nome Empresa: " + nomeEmpresa + "\r\n" + "Nome Contacto: " + nomeContacto + "\r\n" +"Telefone: " +  tel + "\r\n" + "Número de Formandos: " + numFormandos + "\r\n";
			
			//vai buscar os formandos:
			//numeroFormandos = $(".formandosBlock .formandosIndividual").length;
			//pega no conteúdo de cada:
			listaFormandos = "";
			//tem que existir pelo menos um!!
			a = 0;
			while(a < numeroFormandos){
				listaFormandos = listaFormandos + '|' + $(".formandosBlock .formandosIndividual .formandosIndividualDados:eq("+a+")").text() + "\r\n";
				a++;
			}
			$("#formandos").val(listaFormandos);
			//alert("Estes são os dados para enviar por email:\r\n \r\n" + outrosCampos + "\r\nFormandos:\r\n\r\n" + listaFormandos);
			$("form:first").submit();
			
		
		}
	});
	
})

function procedimentosPesquisaLimpar(){
	$("#inputTexto").val("");
	$("#datapubl01_de").val("Data Inicial");
	$("#datapubl01_a").val("Data Final");
	$("#datapubl02_de").val("Data Inicial");
	$("#datapubl02_a").val("Data Final");
	$("#datapubl03_de").val("Data Inicial");
	$("#datapubl03_a").val("Data Final");
	$("#procedimentosActivos").attr("checked", false);
	
	//estes campos tem que ser actualizados neste js (parte das categorias, etc), porque são dinâmicos!
	$("#selectOrdenar").val("ordem 1");
	$("#selectEntidade").val("entidade 1");
	$("#selectTipoProc").val("tipo 1");
	
	a = 8;
	while(a>0){
		$("#categoria" + a).attr("checked", false);
		a--;
	}
}

function bindRemoveAction(){
	$(".btRemoveSmall").css("cursor", "pointer").bind("click", function(event){
		event.preventDefault();
		$($(this).parent()).remove();
	});
}


//scroll procedimentos home:
var scrollerStep = 1;
var scrollerIntervalMs = 75;

function initScroller()
{
	$('.contentHomeProcedimentosWrapper').each( function() {
		$(this).mouseover(function() { doPause(this); });
		$(this).mouseout(function() { doPause(this); });
	});

	setInterval("doScroll()", scrollerIntervalMs);
}

function doScroll()
{
	$('.contentHomeProcedimentosWrapper').filter(':not(".paused")').each( function() {

		var x = this.scrollTop;

		var divHeight = parseInt($(this).css('height'));
		var contentHeight = this.scrollHeight;

		x += scrollerStep;
		
		//fim do scroll
		if(x > (contentHeight - divHeight)){
			//adiciona-se um espaço no topo, para que ao refazer o scroll não haja uma quebra:
			$('#contentHomeProcedimentos .procedimentosExtra').remove();
			originalContent = $('#contentHomeProcedimentos').html();
			$('#contentHomeProcedimentos').html("<div class='procedimentosExtra' style='display: block; height: 112px; overflow: hidden;'></div>" + originalContent);
			
			x = 0;
		}

		//faz o scroll:
		this.scrollTop = x;

	});
}

function doPause(el)
{
	$(el).toggleClass('paused');
}


function scrollProcedimentosHome(){
	//adicionam-se espaços antes e depois:
	originalContent = $('#contentHomeProcedimentos').html();
	$('#contentHomeProcedimentos').html("<div class='procedimentosExtra01' style='display: block; height: 40px; overflow: hidden;'></div>" + originalContent + "<div style='display: block; height: 152px; overflow: hidden;'></div>");
	
	//scroll:
	initScroller();
}