////////////
// recently viewed
////////////

$(function() {

	var footer = $('#recentlyViewedFooter'), back = footer.find('.back'), forward = footer.find('.forward'),
	views = footer.find('ul'), width = footer.find('.listWrapper').width(),
	leftMost = [{
		jq: views.find('li:first-child'),
		left: 0
	}];

	if (footer.length <1) {
		return;
	}

	function backClick() {
		if(leftMost.length > 1 && !views.is(':animated')) {
			leftMost.pop();
			slide(leftMost[leftMost.length - 1].left);
		}
		return false;
	}

	function forwardClick() {
		var next;
		if(!views.is(':animated') && (next = findNextLeft())) {
			leftMost.push(next);
			slide(next.left);
		}
		return false;
	}

	function findNextLeft() {
		var last = leftMost[leftMost.length - 1], end = last.jq, left = last.left;
		while(end.length && (end.position().left + end.width() - left) < width) {
			end = end.next();
		}
		return !end.length ? null : {
			jq: end,
			left: end.position().left
		};
	}

	function enableArrows() {
		back.setVisible(leftMost.length > 1);
		forward.setVisible(findNextLeft() != null);
	}

	function slide(left) {
		enableArrows();
		views.animate({
			left: -left + 'px'
		}, 'fast');
	}

	back.click(backClick);
	forward.click(forwardClick);
	enableArrows();
	footer.find('.scrollRecently').removeClass('scrollRecently');
	footer.find('.recentView').click(function() {
		pageTracker._trackEvent('Recently Viewed', $(this).find('h6 a').html(), $(this).find('a').attr('href'));
		window.document.location = $(this).find('a').attr('href');
		return false;
	});
});