/**
 * Domutils are a set of methods to help manipulate the DOM.  I originally coded
 * these as standalone functions, but ported them to jQuery for this project.
 *  
 * @author Greg Pasquariello
 */
jQuery.newID = function(prefix) {
	if (!jQuery.id) {
		jQuery.id = 0;
	}
	
	if (prefix) {
		return prefix + "_" + ++jQuery.id;
	}
	else {
		return ++jQuery.id;
	}
};


/**
 * For each matched element, creates a DOM tree according to the supplied spec
 * and appends it to the matched element.
 * 
 * For example
 * 
 * $("#container").appendObject({
 *		tag: "div",
 *		style: "border: 1px solid red; height: 50px; width: 300px;",
 *		children: [{
 *			tag: "input",
 *			id: 'hello world',
 *			type: 'text',
 *			value: 'here I am'
 *		}]
 * });
 * @param {Object} spec
 */
jQuery.fn.appendObject = function(spec) {
	var container = this;
	
	return this.each(function(){
		var root;
		
		if (typeof(spec) == "object") {
			root = document.createElement(spec.tag);
			
			//
			// Addresses a bug in IE in which a table must have a <tbody> element.
			//
			if (spec.tag == "table") {
				jQuery(root).appendObject({
					tag: "tbody"
				});
			}
			
			var children = spec.children;
			if (children) {
				for (var i = 0; i < children.length; i++) {
					jQuery(root).appendObject(children[i]);
				}
			}
			
			//
			// Another IE workaround.  setAttribute doesn't work for the class name in 
			// IE, but this works in IE and FF.
			//
			if (spec.cls) {
				root.className = spec.cls;
			}
			
			if (spec.style) {
				root.style.cssText = spec.style;
			}
			
			if (spec.innerHTML) {
				root.innerHTML = spec.innerHTML;
			}
			
			for (key in spec) {
				if (key != "tag" && key != "children" && key != "style" && key != "innerHTML") {
					root.setAttribute(key, spec[key]);
				}
			}
		}
		
		container.append(root);
	});
};