﻿var adIntervalId = 0;
	
var showNextAd = function() {
	var curAd = $$(".currentAd")[0];
	
	// Find the next ad
	var nextAd;
	if(curAd.getNext())
		nextAd = curAd.getNext();
	else
		nextAd = curAd.getParent().getFirst();
	
	// Hide the currently showing ad
	curAd.set('class', 'mainAd');
	curAd.tween('opacity', 0);
	
	// Show the next ad
	nextAd.set('class', 'currentAd');
	nextAd.tween('opacity', 1);
	
}

var showPrevAd = function() {
	var curAd = $$(".currentAd")[0];
	
	// Find the previous ad
	var prevAd;
	if(curAd.getPrevious())
		prevAd = curAd.getPrevious();
	else
		prevAd = curAd.getParent().getLast();
	
	// Hide the currently showing ad
	curAd.set('class', 'mainAd');
	curAd.tween('opacity', 0);
	
	// Show the previous ad
	prevAd.set('class', 'currentAd');
	prevAd.tween('opacity', 1);
	
}

function resetAdInterval() {
	if(adIntervalId != 0) {
		$clear(adIntervalId);
	}
	adIntervalId = showNextAd.periodical(10000);
}

window.addEvent('domready', function() {
	
	var imgs = $$(".mainAd");
	
	imgs.set('visibility', 'visible');
	
	// Setup the first ad and make sure that it is showing
	imgs[0].set('class', 'currentAd');
	imgs[0].setStyle('opacity', 1);
	
	// Make sure that all of the other ads are not showing
	for(var i=1; i<imgs.length; i++)
		imgs[i].setStyle('opacity', 0);
	
	// Setup the tweens
	imgs.set('tween', {duration: 'long'});
	
	// Show another ad every 10 seconds
	resetAdInterval();
	
	$('nextAd').addEvent('click', function() {
		resetAdInterval();
		showNextAd();
	});
	$('prevAd').addEvent('click', function() {
		resetAdInterval();
		showPrevAd();
	});
});
