// This JavaScript file is used on the International Students homepage to display random student profile thumbnails.
// The thumbnails are rendered onto the page and then displayed randomly using JavaScript
// The number of thumbnails to display is determined by a hidden div in the page with the id numberToShow

// Use JQuery to determine whether the DOM is ready
$(document).ready(function(){init()});


// This function determines whether an array (theArray) contains a given item (theItem). It returns a boolean.
function arrayContains(theArray, theItem){
  var contains = false;
  for(var i=0; i<theArray.length; i++){
    if(theArray[i] == theItem) contains = true;
	}
  return contains;
  }
  
// This is a random number generator function
function randomNumber(limit){
  return Math.floor(Math.random()*limit);
  }


// Find the profiles, put them into an array, hide them, then select the number contained in numberToShow at random and display them
// Use arrayContains to ensure that we don't show the same profile twice
function init(){
  var profiles, randnum, numberToShow;
  profiles = new Array();
  var displayProfiles = new Array();
  var divs = document.getElementsByTagName('div');
  
  // Get the profiles into an array and hide them
  for(var i=0; i<divs.length; i++){
    if(divs[i].className == 'profile'){
	  divs[i].style.display = 'none';
	  profiles.push(divs[i]);
	  }
	}	
	
  // Determine how many profiles to show
  // Typically this will be set by the value of a div in the page called numberToShow
  // If this div is absent, take the total number of profiles, divide by two and round up.
  if(document.getElementById('numberToShow'))numberToShow = document.getElementById('numberToShow').innerHTML;
  else numberToShow = Math.round(profiles.length/2);
  if(numberToShow > profiles.length)numberToShow = profiles.length;
	
  // Randomly select profiles to show, checking to ensure that we're not already showing them	
  do{
    randnum = randomNumber(profiles.length);    
	if(!arrayContains(displayProfiles, profiles[randnum])){
	  displayProfiles.push(profiles[randnum])
	  }
	}
	while (displayProfiles.length < numberToShow);	
	for(var j=0; j<displayProfiles.length; j++){
	  displayProfiles[j].style.display = 'block';
	  }	  
  }
  

