/*****************************************************************

	StopWatch javascript class by Peter Bailey - Copyright (c) 2003
	Website: http://www.peterbailey.net/dev/jsclasses/

	Freeware for non-commercial use only.  Contact me regarding
	commercial application of this class.

	Main Features:
	-	Save multiple results and get reports
	-	toString method for useful alerting
	-	Built-in error checking

	Compatibility:
	-	Tested on IE6 and Mozilla 1.1
	-	DOM compliant browsers only

	Note: This document was created with a tab-spacing of four (4)

******************************************************************/

function StopWatch()
{
    this.startTime = null;
    this.endTime   = null;
    this.running   = false;
}

StopWatch.prototype.start = function()
{
    if ( this.running ) return;
	this.startTime = new Date().getTime();
    this.running   = true;
}

StopWatch.prototype.stop = function()
{
    this.endTime = new Date().getTime();
    this.running = false;
}

StopWatch.prototype.read = function()
{
    return this.endTime - this.startTime;
}

StopWatch.prototype.reset = function()
{
    this.startTime = null;
    this.endTime = null;
}

// Advanced methods below.  Remove if unwanted.
StopWatch.prototype.saveAs = function( id, name, overwrite )
{
	if ( this.running )
	{
		alert( 'You cannot save a result while the stopwatch is running!' );
		return;
	}
	if ( !this.saves ) this.saves = new Object();
	if ( this.saves[id] && !( Boolean( overwrite ) ) ) 
	{
		if ( confirm( "Overwrite save '" + id + "'?" ) )
			this.saves[id] = { 'name' : name, 'time' : this.read() }
	}
	else
		this.saves[id] = { 'name' : name, 'time' : this.read() }
}

StopWatch.prototype.getResult = function( id )
{
	if ( save = this.saves[id] )
		return save.time;
	return null;
}

StopWatch.prototype.report = function( id )
{
	if ( !this.saves )
	{
		alert( 'No saved results!' )
	}
	else
	{
		if ( typeof id == 'undefined' )
		{
			var report, total = 0, r = "";
			for ( var i in this.saves )
			{
				report = this.saves[i];
				r += report.name + ": " + report.time + "ms\n";
				total += report.time;
			}
			r += "\nTotal time elapsed: " + total + "ms";
			alert( r );
		}
		else
		{
			var report = this.saves[id];
			alert( report.name + ": " + report.time + "ms\n" );
		}
	}
}

StopWatch.prototype.toString = function()
{
	var i = 0, s = new Array();
	s[i++] = "Running: " + ( ( this.running ) ? "Yes" : "No" );
	s[i++] = "Start: " + this.startTime;
	s[i++] = "End: " + this.endTime;
	s[i++] = "Time Elapsed: " + ( ( this.endTime == null ) ? ( new Date().getTime() - this.startTime ) : this.read() ) + "ms";
	return ( s.join( "\n" ) );
}