
/* Courtesy of Reuven Lerner @ Linux Journal */

var xhr = getXMLHttpRequest();
var subforms_node = null;

function getXMLHttpRequest() {

	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {};
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {};
	try { return new XMLHttpRequest(); } catch(e) {};

	return null;

}

function _appendSubForm(element_id) {

	if( xhr.readyState == 4 ) {

		if( xhr.status == 200 ) {

			subforms_node.appendChild(makeSubForm());

		} else {

			alert("Unable to load form.  Please try again later.");

		}

	}

}

function makeSubForm() {

	var new_node = document.createElement("div");

	// Set subform id...
	new_node.id = 'PetSubForm_' + subforms_node.childNodes.length;

	// Setup base HTML content...
	new_node.innerHTML = (
		'<fieldset>' +
			'<legend>' +
				'Pet Reservation Information ' +
				'(<a href="javascript:removeSubForm(\'' + new_node.id + '\');">remove</a>)' +
			'</legend>' +
			xhr.responseText +
		'</fieldset>' +
		'<br style="clear:both;" />'
	);

	// Update input element names...
	updateElementNames(new_node.getElementsByTagName('input'));

	// Update textarea element names...
	updateElementNames(new_node.getElementsByTagName('textarea'));

	// Update select element names...
	updateElementNames(new_node.getElementsByTagName('select'));

	return new_node;

}

function updateElementNames(elements) {

	for( var x = 0; x < elements.length; x++ ) {

		elements[x].name = subforms_node.childNodes.length + '|' + elements[x].name;

	}

}

function appendSubForm(template_name) {

	if( subforms_node = document.getElementById("SubForms") ) {

		xhr.open("GET", template_name, true);

		xhr.onreadystatechange = _appendSubForm;

		xhr.send(null);

	} else {

		alert('No such element: ' + element_id );

	}

}

function removeSubForm(subform_id) {

	condemned_node = document.getElementById(subform_id);

	condemned_node.parentNode.removeChild(condemned_node);

}

/*
	The use of radio buttons works great!  Uh...  Unless
	you're using IE.  So, once again, let us cater to the
	lowest common denominator by adding an unsavory hack
	that makes checkboxes behave like radio buttons.  Sigh...
*/
function checkboxAsRadio(field_name, field_value) {

	elements = document.getElementsByTagName('input');

	for( x = 0; x < elements.length; x++ ) {

		if( elements[x].name == field_name ) {

			if( elements[x].value == field_value ) {

				elements[x].checked = true;

			} else {

				elements[x].checked = false;

			}

		}

	}

}