
var scrollPosition = 0;
var scrollWindowSize = 4;
var layerCount = 1;
var offsetLeft = 0;
var elementCount = null;
var scrollLength = 120;
var scrollWidth = null;
var totalScrollWidth = null;
var scrollInterval = 3000;
var interval = null;
var enableScroll = true;
var visibleItems = null;

function doScrollLeft() {
	if (!enableScroll) return false;

	enableScroll = false;
	if (scrollPosition == 0 && $(visibleItems).prev().length == 0) {
		totalScrollWidth += scrollWidth;
		$('.scroll-pane').css('width', totalScrollWidth + 'px');
		$('.scroll-pane').prepend($('.scroll-items:eq(0)').clone().attr('id', 'items-' + layerCount++));
		offsetLeft -= scrollWidth;
		$('.scroll-pane').css('left', offsetLeft + 'px');
		if ($('.scroll-items').length > 2) {
			$('.scroll-items:last').remove();
			totalScrollWidth -= scrollWidth;
			$('.scroll-pane').css('width', totalScrollWidth + 'px');
		}
	}

	if (scrollPosition == 0) {
		scrollPosition = elementCount - 1;
		visibleItems = $(visibleItems).prev().get(0);
	} else {
		scrollPosition--;
	}

	offsetLeft += scrollLength;
	$('.scroll-pane').animate({'left' : '+=' + scrollLength + 'px'}, scrollLength * 3, 'linear', function () {
		enableScroll = true;
	});
	return true;
}

function doScrollRight() {
	if (!enableScroll) return false;

	enableScroll = false;
	if (scrollPosition == elementCount - scrollWindowSize && $(visibleItems).next().length == 0) {
		totalScrollWidth += scrollWidth;
		$('.scroll-pane').css('width', totalScrollWidth + 'px');
		$('.scroll-pane').append($('.scroll-items:eq(0)').clone().attr('id', 'items-' + layerCount++));
		if ($('.scroll-items').length > 2) {
			$('.scroll-items:first').remove();
			totalScrollWidth -= scrollWidth;
			$('.scroll-pane').css('width', totalScrollWidth + 'px');
			offsetLeft += scrollWidth;
			$('.scroll-pane').css('left', offsetLeft + 'px');
		}
	}

	if (scrollPosition == elementCount - 1) {
		scrollPosition = 0;
		visibleItems = $(visibleItems).next().get(0);
	} else {
		scrollPosition++;
	}

	offsetLeft -= scrollLength;
	$('.scroll-pane').animate({'left' : '-=' + scrollLength + 'px'}, scrollLength * 3, 'linear', function () {
		enableScroll = true;
	});
	return true;
}

function initOffersScroller() {
	$(document).bind('ready', function () {
		elementCount = $('.scroll-pane .offer').length;
		scrollWidth = elementCount * 120;
		totalScrollWidth = scrollWidth;
		$('.scroll-pane').css('width', scrollWidth + 'px');
		$('.scroll-items').css('width', totalScrollWidth + 'px');
		visibleItems = $('.scroll-items').get(0);
		$('#offers-scroll-left').click(function () {
			clearInterval(interval);
			doScrollLeft();
		});
		$('#offers-scroll-right').click(function () {
			clearInterval(interval);
			doScrollRight();
		});
		interval = setInterval(doScrollRight, scrollInterval);
	});
}