/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @link www.scorpix.ru
 * @requires jQuer
 * @requires jTweener
 */

$(function() {

	function scheduleScroll(rootEl) {
		rootEl = $(rootEl);

		var
			lineEl = rootEl.find('.line'),
			overflowEl = rootEl.find('.names'),
			containerEl = rootEl.find('.container'),
			leftArrowEl = rootEl.find('.left_border .arrow'),
			rightArrowEl = rootEl.find('.right_border .arrow');

		leftArrowEl.click(function() {
			animate(true);
		});

		rightArrowEl.click(function() {
			animate(false);
		});

		$(window).resize(update);
		update();

		function animate(toLeft) {

			jTweener.removeTween(containerEl);

			var
				lineWidth = lineEl.outerWidth(),
				containerWidth = containerEl.width(),
				width = containerWidth - overflowEl.width(),
				curLeft = parseInt(containerEl.css('left')),
				left = curLeft + (toLeft ? Math.round(width / 2) : -Math.round(width / 2));

			if (left < width - lineWidth) {
				left = width - lineWidth;
			}
			if (0 < left) {
				left = 0;
			}

			if (0 == left) {
				leftArrowEl.addClass('hidden');
			} else {
				leftArrowEl.removeClass('hidden');
			}

			if (left <= width - lineWidth) {
				rightArrowEl.addClass('hidden');
			} else {
				rightArrowEl.removeClass('hidden');
			}

			$t(containerEl, {
				left: left,
				time: 0.5
			}).tween();
		}

		function update() {
			var
				lineWidth = lineEl.outerWidth(),
				containerWidth = containerEl.width(),
				width = containerWidth - overflowEl.width(),
				curLeft = parseInt(containerEl.css('left')),
				left = curLeft;

			if (left < width - lineWidth) {
				left = width - lineWidth;
			}
			if (0 < left) {
				left = 0;
			}

			if (0 == left) {
				leftArrowEl.addClass('hidden');
			} else {
				leftArrowEl.removeClass('hidden');
			}

			if (left <= width - lineWidth) {
				rightArrowEl.addClass('hidden');
			} else {
				rightArrowEl.removeClass('hidden');
			}

			if (curLeft != left) {
				containerEl.css('left', left);
			}
		}
	}

	scheduleScroll('#content .schedule');
});
