// *** Tarefas realizadas a priori ***

// Criação do nodo DOM para representar a folha de estilo do tema de alto
// contraste com a referência recuperada no arquivo template-principal.xhtml
var highContrastStylesheet = document.createElement('link');
$(highContrastStylesheet).attr('id', 'highContrastStylesheet');
$(highContrastStylesheet).attr('href', highContrastStylesheetHref);
$(highContrastStylesheet).attr('rel', 'stylesheet');
$(highContrastStylesheet).attr('type', 'text/css');

// Restaurar tema selecionado
restoreTheme();

// Tamanho inicial da fonte do corpo dado em px, bem como seus limites
var defaultFontSize = 12;
var minFontSize = 9;
var maxFontSize = 15;

function storeFontSize(fontSize) {
	$.cookie('sigepe_font-size', fontSize, {path: '/'});
}

function restoreFontSize() {
	var previousFontSize = $.cookie('sigepe_font-size');
	if (previousFontSize)
		$('body').css('font-size', parseInt(previousFontSize));
}

function resizeFont(delta) {
	var currentFontSize = parseInt($('body').css('font-size').slice(0, -2));
	var newSize = currentFontSize + delta;

	if (newSize >= minFontSize && newSize <= maxFontSize) {
		$('body').css('font-size', newSize);
		storeFontSize(newSize);
	}
}

function resetFontSize() {
	$('body').css('font-size', defaultFontSize);
	storeFontSize(defaultFontSize);
}

// Verifica se o mouse está sobre algum elemento html quando do disparo de algum
// evento
function isHovering(event, object) {
	var mouseX = event.pageX;
	var mouseY = event.pageY;

	var offset = object.offset();
	var objX = offset.left;
	var objY = offset.top;
	var objW = object.outerWidth();
	var objH = object.outerHeight();

	return (mouseX >= objX && mouseX <= (objX + objW))
			&& (mouseY >= objY && mouseY <= (objY + objH));
}

function toggleUserDetail() {
	$('.userinfo-detail').fadeToggle();
}

function hideUserDetail() {
	$('.userinfo-detail').fadeOut();
}

function toggleMenu() {
	$('.content-side-menu').animate({
		width : 'toggle'
	}, 500);
	// Alteração do sinal de abertura/fechamento do menu
	$('.side-menu-signal').toggle();
}

function hideMenu() {
	$('.content-side-menu').animate({
		width : 'hide'
	}, 500);
	// Alteração do sinal de abertura/fechamento do menu
	$('.ui-icon-triangle-1-w.side-menu-signal').hide();
	$('.ui-icon-triangle-1-e.side-menu-signal').show();
}

function bindExpandableCollapsibleBehavior(panelSelector, triggerSelector,
		toggleFunction, hideFunction) {
	// Elementos diferentes do painel expansível
	$('*:not(' + panelSelector + ')').click(function(event) {
		var $target = $(event.target);

		// Se o elemento de origem do evento passar pelo acionador da
		// expansão/contração
		if ($target.closest(triggerSelector).length) {
			event.stopPropagation();
			toggleFunction();
		}

		// Se a origem passar pelo painel expansível, prosseguir
		else if ($target.closest(panelSelector).length) {
			;
		}

		// Senão, se trata de um clique sem ligação com o acionador nem o painel
		// expansível e representa um "clique fora", ou seja, o painel pode ser
		// fechado
		else
			hideFunction();
	});
}
// Apenas para não faltar referência no clique no logotipo do sistema
function redirectOnClickLogo() {
	return false;
}

function toggleTheme() {
	var themeIndex = (parseInt($.cookie('sigepe_theme_index')) + 1) % 2;

	// Tema de alto contraste
	if (themeIndex != 0)
		$('head').first().append(highContrastStylesheet);
	// Tema normal
	else
		$(highContrastStylesheet).remove();

	$.cookie('sigepe_theme_index', themeIndex, {path: '/'});
}

function restoreTheme() {
	var themeIndex = $.cookie('sigepe_theme_index');

	// Tema de alto contraste
	if (themeIndex != null) {
		if (parseInt(themeIndex) != 0)
			$('head').first().append(highContrastStylesheet);
	} else
		$.cookie('sigepe_theme_index', 0, {path: '/'});
}

$(function() {
	// Restaurar o tamanho da fonte segundo redimensionamentos anteriores
	restoreFontSize();

	// Comportamento da aba de informações do usuário
	bindExpandableCollapsibleBehavior('.userinfo-detail', '.userinfo-trigger',
			toggleUserDetail, hideUserDetail);

	// Tratamento do acionador "Alterar imagem"
	$('.userinfo-photo').mouseenter(function() {
		$('.userinfo-change-photo').fadeIn();
	}).mouseleave(function(event) {
		if (!isHovering(event, $('.userinfo-change-photo')))
			$('.userinfo-change-photo').fadeOut();
	});

	$('.userinfo-change-photo').mouseleave(function(event) {
		if (!isHovering(event, $('.userinfo-photo')))
			$('.userinfo-change-photo').fadeOut();
	});

	// Acionamento da barra "Acesso rápido"
	$('.btn-collapse-footer').click(function() {
		$('.footer-detail').fadeToggle();
		$(this).find('.signal-icon').toggle();

		// Scroll para o fim da página (para mostrar as opções de acesso rápido)
		$('html').animate({
			scrollTop : $(document).height()
		});
	});

	// Acionamento do menu lateral "Menu de Processos"
	bindExpandableCollapsibleBehavior('.content-side-menu', '.btn-side-menu',
			toggleMenu, hideMenu);

	// Aumentar fonte
	$('.fontPlus').click(function() {
		resizeFont(1);
	});

	// Diminuir fonte
	$('.fontMinus').click(function() {
		resizeFont(-1);
	});

	// Fonte no tamanho normal
	$('.font').click(function() {
		resetFontSize();
	});

	// Atribuir o comportamento de redirecionamento ao se clicar no
	// logotipo do sistema
	$('#logo').click(function() {
		redirectOnClickLogo();
	});
});