window.addEvent('domready', function() {
	$$('.horizscrollarea').each(function(area, n){

		var length = area.getElements('.section').length;
		area.getElement('div').setStyle('width', length * 675);
		area.store('length', length);

		// FOR ALL SECTIONS IN AREA's
		area.getElements('.section').each(function(section, i){
			var sectionImg = section.getElement('img');
			section.store('no', i);
		});

		// PRELOAD FIRST SECTION OF AREA's
		preloadImg(area.getElement('.section:nth-child(1)'));

		// LOAD FIRST AREA
		if(n==0) {
			currentArea = area;
			currentArea.length = area.retrieve('length');

			currentSection = area.getElement('.section:nth-child(1)');
			preloadImg(area.getElement('.section:nth-child(2)'));
		}
	});

	updateScrollPos();
	fxScrollSection = new Fx.Scroll(currentArea, {wheelStops:false, link:'chain', duration: 750});
	fxScrollSection.set(0,0);
	fxScrollArea = new Fx.Scroll('vertscrollarea', {wheelStops:false, link:'ignore'});
	fxScrollArea.set(0,0);
	
	currentLink = $('menuTop').getElement('a.active');
});



var fxScrollSection;
var fxScrollArea;

var currentArea;
var currentLink;
var currentSection;
var imgDir = 'index-images/';



function preloadImg(section){
	var sectionImg = section.getElement('img');
	section.setStyle('background', 'none');
	// IF HAS IMAGE, PRELOAD
	if(sectionImg != null) {
		sectionImg.setProperty('src', imgDir + sectionImg.getProperty('alt'));
		if(sectionImg.getProperty('height') != null)
			sectionImg.setStyle('margin-top', (450-sectionImg.getProperty('height'))/2);
	}
}



function updateScrollPos(){
	$('scrollPos').set('text', currentSection.retrieve('no')+1 + ' / ' + currentArea.retrieve('length'));
}




// problem when first => last (goes past unPreloaded IMG's)
function prev(){
	if(currentSection.getPrevious('.section')==null)
		return;
	currentSection = currentSection.getPrevious('.section');

	fxScrollSection.toElement(currentSection);
	updateScrollPos();
	// PRELOAD PREVIOUS != NULL
	if(currentSection.getPrevious('.section') != null)
		preloadImg(currentSection.getPrevious('.section'));
}

function next(){
	currentSection = (currentSection.getNext('.section')!=null) ? currentSection.getNext('.section') : currentSection.getParent().getFirst('.section');
	fxScrollSection.toElement(currentSection);
	updateScrollPos();
	// PRELOAD NEXT != NULL
	if(currentSection.getNext('.section') != null)
		preloadImg(currentSection.getNext('.section'));
}



function toArea(i, link){
	currentArea = fxScrollSection.element = $('vertscrollarea').getElement('.horizscrollarea:nth-child(' + i + ')');

	fxScrollArea.toElement(currentArea);

	currentLink.setProperty('class', 'inactive');
	$(link).setProperty('class', 'active');
	currentLink = $(link);

	currentSection = currentArea.getElement('.section:nth-child(1)');
	fxScrollSection.toElement(currentSection);

	updateScrollPos();

	preloadImg(currentArea.getElement('.section:nth-child(2)')); // does not always exist

}