/*
	gmDebug.js - CopyLeft 2011 Greg Macdonald, greg@ggmac.com
*/



/*
 * Client debugging utility
 *
 *	TODO: JSLint does not like the way we declare this singelton, preferring we remove 'new', but then
 *			we can't just use the gmDebug object because there isn't actually an instance.  Hmmm...
 */
var gmDebug = new function () {
	this.logWindow = null;
	this.enabled = false;

	this.enable = function (enable) {
		this.enabled = enable || true;
		if (!enable && this.logWindow) {
			this.logWindow.close();
		}
	};

	this.openLogWindow = function () {
		if (!this.logWindow || this.logWindow.closed) {
			this.logWindow = window.open('', 'gmDebugLog', 'height=500, width=350, location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no');
			if (this.logWindow) {
				this.logWindow.document.writeln("<html><head><title>Debug Logger</title></head><body><div id='content'></div></body></html>");
			}
		}
		this.enabled = (this.logWindow ? true : false);
	};

	this.clear = function () {
		var pageContent;

		if (this.enabled) {
			this.openLogWindow();	// on page reload the log window can exist before we have a handle to it.
			if (this.logWindow) {
				pageContent = this.logWindow.document.getElementById('content');
				if (pageContent) {
					pageContent.innerHTML = "";
				}
			}
		}
	};

	this.log = function (html) {
		var line, pageContent;

		if (this.enabled) {
			this.openLogWindow();

			line = this.logWindow.document.createElement('div');
			line.innerHTML = html;

			pageContent = this.logWindow.document.getElementById('content');
			if (pageContent) {
				pageContent.appendChild(line);
			} else {
				this.logWindow.document.firstChild.appendChild(line);
			}
			line.scrollIntoView();
		}
	};

	// Dump an object or data element to the log.
	this.dump = function (thing, label) {
		var dumpStr = this.thingToString(thing, label) + "<br>";
		this.log(dumpStr);
	};

	// Dump an object or data element to a string.  Recurses contained compound objects
	this.thingToString = function (thing, label) {
		var name,
			type = typeof thing,
			str = (label || typeof thing) + " <span style='color:#ccc'>(" + type + ")</span> ";

		if ('object' === type) {
			str += "<blockquote style='margin:0 0 0 15px'>";
			for (name in thing) {
				if (thing.hasOwnProperty(name)) {
					str += this.thingToString(thing[name], name);
				}
			}
			str += "</blockquote>";
		} else {
			str += thing.toString() + "<br>";
		}
		return str;
	};
};

