//* Random Speakers
//*
//* A small JavaScript library that can be used to randomly
//* select a number of pictures from a pool, and display them
//* on a web page along with a caption and a link.
//*
//* It is very important that the three arrays "PicturePaths",
//* "PictureCaptions" and "PictureLinks" be *EXACTLY* the same
//* size.

// The arrays for the pictures, captions and links.
var PicturePaths = new Array();
var Pictures = new Array();
var PictureCaptions = new Array();
var PictureLinks = new Array();

// The number of times the loadImage function has been called
var imageLoaded=0;

// An array to keep track of which Pictures have already been chosen.
// This is used to ensure that the same image is not displayed more than
// once on the same page.
var selectedPictures = new Array();

// Loop over the array of picture paths, and initialize
// an array of actual Javascript Images.
function preloadPictures() {
  if (PicturePaths.length>=1) {
    for (i=0;i<PicturePaths.length;i++){
      Pictures[i] = new Image();
      Pictures[i].src = PicturePaths[i];
    }
  } else {
    alert("Error: No pictures have been defined!");
  }
}

// Return a number between 0 and the size of the PicturePaths array
function getRandomPictureID() {
  var tmpid=-1;
  tmpid = Math.round(Math.random()*(PicturePaths.length-1));
  while(tmpid>=PicturePaths.length) { tmpid = Math.round(Math.random()*(PicturePaths.length-1)); }
  return(tmpid);
}

// Get a new, randomly selected picture id which represents it's position
// in the Pictures array.  Ensure that it has not already been selected for
// this page, and then mark it as selected.
function getNewPictureID() {
  var tmpid=-1;
  if (imageLoaded != PicturePaths.length) {
    tmpid = getRandomPictureID();
    while(selectedPictures[tmpid]==1) { tmpid = getRandomPictureID(); }
    selectedPictures[tmpid]=1;
    imageLoaded++;
  }
  return(tmpid);
}

// Load all the images from 1 to numImages
function loadImages(numImages) {
	var picid=-1;

	for (i=1; i<=numImages; i++) {
  	picid=getNewPictureID();

  	if (picid!=-1 && Pictures[picid]) {
    	document.images["Picture" + i].src=Pictures[picid].src;

	    if (document.getElementById) {
	    	if (document.getElementById("Caption" + i))
					document.getElementById("Caption" + i).innerHTML=PictureCaptions[picid];
	    	if (document.getElementById("Link" + i))
				document.getElementById("Link" + i).href=PictureLinks[picid];
			}
		}
	}
}
