// ***************
// Rotating Teaser
// ***************

function RotatingTeaser(data, interfaceId) {

	this.view = document.getElementById(interfaceId);

	this.teasers = new Array();
	this.curIndex = -1;
	this.weights = data.split(',');
	this.cumWeights = 0;

	this.init();

	this.curIndex = this.random();
	this.draw();
}

RotatingTeaser.prototype.init = function() {

	var tags = this.view.getElementsByTagName('div');

	// find freeteaser modules in HTML and ensure
	// that only one of them is currently visible

	for ( var i = 0; i < tags.length; i++) {
		if (tags[i].className.toLowerCase().indexOf('aon_modul') >= 0) {
			this.teasers.push(tags[i]);
			if (tags[i].style.display == 'block') {
				if (this.curIndex >= 0) {
					this.teasers[this.curIndex].style.display = 'none';
				}
				this.curIndex = this.teasers.length - 1;
			}
		}
	}

	// accumulate the weights for later random teaser calculation

	for ( var i = 0; i < this.weights.length; i++) {
		this.cumWeights += 1 * this.weights[i];
	}
}

RotatingTeaser.prototype.random = function() {

	var newIndex = 0;
	var lowerMargin = 0;
	var rnd = Math.random() * this.cumWeights;

	// calculate a random teaser index depending on the overall teaser weights

	for ( var i = 0; i < this.weights.length; i++) {
		if (lowerMargin <= rnd && lowerMargin + 1 * this.weights[i] > rnd) {
			newIndex = i;
			break;
		} else {
			lowerMargin += 1 * this.weights[i];
		}
	}

	return newIndex;
}

RotatingTeaser.prototype.draw = function() {

	var oldIndex = -1;

	for ( var i = 0; i < this.teasers.length; i++) {
		if (this.teasers[i].style.display == 'block') {
			oldIndex = i;
		}
	}

	if (oldIndex != this.curIndex) {
		if (oldIndex != -1) {
			this.teasers[oldIndex].style.display = 'none';
		}
		this.teasers[this.curIndex].style.display = 'block';
	}
}
