//Set cookie function, see my article on cookie functions
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}
// Retreive cookie value function
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}
// this function is used to go through the array of previously
// seen numbers
// and if there is a match, a new random number is chosen
function checkRandomNum(base, array){
	num = Math.ceil(Math.random()*base)
	for(var i=0; i <array.length; i++){
		if(Number(array[i])==num){
			checkRandomNum(base, array)
		}
		
	}
	return(num)
}

function randomNumber(){
	num = 8 //total number of images
	casheLimit=3 //how many to keep in memory if you use 
        //same number as num, 
	//you will get the same sequence over and over again.  
	if(getCookie("randomCookie")){
		cookie_array = getCookie("randomCookie")
		cookie_array = cookie_array.split("|")
		if(cookie_array.length>=casheLimit){
			cookie_array.shift()
		}
		randomNum = checkRandomNum(num, cookie_array)
		
	}else{
		randomNum = Math.ceil(Math.random()*num)
		cookie_array = Array()
	}
	cookie_array.push(randomNum)
	cookiestring=""
	for(var i=0; i <cookie_array.length; i++){
		cookiestring +=cookie_array[i]
		if(i <cookie_array.length-1){
			cookiestring +="|"
		}
	}
	setCookie("randomCookie", cookiestring)
	//This is where you would use the number to output a random image. 
	 //In this case, I have 8 images named 1.jpg, 2.jpg...
	
	str = 'url(images/masthead_image'+randomNum+'.jpg) #CCC';
	return str;
}
document.getElementById('masthead').style.background=randomNumber();
