

var imgNames = new Array();//store of img names
var newImg = new Array();//store of replacement img objects
var origSrc = new Array();//store of original img paths
var on = null,loaded = false;//'on' and 'loaded' state flags
var done = false;

//Iterates through document's images array and stores/creates images for later use
//	takes an optional parameter 'ref' to enable an image to be toggled() 'on' at page load
function preload(ref){
	if(!ref){
		ref = null;
	}
	for(i = 0;i < document.images.length;i++){
		img = document.images[i];	//Assigns current image to variable img
		if(img.src.substring(img.src.lastIndexOf('.')-4,img.src.lastIndexOf('.')) == '_off'){
			imgNames[i] = img.name;
			origSrc[i] = img.src;	//Stores image location in origSrc array
			newImg[i] = new Image();	//Creates new image in newImg array
			newImg[i].src = img.src.substring(0,img.src.lastIndexOf('.')-3) + 'on' + img.src.substring(img.src.lastIndexOf('.'));	//Constructs the path for the newImg image preserving img src extension
		}
	}
	loaded = true;
	if(ref != null){
		toggle(ref)
	}
	done = true;
}

//Toggles image for clicked link and sets flag variable on to link's image
function toggle(ref){
	num = refToNum(ref);
	img = document.images[ref];
	if(on != null){
                if(on == num){
                        img.src = newImg[num].src;
                        on = null;
                        return
                }else{
		        document.images[on].src = origSrc[on];
		        img.src = newImg[num].src;	//Set clicked image within clicked link to new image source
               }
	}else{
		img.src = newImg[num].src;	//Set clicked image within clicked link to new image source
        }
        on = num
}

//Changes image of link below mouse cursor
function hilight(ref){
	if( done ){
		num = refToNum(ref);
		if(loaded && num != on){
			img = document.images[ref];
			img.src = newImg[num].src				//Set link's image to new source
		}
	}
}

//Reverts link's image when link loses focus
function lolight(ref){
	if( done ){
		num = refToNum(ref);
		if(loaded && num != on){
			img = document.images[ref];
			img.src = origSrc[num]	//Set link's image to original source
		}
	}	
}


//Checks if ref is numeric and retrieves the numeric index of image with Id = ref if it is not
function refToNum(ref){
	if(isNaN(ref)){//If 'ref' is not numeric
		for(i=0;i<imgNames.length;i++){//For each id in imgNames array
			if(ref == imgNames[i]){
				num = i;
				break
			}
		}
	}else{
		num = parseInt(ref, 10)
	}
	return num
}
