// config vars: edit me.
var xmlpath = '/portal/xml/banners.xml';
var portalspeed = 6 * 1000;
var portalspdx = 0.9;

// vars: don't edit me.
var xlist;
var portalrun = 1;
var portalindex = 0;
var portaldebug = 1;
var lastrotate = rightnow() - portalspeed;

function rotatepic(delay) {
	if (!portalrun) {
		//alert('I was asked to rotate the pic, but portalrun was set to 0.');
		return;
	}
	var rn = rightnow();
	if ( delay == 1 && (rn - lastrotate) < (portalspeed - 99) ) {
		//window.status = 'Delay not yet reached (' + (rn-lastrotate) + ' < '+portalspeed+').';
		return;
	}
	
	// This is the 'do it' section //
	var theimgsrc	= xlist[portalindex].getElementsByTagName('imgsrc')[0].childNodes[0].nodeValue;
	var thetitle	= xlist[portalindex].getElementsByTagName('title')[0].childNodes[0].nodeValue;
	var thetext		= xlist[portalindex].getElementsByTagName('text')[0].childNodes[0].nodeValue;
	var thelink		= xlist[portalindex].getElementsByTagName('link')[0].childNodes[0].nodeValue;
	$('portalimg').setAttribute('src', theimgsrc);
	$('portaltext').innerHTML = thetext;
	$('portaltitle').innerHTML = thetitle;
	$('portallink').setAttribute('href', thelink);
	// This is the END of the 'do it' section //
	
	lastrotate = rightnow();
	indexchange(1);
}

function rewindpic() {
	if (portalrun) {
		indexchange(-2);
		rotatepic(0);
	} else {
		portalrun = 1;
		lastrotate = rightnow(); // avoids an extremely unlikely race condition
		indexchange(-2);
		rotatepic(0);
		portalrun = 0;
	}
}

function ffwdpic() {
	if (portalrun) {
		rotatepic(0);
	} else {
		portalrun = 1;
		lastrotate = rightnow(); // avoids an extremely unlikely race condition
		rotatepic(0);
		portalrun = 0;
	}
}

function pausepic() {
	portalrun = 0;
}

function playpic() {
	portalrun = 1;
}

function initrotatepic() {
	var xmlDoc;
	if (window.XMLHttpRequest) {// code for all new browsers
		xmlDoc = new XMLHttpRequest();
	} else if (window.ActiveXObject) {// code for IE5 and IE6
		xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlDoc.open('GET', xmlpath, false);
	xmlDoc.send(null);
	xlist = xmlDoc.responseXML.getElementsByTagName('NewsItem');
	setInterval('rotatepic(1)', 500); // let the fn itself check if time has gone by.
	$('portalbuttons').style.visibility = 'visible';
}

function indexchange(inc) {
	portalindex += inc;
	var sanity = 0;
	if ( portalindex < 0 ) {
		while ( portalindex < 0 ) {
			if (sanity > 50) break;
			portalindex += xlist.length;
			sanity++;
		}
	} else {
		while ( portalindex > (xlist.length-1) ) {
			if (sanity > 50) break;
			portalindex -= xlist.length;
			sanity++;
		}
	}
	return portalindex;
}

function rightnow() {
	return parseInt((new Date).getTime() / 1);
}

function $(id) {
	return document.getElementById(id);
}