$(function() {

	var $header = $('header');
	
	$('#text-option').click(function(e) {
	
		e.preventDefault();
		
		$('#text-option-overlay').toggleHidden();
	
	});
	

	/* Scroll start & stop */
	var $window = $(window),
	
		timer = false,
		
		onScroll = function(e) {
		
			if(timer) {
				clearTimeout(timer);
			} else {
				$window.trigger('scrollstart', e);
			}
			timer = setTimeout(function() {
				$window.trigger('scrollend', e);
			}, 50);
		};
	
	$window.scroll(onScroll);
	/**/
	
	// Detect read paragraphs
	$window.on('scrollend', function() {
		
		var readPosition = document.body.scrollTop;
		
		$('section.active p:not(.read)').each(function() {
			if((this.offsetTop + this.offsetHeight) <= readPosition) {
				$(this).markAsRead();
			}
		
		});
	});
	
	
	var currentBlockId = 0,
	
		unblock = function() {
			console.log('unblock', currentBlockId);
			$('.glossary p.hidden').each(function() {
				
				if($(this).attr('data-unblock') <= currentBlockId) {
					$(this).show();
				}
			});
		};
	window.currentBlockId = currentBlockId;
	
	$.fn.markAsRead = function() {
		
		var $target = $(this);
		
		$target.addClass('read');
		
		$target.find('.unblock').each(function() {
			
			if($(this).attr('data-unblock') > currentBlockId) {
				currentBlockId = $(this).attr('data-unblock');
			}
		});
		unblock();
	};
	
	$.fn
	
	
	var sectionTitle = '',
	
		sectionHref = '';
		
	$.fn.startReadSection = function() {
		
		
		var $section = $(this),
		
			$currentSection = $('section.active');
			
		console.log('document.body.scrollTop', document.body.scrollTop);
		
		$currentSection.data('scroll', document.body.scrollTop);
		
		sectionTitle = $section.find('h2').html();
		
		sectionHref = '#' + $section.attr('id');
		
		$header.find('h2').html(sectionTitle);
		
		$section.activate();
		
		document.body.scrollTop = $section.data('scroll') || 0;
	};
	
	$window.bind('hashchange', function(e) {
		
		var $target = $(location.hash),
		
			$parent = $('ol a[href="' + location.hash + '"]').closest('section');
		
		if(!$target.length) {
			$target = $('#toc');
		}
		if($target.length) {
			
			if(!sectionTitle) {
				var $parentTitle = $parent.find('h2');
				
				sectionTitle = $parentTitle.text();
				sectionHref = '#' + $parent.attr('id');
			}
			
			if(sectionTitle) {
				$header.find('a.back')
						.show()
						.text(sectionTitle)
						.attr('href', sectionHref);
			} else {
				$header.find('a.back').hide();
			}
			
			$target.startReadSection();
		} else {
			// alert('Page inexistante');
		}
	}).trigger('hashchange');
	
	
	
	if(!$('section').filterActive().length) {
		$('#toc').startReadSection();
	}
});
