//some settings
var reloadTime = 3000;	//the time between image rotation - in miliseconds   1sec = 1000mili


//a tracker of which image is currently displayed
var currentImg;

/**
 * 
 */
function hp_startCycle(){

	//the containing element
	var cycle_pool = $( 'cycle_pool' );
	var imgs = cycle_pool.childNodes;
	var totalImageCount = imgs.length;

	//pick a staring point
	//
	// (Math.random * maxnumber) + minimum number
	//
	//  our max number has -1 because array indexes start with 0 not 1,
	//  and our minimum os 0 because thats where the array starts
	//
	var startid = Math.floor( Math.random() * (totalImageCount - 1) ) + 0;
	//console.log( "starting point", hp_currentIndex, children [ hp_currentImage ] );

	//set the current index to the one we chose to start with
	currentImg = imgs[ startid ];
	
	//show the randomly picked item first	
	hp_rotateImage();
	
	//start the timer - rotateImage will take it from here - once every ... seconds
	setInterval( hp_rotateImage, reloadTime );
	
}

/**
 * 
 */
function hp_rotateImage(){
	
	var firstItem = currentImg;
	
	hide( currentImg );
	
	//run this portion of code until we find a suitable element
	do {
		
		//if we're pastthe end go back to the beginning
		if (currentImg == currentImg.parentNode.lastChild) {
			currentImg = currentImg.parentNode.firstChild;
		} else {
			//increment to the next child
			currentImg = currentImg.nextSibling;
		}
		
	} while ( !isElement( currentImg ) && currentImg != firstItem );

	//show the new item
	show( currentImg );
}


/**
 * Get an HTML DOM Element by ID
 * @param {Object} elementName
 */		
 function $ ( elementName ){
 	var undefined;
	
	if ( document.getElementById != undefined ) {
		return document.getElementById(elementName);
	} else {
		if ( document.all != undefined ) {
			return document.all[elementName]; 
		} else if ( document.layers != undefined ) {
			return document.layers[elementName];
		}
	}
}

/**
 * Show an element in the document
 * @param {Object} element
 */
function show( element ){
	try {
		element.style.display = 'block';
		element.style.visibility = 'visible';
	} catch( ex ){
		return false;
	}	
	return true;
}

/**
 * Hide a SINGLE element
 * @param {Object} element
 */
function hide( element ){
	try {
		element.style.display = 'none';
		element.style.visibility = 'hidden';
	} catch ( ex ) {
		return false;
	}
	return true;
}
			
function isObject(o){
	return (o instanceof Array) ? false : (o !== null) && (typeof(o) == 'object');
}	

function isElement(o){
	//console.log( o, o.nodeType  );
	return ( o.nodeType == 1);
}

window.onload = hp_startCycle;