$(function() {
	
	var itemsPerSlide = 10;
	var $selectedItem = $('#overlaySelectorScrollArea a[href*="' + window.location.pathname + '"]');
	var $arrowRight = $('#overlaySelectorRight');
	var $arrowLeft = $('#overlaySelectorLeft');
	var currSlideIndex = parseInt(($selectedItem.index() + 1) / itemsPerSlide, 10);
	
	//set scroll area width
	var $scrollArea = $('#overlaySelectorScrollArea');
	$scrollArea.width($scrollArea.children().length * 70);
	
	//slide handling
	var goToSlide = function(index, initial) {
		
		var marginLeft = index * 700 * -1 + 'px';
		if(initial) {
			$scrollArea.css('margin-left', marginLeft);
			currSlideIndex = index;
		} else {
			$scrollArea.not(':animated').animate({
				'margin-left': marginLeft
			}, 500, 'swing', function() {
				currSlideIndex = index;
			});
		}
		
		//show or hide arrow left
		if(index == 0) {
			$arrowLeft.addClass('inactive');
		} else {
			$arrowLeft.removeClass('inactive');
		}

		//show or hide arrow right
		if(index == parseInt($scrollArea.children().length / itemsPerSlide, 10)) {
			$arrowRight.addClass('inactive');
		} else {
			$arrowRight.removeClass('inactive');
		}
		
	}
	
	//jump to the current slide with the selected item
	goToSlide(currSlideIndex, true);
	
	$arrowRight.click(function(ev) {
		ev.preventDefault();
		if(!$arrowRight.hasClass('inactive')) {
			goToSlide(currSlideIndex + 1);
		}
	});
	
	$arrowLeft.click(function(ev) {
		ev.preventDefault();
		if(!$arrowLeft.hasClass('inactive')) {
			goToSlide(currSlideIndex - 1);
		}
	});
	
	var hasHistoryManagementSupport = !!(window.history && history.pushState);
	if(hasHistoryManagementSupport) {
		
		$('#overlaySelectorScrollArea a').click(function(ev) {
			ev.preventDefault();
			var url = $(this).attr('href');
			$.ajax({
				url: url,
				dataType: 'html',
				success: function(res) {
					$('#overlay #contentWrapper').replaceWith($('#overlay #contentWrapper', res));
					window.history.pushState({}, null, url);
					changeLinkTargets();
				}
			});
		});
		
	}
	
});
