var count = 0;
var rotationTimeout = 1500; // initial
var origScriptSrc = null;
var rotationTimer = null;

function doRandomPhotoRotation (id)
{
	var target = document.getElementById('randomPhoto1');
	if (!target) {
		return;
	}
	target.innerHTML = '<div style="height: 160px; font-size: 85%; color: #aaa;">loading photo...</div>';
	++count;

	var elem = document.getElementById(id);
	if (!elem) {
		return;
	}
	var scriptElemParent = elem.parentNode;
	if (!origScriptSrc) {
		origScriptSrc = elem.src;
	}
	scriptElemParent.removeChild(elem);

	var newScriptElem = document.createElement('script');
	newScriptElem.type = elem.type;
	newScriptElem.id = elem.id;
	newScriptElem.src = origScriptSrc + '&cnt=' + count;
	scriptElemParent.appendChild(newScriptElem);

	if (count >= 120) {
		return; // stop rotating
	}
	else if (count >= 100) {
		rotationTimeout = 60000;
	}
	else if (count >= 2) {
		rotationTimeout = 5200;
	}
	else if (count >= 1) {
		rotationTimeout = 2600;
	}
	rotationTimer = setTimeout("doRandomPhotoRotation('" + id + "')", rotationTimeout);
}

function clearRandomPhotoTimer ()
{
	if (rotationTimer) {
		clearTimeout(rotationTimer);
		rotationTimer = null;
	}
	if (window.removeEventListener) {
		window.removeEventListener('unload', clearRandomPhotoTimer, false);
	}
	else if (window.detachEvent) {
		window.detachEvent('unload', clearRandomPhotoTimer);
	}
}

function startRandomPhotoRotation (id)
{
	if (window.addEventListener) {
		window.addEventListener('unload', clearRandomPhotoTimer, false);
	}
	else if (window.attachEvent) {
		window.attachEvent('onunload', clearRandomPhotoTimer);
	}
	if (!rotationTimer) {
		rotationTimer = setTimeout("doRandomPhotoRotation('" + id + "')", rotationTimeout);
	}
}

