// (C) 2000-2006, Clinton R. Johnson (xepol@xepol.com)
//
// WebCam Script V1.01
//
// Purpose -> To display webcam images at any desired rate.
//
// You may NOT reuse this script in whole, or in part, without 
// written permission of the author.
//

var verText=navigator.appVersion;
var Version=parseFloat(verText);
var isOpera=(window.navigator.userAgent.indexOf("Opera")!=-1);
var isIE = ((!isOpera)&&(navigator.appName=="Microsoft Internet Explorer"));
var isNetscape = ((!isOpera)&&(navigator.appName=="Netscape"));

var Started,Busy,IsError;
var FastestSpeed,SlowestSpeed,SlowURLSpeed,CurrentSpeed,CountDown;
var TotalTime,DLTime,MaxDLTime;
var Frames,Errors,Missed;
var FastURL,SlowURL,LoadingURL,ErrorURL;
var PictureURL;
var WebCamStatsSpan;

var Never=60*60*24;
var Stream=0;

var BreakButtons=true;
var MaxRowCount=2;
var CamWidth=-1;
var CamHeight=-1;
var CamBorder=-1;
var NetscapeOnLoad=(!isIE);
var NetscapeOnLoadSpeed=100;
var OnLoadDelay=1000;

var IEBrake=false;

var Cam;
var fps;
var Rate;
var RateText;

	Started=false;
	Busy=true;
	IsError=false;

	CurrentSpeed=Never;
	SlowURLSpeed=Never;
	FastestSpeed=Never;
	SlowestSpeed=Never;

	LoadingURL="/images/WebCamDl.jpg";
	ErrorURL="/images/WebCamNoImage.jpg";
	FastURL="/images/WebCamNoImage.jpg";
	SlowURL="/images/WebCamNoImage.jpg";

	ResetStats();

function Configure(aFastURL,aSlowURL,aFastestSpeed,aSlowURLSpeed,aDefaultSpeed)
{
	FastURL=aFastURL;
	SlowURL=aSlowURL;
	FastestSpeed=aFastestSpeed;
	SlowURLSpeed=aSlowURLSpeed;
	CurrentSpeed=aDefaultSpeed;
}

function WebCamImage(ShowSpeed)
{
	document.write("<img src='"+LoadingURL+"' name='webcamimg' ");
	if (CamBorder!=-1) document.write("border='"+CamBorder+"' ");
	if (CamWidth!=-1) document.write("width='"+CamWidth+"' ");
	if (CamHeight!=-1) document.write("height='"+CamHeight+"' ");

	if (!NetscapeOnLoad)	document.write("onLoad='ImageOK(this);' ");
	document.write("onError='ImageError(this);'>");
	if(ShowSpeed)
	{
		document.write("<br>");
		WebCamSpeed();	
	}
}

function WebCamSpeed()
{
	document.write(GetCamSpeed());
}

function WebCamStats()
{
	document.write("<span id='WebCamStatsSpan'></span>");
}

function ShowTime(aTime)
{
var Hour,Min,Sec;
var Text;

	if (aTime>=Never) return "Never";

	Hour=Math.floor(aTime/(60*60));
	aTime=aTime-(Hour*60*60);
	Min=Math.floor(aTime/60);
	aTime=aTime-(Min*60);
	Sec=aTime;

	Text="";
	if (Hour==1)	Text=Text+" 1 Hour"
	if (Hour>1)	Text=Text+" "+Hour+" Hours"
	if (Min==1)	Text=Text+" 1 minute"
	if (Min>1)	Text=Text+" "+Min+" minutes"
	if (Sec==1)	Text=Text+" 1 second"
	if (Sec!=1)	Text=Text+" "+Sec+" seconds"
	return Text;
}

function SafeDivide(dividend,divisor)
{
	if (divisor==0)
	{
		return 0;
	}
	return (dividend/divisor);
}

function GetCamSpeed()
{
	if(FastestSpeed>=Never)	return "This cam never updates";
	if(FastestSpeed==Stream)		return "This cam is streaming.";
	return ("This cam updates every"+ShowTime(FastestSpeed)+".");
}

function GetCurrentSpeed()
{
	if(CurrentSpeed>=Never)		return "No updates"
	if(CurrentSpeed==Stream)	return "Streaming";
	return ("Request updates every"+ShowTime(CurrentSpeed)+".");
}

function GetCurrentState()
{
	if (IsError)			return "DOWNLOAD ERROR";
	if (CurrentSpeed>=Never)	return "Never updates";
	if (CurrentSpeed==Stream)	return "Streaming";
	if (Busy)			return "Downloading";
	return ("Next update in "+ShowTime(CountDown)+".");
}

function CalculateRates()
{
	RateText="No images";
	fps=SafeDivide(Frames,TotalTime);  // Frames Per Second.
	Rate=SafeDivide(TotalTime,Frames); // Seconds Per Frame.
	if (Rate>1)	RateText=Math.round(Rate*10)/10+" seconds per frame"
	if (fps>=1)	RateText=Math.round(fps*10)/10+" frames per second";
}

function SetSpeed(Speed)
{
	ResetStats();
	ResetWebCam();
	
	if ((Speed!=-1)&&(Speed<FastestSpeed))
	{
		Speed=FastestSpeed;
	}
	if ((Speed!=Never)&&(Speed>SlowestSpeed))
	{
		Speed=SlowestSpeed;
	}
	if (Speed==-1) // Refresh
	{
		GetPicture();
	}
	else
	{
		CurrentSpeed=Speed;
	}
	if ((!Busy)&&(CurrentSpeed==Stream))
	{
		GetPicture();
	}
	return false;
}

var RowCount;

function WebCamButton(Caption,Speed)
{
	
	if ((Speed==-1)||(Speed==Never)||((Speed>=FastestSpeed)&&(Speed<=SlowestSpeed)))
	{
		if ((MaxRowCount!=-1)&&(RowCount>=MaxRowCount))
		{
			document.write("<br>");
			RowCount=0;
		}
		document.write("<input type='button' value='"+Caption+"' onClick='SetSpeed("+Speed+");'>");
		RowCount+=1;
	}
}

function WebCamButtons()
{
	RowCount= 0;
	
	WebCamButton("Streaming",Stream);
	if(FastestSpeed!=Never)		WebCamButton("Never",Never);
	if (BreakButtons) RowCount=MaxRowCount;
	WebCamButton("1 second",1);
	if (NetscapeOnLoad) WebCamButton("2 seconds",2);
	WebCamButton("5 seconds",5);
	WebCamButton("10 seconds",10);
	WebCamButton("15 seconds",15);
	WebCamButton("30 seconds",30);
	WebCamButton("45 seconds",45);
	WebCamButton("1 minute",60);
	WebCamButton("5 minutes",300);
	if (BreakButtons) RowCount=MaxRowCount;
	WebCamButton("Refresh",-1);
	
}

function StartTimer()
{


	if (isIE)
	{
		verAt = verText.indexOf("MSIE")+5;
		Version=parseFloat(verText.substr(verAt));
	}
	if ((!isOpera)&&(Version>=5.0))
	{
	  	WebCamStatsSpan = window.document.getElementById('WebCamStatsSpan');
	}
	Cam = document.images.webcamimg;
  	Started=true;
  	ResetStats();
  	ResetWebCam();
	if ((Cam)&&(NetscapeOnLoad))
	{
		Busy=!Cam.complete;
		if (Busy)
		{
			setTimeout("NetscapeLoadTimer()", NetscapeOnLoadSpeed);
		}
	}
	DoTimer();
	if ((CurrentSpeed==Stream)&&(NetscapeOnLoad)&&(!Busy))
	{
		GetPicture();
	}
}

function ResetWebCam()
{

	IsError=false;		
	CountDown=0;
	Report();
	if ((CurrentSpeed==Stream)&&(!Busy))
	{
		GetPicture();
	}
}

function ResetStats()
{
	Frames=0;
	Errors=0;
	Missed=0;
	TotalTime=0;
	DLTime=0;
	MaxDLTime=0;
	Report();
	return false;
}

function DoTimer()
{

	TotalTime +=1;
	if (CurrentSpeed<Never)
	{
		CountDown -= 1;
	}
	if (Busy)
	{
		DLTime+=1;
	}
	if (CountDown<=0)
	{
		CountDown=CurrentSpeed;
		if (CurrentSpeed!=Stream)
		{
			if(Busy)
			{
				Missed += 1;
			}
			else
			{
				GetPicture();
			}
		}
	}
	Report();
	setTimeout("DoTimer()", 1000 );
}

function Report()
{
var	Msg;

	CalculateRates();	
	if (WebCamStatsSpan)
	{
		Msg = ""
	
		if (IsError)
		{
			Msg="There was an error downloading from<br>"+PictureURL+"<br>Please select a speed to try downloading again.<br><br>"
		}
		Msg=Msg+"<table Width=100% border='1' cellpadding='0' cellspacing='0'>";
		Msg=Msg+"<tr><th Width=30%>Status<td><th Width=70%>&nbsp</td></tr>";
		Msg=Msg+"<tr><td>Maximum Speed<td><td>"+GetCamSpeed()+"</td></tr>";
		Msg=Msg+"<tr><td>Current Speed<td><td>"+GetCurrentSpeed()+"</td></tr>";
		Msg=Msg+"<tr><td>Action<td><td>"+GetCurrentState()+"</td></tr>";
		Msg=Msg+"<tr><td>Feed<td><td>"+PictureURL+"</td></tr>";
		if(CurrentSpeed<Never)
		{
			Msg=Msg+"<tr><td>Frames<td><td>"+Frames+"</td></tr>";
			Msg=Msg+"<tr><td>Errors<td><td>"+Errors+"</td></tr>";
			Msg=Msg+"<tr><td>Missed<td><td>"+Missed+"</td></tr>";
			Msg=Msg+"<tr><td>Average DL Time<td><td>"+Math.round(Rate*10)/10+" seconds</td></tr>";
			Msg=Msg+"<tr><td>Frame Rate<td><td>"+RateText+"</td></tr>";
			Msg=Msg+"<tr><td>Max DL Time<td><td>"+MaxDLTime+" seconds</td></tr>";
		}
		if (NetscapeOnLoad)
		{
			Msg=Msg+"<tr><td>Load Symantics<td><td>Netscape ("+OnLoadDelay+"ms frame delay)</td></tr>";
		}
		else
		{
			if (IEBrake)
			{
				Msg=Msg+"<tr><td>Load Symantics<td><td>IE ("+OnLoadDelay+"ms frame delay)</td></tr>";
			}
			else
			{
				Msg=Msg+"<tr><td>Load Symantics<td><td>IE (enhanced streaming)</td></tr>";
			}
		}
		Msg=Msg+"</table>";
		
		WebCamStatsSpan.innerHTML=Msg;
	}
}

function GetPicture()
{
var isopen;
var aURL;

	if (!IsError) 
	{
		Busy=true;
		IsError=false;
		DLTime=0;
		isopen = Math.round(1000000+(Math.random() * 1000000));
		if ((CurrentSpeed<SlowURLSpeed)||(SlowURLSpeed==Stream))
		{
			PictureURL=FastURL;
		}
		else
		{
			PictureURL=SlowURL;
		}
		aURL=PictureURL+"?"+isopen;
		if (Cam)
		{
			Cam.src=aURL;
			if (NetscapeOnLoad)
			{
				setTimeout("NetscapeLoadTimer()", NetscapeOnLoadSpeed);
			}
		}

		Report();
	}

}

function ImageOK(anImage)
{

	Busy=false;
	if (Started)
	{
		if (!IsError)
		{
			Frames += 1;
			if (DLTime>MaxDLTime)
			{
				MaxDLTime=DLTime;
			}
		}
		Report();
		if (CurrentSpeed==Stream)
		{
			// It is possible for feeds to download too quickly.
			if (fps>16) {
				if (!IEBrake) OnLoadDelay=0;
				IEBrake=true;
				OnLoadDelay +=100;
				Report();
			}
			if ((fps<2)&&IEBrake&&(OnLoadDelay>100)){
				OnLoadDelay -=100;
				Report();
			}
			if ((NetscapeOnLoad)||(IEBrake))
			{
				setTimeout("NetscapeDoStream()", OnLoadDelay);
			}
			else
			{
				GetPicture();
			}
		}
	}
	return true;
}

function ImageError(anImage)
{
	Busy=true;
	IsError=true;
	Report();
	Errors += 1;
	if (Cam) Cam.src=ErrorURL;
	return false
}

function NetscapeLoadTimer()
{
	if (Cam.complete)
	{
		ImageOK(Cam);
	}
	else
	{
		setTimeout("NetscapeLoadTimer()", NetscapeOnLoadSpeed);
	}
}

function NetscapeDoStream()
{
	GetPicture();
}
