// ********************************
// Any html page using this file must define
// a FORM named picForm, containing an IMG named picCam
// Call StartRefresh(sPath, nRate) with the URL of the image and the refresh rate (in seconds)
// ********************************

// Input parms
var m_nRefreshRate
var m_sImagePath

// Global variables
var m_nDummyCount
var m_nNextRefreshTime
var m_picImages
var m_iImageNum
var m_bRefreshingPic
var m_bStalling

function RefreshPic()
{
  // Time's up, show another picture
  var now = new Date()
  m_nNextRefreshTime = now.getTime() + (m_nRefreshRate * 1000)
  
  // Must add fake dummy argument, to trick browser cache into getting a new image
  // otherwise, Netscape will just keep displaying the same cached image
  // If your CGI (fullsize.jpg) takes input parameters, ignore this "x" parameter, it just counts up starting with a random value
  var sExtra
  if (m_sImagePath.indexOf("?") >= 0) sExtra = "&"
  else sExtra = "?"
  var sImageURL = m_sImagePath + sExtra + "x=" + m_nDummyCount++ 
  
  // use double-buffering, so white background won't show through while new image loads
  m_iImageNum = 1 - m_iImageNum
  m_picImages[m_iImageNum] = new Image()
  m_picImages[m_iImageNum].src = sImageURL
  m_bRefreshingPic = true
  m_bStalling = false
  // Since images stored in variables can not trigger an onLoad event,
  // we must use a timer to constantly check if the new image is .complete
}

function HandleTimer()
{
  // check to see if we are stalling before next image
  if (m_bStalling)
  {
    var now = new Date()
    if (now.getTime() >= m_nNextRefreshTime) RefreshPic()
    return
  }

  // check to see if an image has been retrieved
  if (!m_bRefreshingPic) return  // see if I am waiting for an image
  if (!m_picImages[m_iImageNum].complete) return // see if image is done loading yet
  
  // good, show it & start stalling for next image
  document.picForm.picCam.src = m_picImages[m_iImageNum].src

  m_bStalling = true
}

// *** Set this m_nRefreshRate to the rate (in seconds) at which the browser will poll for a new image ***
// Program will not attempt to grab images more than once in this many seconds
function StartRefresh(sPath, nRate)
{
  m_sImagePath = sPath // used by RefreshPic
  m_nRefreshRate = nRate
  
  m_picImages = new Array(2)
  m_picImages[0] = new Image()
  m_picImages[1] = new Image()
  m_iImageNum = 0
  m_bRefreshingPic = false
  m_bStalling = false
  
  var now = new Date()
  m_nDummyCount = now.getTime() % 86400 //no need for that many digits, limit "extra parm" to 24 hours

  RefreshPic()
  
  setInterval("HandleTimer()", 50) // call timer function as fast as possible (50 msec)
}
