/* WHAT
 * formBuilder() creates form elements given a JOSN text of objects with name and value attributes
 * 
 * HOW
 * 1) Create a formBuilder intance: formBuilderName = new formBuilder(theFormElement); 
 *       where theFormElement is an element reference [object] or an id [string]
 *       theFormElement can be the form itself or any container within it. 
 * 2) Build the form - formBuilderName.buildTheForm(data);
 * 3) Submit the form - formBuilderName.form.submit();
 * 
 * DEPENDANCIES
 * Requires json2.js [http://www.json.org/json2.js] to parse the JSON text
 */

// example JSON text
// jsonText = '[ {"name": "PERS_SALUTATION", "value": "Dr", "type": "text"},{"name": "PERS_FIRST_NAME", "value": "My"},{"name": "PERS_LAST_NAME", "value": "Name"} ]';

DEBUG;
if (DEBUG == 'undefined')
	var DEBUG = false;

function FormBuilder(formEl, callbackFn) {
	this.targetForm = '';
	this.formEl = '';
	this.dataObj = '';
	this.defaultType = "hidden";
	this.showLabel = false;

	// some issue after here
	targetForm = formEl;
	while (targetForm.nodeName.toLowerCase() != 'form'){
		targetForm = targetForm.parentNode;
	}
	this.targetForm = targetForm;
	this.buildTheForm = function(data) {
		
		if(typeof(data) == 'text'){
		    dataObj = JSON.parse(data);
		} else {
			dataObj = data;
		}

		for (var i=0; i<dataObj.length; i++){
			
			if (dataObj[i].type == undefined) {
				dataObj[i].type = this.defaultType;
			}
		
			var container = document.createElement('div');
			var formElement = document.createElement('input');
			
			// loop through all attributes 
			for (var prop in dataObj[i]){
				el = dataObj[i];
				formElement.setAttribute(prop, eval('el.'+prop));
			} 
			
			// special case - TODO - maybe move to anonymous fn
			try {
				var labelName = dataObj[i].name.toLowerCase().replace(/_/g, ' ') + ": ";
				var firstLetter = labelName.charAt(0).toUpperCase();
				labelName = firstLetter + labelName.substring(1);
			} catch (err) {
				if (DEBUG){
					alert(err);
				}
			}
			
			if (this.showLabel) {
				var label = document.createElement('label');
				label.innerHTML = labelName;
				label.appendChild(formElement);
				container.appendChild(label);
			} else {
				// check title doesn't already exist
				formElement.title = labelName;
				container.appendChild(formElement);
			}
			formEl.appendChild(container);
		}
		
		if (callbackFn)
			callbackFn();
	}
	
}
// -------------------------------------------


