var GrandPublicScrollerRunning		= false;
var GrandPublicScrollerCurrentPos	= 0;

document.observe("dom:loaded", function() {
	$$('a.GrandPublicLeft').invoke('observe', 'click', observeGrandPublicScrollerScrollsBy);
	$$('a.GrandPublicRight').invoke('observe', 'click', observeGrandPublicScrollerScrollsBy);

	$$('a.GrandPublicScrollNav').invoke('observe', 'click', observeGrandPublicScrollerScrollNav);

});

function observeGrandPublicScrollerScrollsBy(event) {
	if (!GrandPublicScrollerRunning) {
		event.stop();
		element		= event.element();
		direction	= element.readAttribute('class');
		parentId	= element.readAttribute('rel');
		
		GrandPublicScrollerScroll(parentId, direction);
		
	}
	
}

function observeGrandPublicScrollerScrollNav(event) {
	event.stop();
	if (!GrandPublicScrollerRunning) {
		element	= event.element();
		position= element.readAttribute('rel');

		parts = position.split('_');

		position = parts[1];
		parentId = parts[0];

		if (position != GrandPublicScrollerCurrentPos) {
			if (position < GrandPublicScrollerCurrentPos) {
				direction = 'GrandPublicLeft';
				
			} else {
				direction = 'GrandPublicRight';
				
			}
			
			stepsCount = Math.abs(position - GrandPublicScrollerCurrentPos);
			GrandPublicScrollerScroll(parentId, direction, stepsCount);
			
		}
		
	}
	
}

function GrandPublicScrollerScroll(parentId, direction, stepsCount) {
	if (undefined == stepsCount) {
		stepsCount = 1;
		
	}
	
	childs = $$('#' + parentId + ' div.GrandPublicScrollerMooItem');
	maxStep = childs.length;
	
	if (0 < maxStep) {
		width = childs[0].getWidth();
		
		if ('GrandPublicRight' == direction) {
			if (GrandPublicScrollerCurrentPos+1 < maxStep) {
				GrandPublicScrollerCurrentPos = GrandPublicScrollerCurrentPos + (1 * stepsCount);
				
			} else {
				return;
				
			}
			
			step = -width * stepsCount;
			
		} else {
			if (GrandPublicScrollerCurrentPos-1 >= 0) {
				GrandPublicScrollerCurrentPos = GrandPublicScrollerCurrentPos - (1 * stepsCount);
				
			} else {
				return;
				
			}
			
			step = width * stepsCount;
			
		}
		
		new Effect.Move($(parentId), {
			'x'				: step, 
			'y'				: 0,
			'duration'		: 1,
			'mode'			: 'relative',
			'beforeStart'	: function() {GrandPublicScrollerRunning = true},
			'afterFinish'	: function() {
				GrandPublicScrollerRunning = false;
				refreshGrandPublicScrollerNavSelected();
			}
		});

	}
	
}

function refreshGrandPublicScrollerNavSelected() {
	$$('a.GrandPublicScrollNav').each(function (item) {
		position= item.readAttribute('rel');
		parts	= position.split('_');
		position= parts[1];
		
		if (
			(position == GrandPublicScrollerCurrentPos)
			&& (!item.hasClassName('selected'))
		) {
			item.addClassName('selected');
			
		} else if (
			(position != GrandPublicScrollerCurrentPos)
			&& (item.hasClassName('selected'))
		) {
			item.removeClassName('selected');
			
		}
	});

}
