// *******************************************************************
// cdsProfiler.js
//
// Version 2.0
// Copyright (c) 2008 Catalog Data Solutions. All Rights Reserved.
//
// Utility for profiling javascript applications
// *******************************************************************

function cdsProfiler() {
	var stats = new Object();

	/**
	 * Start profiling of code and save the results under the given label
	 */
	this.start = function(label) {
		var st = stats[label];
		if (st != null) {
			st.start();
		} else {
			st = new cdsProfilerStats();
			st.start();
			stats[label] = st;
		}
	}
	
	/**
	 * Stop profiling of code for the given label
	 */
	this.stop = function(label) {
		var st = stats[label];
		if (st != null) st.stop();
	}
	
	/**
	 * Display profiling results
	 */
	this.display = function(elementId) {
		var e = document.getElementById(elementId);
		if (e != null) {
			while (e.hasChildNodes()) e.removeChild(e.lastChild);
			var table = document.createElement("table");
			e.appendChild(table);
			table.setAttribute("border", "1");
			var thead = document.createElement("thead");
			table.appendChild(thead);
			var tr = document.createElement("tr");
			thead.appendChild(tr);
			var td = document.createElement("td");
			tr.appendChild(td);
			td.appendChild(document.createTextNode("Label"));
			td = document.createElement("td");
			tr.appendChild(td);
			td.appendChild(document.createTextNode("Count (s)"));
			td = document.createElement("td");
			tr.appendChild(td);
			td.appendChild(document.createTextNode("Time"));
			td = document.createElement("td");
			tr.appendChild(td);
			td.appendChild(document.createTextNode("Average Time (s)"));
			
			var tbody = document.createElement("tbody");
			table.appendChild(tbody);

			for (var k in stats) {
				var st = stats[k];
				tr = document.createElement("tr");
				tbody.appendChild(tr);
				td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(document.createTextNode(k));
				td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(document.createTextNode(st.count));
				td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(document.createTextNode(st.time / 1000));
				td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(document.createTextNode((st.time / st.count) / 1000));
			}
		}
	}
}

function cdsProfilerStats() {
	this.count = 0;
	this.time = 0;
	this.startTime = null;
	
	this.start = function() {
		if (this.startTime == null) {
			this.startTime = new Date();
		}
	}
	
	this.stop = function() {
		if (this.startTime != null) {
			this.time += (new Date()) - this.startTime;
			this.startTime = null;
			this.count++;
		}
	}
}

var profiler = new cdsProfiler();



