
$.fn.scrollable = function() { 
    
    var pageHeadline = $('h1').first();
    var scrollableContent = this.find('.scrollable-content');
    var scrolledItems = this.find('.scrolled-item');
	var previousAnchor = this.find('a[rel=previous-page]');
	var nextAnchor = this.find('a[rel=next-page]');
	var navigationAnchors = this.find('a[rel=navigation]');
    var itemWidth = parseInt(this.css('width')) || 0;
    var position = 0;
    var animationSpeed = 750;
    var allowAnimation = true;
    
    var updateState = function(change) {
    	
    	position += change;
    	
    	var selectedItem = $(scrolledItems.get(position));
		var selectedItemData = selectedItem.find('a[rel=scrolled-item]');
		var selectedItemURL = selectedItemData.attr('name').replace(/^-/, '#') || '#';
    	
		allowAnimation = false;
		scrollableContent.animate({ left: -position * itemWidth }, animationSpeed, 'easeInOutExpo', function() {
			scrollableContent.css('left', -position * itemWidth);
			allowAnimation = true;
		});
		
		pageHeadline.hide();
		pageHeadline.text(selectedItemData.attr('title'));
		pageHeadline.show('drop', { direction: change < 0 ? 'left' : 'right' }, animationSpeed);
		
		var previousItemData = selectedItem.prev().find('a[rel=scrolled-item]');
		previousAnchor.toggleClass('navigation-previous-page-disabled', !previousItemData.length);
		previousAnchor.attr('href', (previousItemData.attr('name') || '').replace(/^-/, '#'));
		previousAnchor.attr('title', previousItemData.attr('title'));
		
		var nextItemData = selectedItem.next().find('a[rel=scrolled-item]');
		nextAnchor.toggleClass('navigation-next-page-disabled', !nextItemData.length);
		nextAnchor.attr('href', (nextItemData.attr('name') || '').replace(/^-/, '#'));
		nextAnchor.attr('title', nextItemData.attr('title'));
		
		navigationAnchors
			.removeClass('selected')
			.filter('[href="' + selectedItemURL + '"]').addClass('selected')
		
		document.location = selectedItemURL;
	};
    
    previousAnchor.click(function() {
    	if (!allowAnimation || $(this).hasClass('navigation-previous-page-disabled'))
    		return false;
    	updateState(-1);
		return false;
	});
	
	nextAnchor.click(function() {
		if (!allowAnimation || $(this).hasClass('navigation-next-page-disabled'))
    		return false;
		updateState(+1);
		return false;
	});
	
	navigationAnchors.each(function(index) {
		$(this)
			.attr('href', this.href.toString().replace(/^.*\/([a-zA-Z0-9\-\._]+)$/, '#$1'))
			.click(function() {
				if (!allowAnimation || $(this).hasClass('selected'))
    				return false;
    			updateState(index - position);
    			return false;
			})
	});
	
	var anchorMatch = document.location.toString().match(/#([a-zA-Z0-9\-\._]+)$/);
    if (anchorMatch)
    	position = this.find('a[rel=scrolled-item]').filter('[name="-' + anchorMatch[1].toString() + '"]').closest('.scrolled-item').prevAll().length;
	
	updateState(0);
}

