var templateForm;
var desinationForm;


/*
Wrapper for the JQuery AJAX .post function
*/
function submitAJAX(iPage, iData, iSync) {
	if (iSync == null) {
		iSync = false;
	}
	//jQuery("#test_form").serialize()
	//{username: "ksmithwick"}
	
	//jQuery.post(iPage, iData, function(data, status) { handleAJAXResponse(data, status); }, "html");
	//jQuery.post(iPage, iData, function(data, status) { handleAJAXResponse(data, status); }, "json");
	//alert(iData);
	
	jQuery.ajax({
		type: "POST", 
		dataType: "json",
    	url: iPage,
    	global: true,
    	async: iSync, 
    	data: iData, 
    	success: function(data, textStatus) {
			handleAJAXResponse(data, textStatus);
			//alert(data);
    	}
   	});
}


/*
Handle the JQuery AJAX Post response
*/
function handleAJAXResponse(jsonObj, textStatus) {
	//alert(jsonObj);
		
	// Update the destination form
	if ((templateForm) && (desinationForm)) {
		var tmpTemplate = findObj(templateForm.attr('id'));
		findObj(desinationForm.attr('id')).innerHTML = tmpTemplate.innerHTML;
		//desinationForm.html(templateForm.html());
	}
	
	templateForm = '';
	desinationForm = '';
	
	if (textStatus == 'success') {
		processJSONData(jsonObj);
		
	} else {
		alert('AJAX Execution Error: ' + textStatus);
	}	
}


/*
Process the specified JSON data object
*/
function processJSONData(iJSON, iContainer) {
	jQuery.each(iJSON, function(iVariable, iValue) {
		if (iValue) {
			if (iContainer) {
				var tmpObj = jQuery('#' + iContainer + ' #' + iVariable);
				//if (!tmpObj.size()) { var tmpObj = jQuery('#' + iContainer + " [name=" + iVariable + "]"); }
				//if (!tmpObj.size()) { var tmpObj = jQuery('#' + iContainer + " [id*=" + iVariable + "]"); }
				//if (!tmpObj.size()) { var tmpObj = jQuery('#' + iContainer + " [name*=" + iVariable + "]"); }

			} else {			
				var tmpObj = jQuery('#' + iVariable);
				//if (!tmpObj.size()) { var tmpObj = jQuery("[name=" + iVariable + "]"); }
				//if (!tmpObj.size()) { var tmpObj = jQuery("[id*=" + iVariable + "]"); }
				//if (!tmpObj.size()) { var tmpObj = jQuery("[name*=" + iVariable + "]"); }
			}
			
			// If the current object is another JSON oject
			if ((typeof iValue == 'object') && (iValue.toString().indexOf('object') > -1)) {
				if (iContainer) {
					processJSONData(iValue, iContainer + ' #' + iVariable);
				} else {
					processJSONData(iValue, iVariable);
				}
				
			} else {
				//alert(iContainer + '.' + iVariable + ' = ' + iValue + ' : ' + tmpObj.size());

				// Object exists on the page
				if (tmpObj.size()) {
					setFieldValue(tmpObj, iValue);
					
    	   		// Object doesn't exist on the page
				} else {
					// Check for a JS function
					if (iVariable.indexOf('script_') == 0) {
						setTimeout(iValue, 10);
						//eval(iValue);
					
					// Check for a form validation error
					} else if (iVariable.indexOf('_error') > -1) {
						setFormError(iVariable.replace('_error', ''));
					
					} else {
						//alert('AJAX Variable Error: ' + iVariable);
					}
				}
			}
		}
	});
}


function setFieldValue(iFieldObj, iValue) {
	switch (iFieldObj.attr('type')) {
		case 'text':
		case 'password':
		case 'file':
		case 'hidden':
		case 'submit':
		case 'button':
		case 'reset':
		case 'textarea':
		case 'select-multiple':
			iFieldObj.val(iValue);
			//alert(jQuery(tmpObj).fieldValue());
			break;

		case 'checkbox':
			if (!iFieldObj.attr('checked')) {
				iFieldObj.trigger('click');
			} else {
				//iFieldObj.attr('checked', false);
			}
			break;
								
		case 'select-one':
			findObj(iFieldObj.attr('id')).value = iValue;
			//tmpObj.val(iValue);
			break;
								
		case 'radio':
			jQuery("input[name=" + iFieldObj.attr('id') + "]").each(function() {
				if (jQuery(this).val() == iValue) {
					jQuery(this).attr('checked', 'checked');
				}
			});
			break;
								
		default:
			//iFieldObj.html(iValue);
			if (iFieldObj.attr('id')) {
				findObj(iFieldObj.attr('id')).innerHTML = iValue;
			}
			break;
	}
}


/*
Add the error classes to the specified field
*/
function setFormError(iErrorName) {
	jQuery('#' + iErrorName).addClass('errorElem');
	//jQuery("[name=" + iErrorName + "]").addClass('errorElem');
	jQuery('#' + iErrorName + '_label').addClass('errorCell');
}


/*
Clean all error elements in the specified form
*/
function clearFormErrors(iFormObj) {
	jQuery('.errorElem').removeClass('errorElem');
	jQuery('.errorCell').removeClass('errorCell');	
}


/*
The error element has been focused so clear any error objects
*/
function cleanFormError(iErrorObj) {
	var tmpName = iErrorObj.name || iErrorObj.id || iErrorObj.attr('name') || iErrorObj.attr('id');
	if (tmpName) {
		jQuery('#' + tmpName).removeClass('errorElem');
		//jQuery("[name=" + tmpName + "]").removeClass('errorElem');
		jQuery('#' + tmpName + '_label').removeClass('errorCell');
	}
}


/*
Disable a form button, and set updating display label
*/
function doFormSubmit(iDisplay, iForm) {
	var tmpName = iForm.name || iForm.id;

	// Clear all form errors
	clearFormErrors(iForm);
	
	jQuery('#' + tmpName + ' #updateBtn').attr('disabled', true);	
	iDisplay = replace(iDisplay, '...', '<img src=\'/images/progress_dots.gif\'>');	
	jQuery('#' + tmpName + ' #updateMsg').html('<span class="btext12">' + iDisplay + '</span><br><br>');
}


/*
Show a data form for the specified form
*/
function showDataForm(iID, iFormName) {
	var Now = new Date();
	var Start = Now.getTime()
	
 	toggleLinks('update_' + iID, 'image_' + iID); 
 	
 	if ((jQuery('#image_' + iID).attr('src')).indexOf('minus') == -1) {
 		return false;
 	}
 	
 	jQuery('#update_' + iID).html('<br><center><b>Loading data...</b></center><br>'); 
 	
 	var tmpAddress = window.location.href;
	if (tmpAddress.indexOf('?') > 0) {
		var tmpDat = tmpAddress.split('?');
		tmpAddress = tmpDat[0];
	}

	templateForm = jQuery('#' + iFormName);
	desinationForm = jQuery('#update_' + iID);
	
 	submitAJAX(tmpAddress + '?action=XML_GET', {0: iID});
 	
	var Now = new Date();
	//alert((Now.getTime() - Start));
	
	//setTimeout('alert(jQuery(\'#update_1 #user_id\').fieldValue());', 2000);
}
