// global variables
var _rollover_supported = false;
var _rollovers, _rollovers_idx;
var _rollover_cache_clock = -1;

/// Initialize everything needed before using rollovers
function _InitializeRollovers() {
	if(!document.images) return;
	_rollover_supported = true;
	_rollovers = new Array();
	_rollovers_idx = new Object();
}
_InitializeRollovers();
 
/// Rollover constructor (create a Rollover object)
function Rollover(imgname, states) {
	this.is_ready = false;
	this.is_willing = true;
	if((_rollover_supported==false)||(imgname==null)||(states==null)) {
		this.is_willing=false;	return;
	}
 	this.imgname = imgname;
	this.states = states.split(",");
	this.img = new Array();
	var i = _rollovers.length;
	_rollovers[i] = this;
	_rollovers_idx[imgname] = i;
	_RolloverScheduleCaching();
}
new Rollover();

/// Initialize a specific rollover, return true if initialize completed
function _Rollover_initialize() {
	if(_rollover_supported==false)		return false;
	this.image = document.images[this.imgname];
	if((!this.image)||(!this.image.src))	return false;
	var imgsrc = this.image.src;
	var i, w = this.image.width, h = this.image.height;
	var prefixend = imgsrc.lastIndexOf(this.states[0]);
	if (prefixend == -1) {
		this.is_willing = false;	return false;
	}
	var suffixstart = prefixend + this.states[0].length;
	this.prefix = imgsrc.substring(0, prefixend);
	this.suffix = imgsrc.substring(suffixstart, imgsrc.length);

	// precache defined rollover states:
	for(i=0; i<this.states.length; i++) {
		this.img[i] = new Image(w, h);
		this.img[i].src = this.prefix + this.states[i] + this.suffix;
	}
	this.is_ready = true;
	return true;
}
Rollover.prototype.initialize = _Rollover_initialize;

/// Set the rollover image, given the state name
function _Rollover_rollover(state) {
	if(this.is_ready)		this.image.src = this.prefix + state + this.suffix;
	else if(this.is_willing)	this.initialize();
}
Rollover.prototype.rollover = _Rollover_rollover;

/// Schedule precaching
function _RolloverScheduleCaching() {
	if(_rollover_cache_clock >= 0)
		clearTimeout(_rollover_cache_clock);
	_rollover_cache_clock = setTimeout("_RolloverCacheImages();", 2000);	
}

/// Cache all the rollover images used in this page.
function _RolloverCacheImages() {
	var i, r, tryagain=0;
	if(_rollover_supported==false) return;
	_rollover_cache_clock = -1;
	for(i=0; i<_rollovers.length; i++) {
		r = _rollovers[i];
		if((!r.is_ready)&&(r.is_willing))
			if((r.initialize()==false)&&(r.is_willing))
				tryagain++;
	}
	if(tryagain > 0)	_RolloverScheduleCaching();
}

/// create a rollover for future use, required to use rollovers.
function CreateRollover(imgname, states) {
	new Rollover(imgname, states);
}

/// set a rollover to a given state (likely called by onmouse* events)
function rollover(imgname, state) {
	var rollidx = _rollovers_idx[imgname];
	_rollovers[rollidx].rollover(state);
	return true;
}



