/********************************************************************\
* FarmSelect Organic Farm Simulator
* Copyright 2007 The Rodale Institute
* 
* File		: $Source: /var/lib/cvsroot/FarmSelect/code/includes/ajax.js,v $
* Author	: Jeremy Eastburn and Brandon Miquel
* Revision	: $Revision: 1.20 $
* Checked in	: $Date: 2007/10/30 00:36:32 $
* Checked in by : $Author: jeastburn $
*
* Revision history at end of file
* 
/********************************************************************/


/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject(); 

function addToTable(plan_id,table_id)
{
	/* COMMENTED OUT VALIDATION (6/19) as there are some fields that are optional, so just let the user confirm before adding row */
	//if (!confirm("Press OK to add this row to the table..."))
	//{
	//	return false;
	//}
	/*
	for (var i=2; i<addToTable.arguments.length; i++)
	{
		var tempVar = arguments[i];

		// Validate/verify each field is non-empty
		if (isRadioGroup(tempVar))
		{
			if (RadioGroupIsEmpty(tempVar))
			{
				alert("Please fill in all fields (Field # "+(i-1)+" is empty)");
				return false;
			}
		}
		else if (isCheckboxList(tempVar))
		{
			// We are not validating checkbox lists (could be a single checkbox list that user doesn't want to check)
		}
		else if (isTextbox(tempVar)) // must check textboxes last
		{
			if (IsEmpty(tempVar))
			{
				alert("Please fill in all fields (Field # "+(i-1)+" is empty)");
				tempVar.focus(); // set focus on missing field
				return false;
			}
		}
	}
	*/

	// Check for hidden row ID field if we are editing existing row
	var editRowID = $('editRowID_'+table_id).value;
	var url = "";

	if (editRowID != null && editRowID != "")
		url = '../ajax_table_insert.php?editRowID=' + editRowID + '&plan_id=' + plan_id + '&table_id=' + table_id;
	else
		url = '../ajax_table_insert.php?plan_id=' + plan_id + '&table_id=' + table_id;

	// All fields have been validated, so loop through again to insert into DB
	var cnt = 0;
	for (var i=2; i<addToTable.arguments.length; i++)
	{
		var tempVar = arguments[i]; // for debugging in firebug

		if (isRadioGroup(tempVar))
		{
			var aRadioGroup = tempVar;
			var success = false;
			for (var x=0; x<aRadioGroup.length; x++)
			{
				if (aRadioGroup[x].checked)
				{
					url += '&qname_' + cnt + '=' + aRadioGroup[x].name;
					url += '&resp_' + cnt + '=' + aRadioGroup[x].value;

					// If successfully verified, empty out field
					aRadioGroup[x].checked=false;
					success = true;
				}
			}

			// If nothing is checked, must still register an empty response to database so table looks correct
			if (!success)
			{
				url += '&qname_' + cnt + '=' + aRadioGroup[0].name;
				url += '&resp_' + cnt + '=' + '';
			}

		}
		if (isCheckboxList(tempVar))
		{
			var aCheckboxList = tempVar;
			// checkbox list can have 1 or many items, must sum up bitwise total
			if (aCheckboxList.length)
			{
				// If there are multiple checkboxes, we need to comma separate the values
				var tempSum = 0;
				for (var x=0; x<aCheckboxList.length; x++)
				{
					if (aCheckboxList[x].checked)
					{
						tempSum += aCheckboxList[x].value;

						// If successfully verified, empty out field
						aCheckboxList[x].checked=false;
					}

				}

				url += '&qname_' + cnt + '=' + aCheckboxList[x-1].name;
				url += '&resp_' + cnt + '=' + tempSum;
			}
			else
			{
				// Element is only a single checkbox
				if (aCheckboxList.checked)
				{
					url += '&qname_' + cnt + '=' + aCheckboxList.name;
					url += '&resp_' + cnt + '=' + aCheckboxList.value;

					// If successfully verified, empty out field
					aCheckboxList.checked=false;
				}
				else
				{
					url += '&qname_' + cnt + '=' + aCheckboxList.name;
					url += '&resp_' + cnt + '=' + '';
				}
			}


		}
		else if (isTextbox(tempVar) || isTextarea(tempVar))
		{
			url += '&qname_' + cnt + '=' + tempVar.name;
			url += '&resp_' + cnt + '=' + escape(tempVar.value);

			// If successfully verified, empty out field
			tempVar.value='';
		}

		// Reset editRowID field to empty in case they want to enter new row after this
		$('editRowID_'+table_id).value = "";

		// Update button text
		eval("document.forms[0].addToTableButton_" + table_id).value = "Add To Table >>";

		cnt++;
	}

	/* Create the request. The first argument to the open function is the method (POST/GET),
		and the second argument is the url... */
	http.open('get', url);
	http.onreadystatechange = function()
		{
			/* Make sure that the transaction has finished. The XMLHttpRequest object 
				has a property called readyState with several states:
				0: Uninitialized
				1: Loading
				2: Loaded
				3: Interactive
				4: Finished */
			if(http.readyState == 4){ //Finished loading the response
				/* Retrieve the responseText property of the XMLHttpRequest object. */
				
				var response = http.responseText;
				/* Perform page-update (if necessary) */
				//NOTHING TO DISPLAY
			}
		}
	http.send(null);

	return true;
}

function deleteFromTable(plan_id,table_id,row_id)
{
	http.open('get', '../ajax_table_delete.php?plan_id=' + plan_id + '&table_id=' + table_id + '&row_id=' + row_id);
	http.onreadystatechange = function()
		{
			if(http.readyState == 4){
				//var response = http.responseText;
				// Row has been deleted, so call "update" function to update the table
				updateTableAfterTimeout(plan_id,table_id);

				// Reset editRowID field to empty in case they want to enter new row after this
				$('editRowID_'+table_id).value = "";

				// Update button text
				eval("document.forms[0].addToTableButton_" + table_id).value = "Add To Table >>";
			}
		}
	/* Send the data. We use something other than null when we are sending using the POST
		method. */
	http.send(null);
}

// We need to PAUSE 1.5 seconds before calling the "update table" method (to allow for database insertion)
function updateTable(plan_id,table_id){
	var t = setTimeout("updateTableAfterTimeout("+plan_id+","+table_id+")",1500);
}

/* Function called to get the product categories list */
function updateTableAfterTimeout(plan_id,table_id) {
	/* Create the request. The first argument to the open function is the method (POST/GET),
		and the second argument is the url... */
	http.open('get', '../ajax_table_update.php?plan_id=' + plan_id + '&table_id=' + table_id);
	/* Define a function to call once a response has been received. */
	http.onreadystatechange = function()
		{
			/* Make sure that the transaction has finished. The XMLHttpRequest object 
				has a property called readyState with several states:
				0: Uninitialized
				1: Loading
				2: Loaded
				3: Interactive
				4: Finished */
			if(http.readyState == 4){ //Finished loading the response
				/* Retrieve the responseText property of the XMLHttpRequest object. */
				var response = http.responseText;
				/* Perform page-update (if necessary) */
				$('update_table_div_'+table_id).innerHTML = response;
			}
		}
	/* Send the data. We use something other than null when we are sending using the POST
		method. */
	http.send(null);
}

function editRowFromTable(plan_id,table_id,row_id)
{
	// Update button text
	eval("document.forms[0].addToTableButton_" + table_id).value = "Edit Row >>";

	// Update hidden row ID field since we are editing
	$('editRowID_'+table_id).value = row_id;

	// Need to pull all field names, field types, and responses from DB
	var response = null;
	http.open('get', '../ajax_table_getrowdata.php?plan_id=' + plan_id + '&table_id=' + table_id + '&row_id=' + row_id);
	http.onreadystatechange = function()
		{
			if(http.readyState == 4){ //Finished loading the response
				var response = http.responseText;

				// Update fields with responses pulled from DB
				// "question_id^question_name^question_type^response|..."
				if (response != null && response != "")
				{
					var arrQuestions = response.split("|");
					for (var i=0; i<arrQuestions.length; i++)
					{
						if (arrQuestions[i] != "")
						{
							var arrQData = arrQuestions[i].split("^");
							var question_id = arrQData[0];
							var question_name = arrQData[1];
							var question_type = arrQData[2];
							var q_response = arrQData[3];

							if (question_type == "textbox")
							{
								var tmp = eval("document.forms[0]." + question_name);
								tmp.value = unescape(q_response);
							}
							else if (question_type == "radio")
							{
								var tmp = $(question_name + q_response);
								if (tmp != null)
									tmp.checked = true;
								else
									clearRadioGroup(eval("document.forms[0]." + question_name));
							}
							else if (question_type == "checkbox")
							{
								var tmp = eval("document.forms[0]." + question_name);
								if (tmp.value == q_response)
									tmp.checked = true;
								else
									tmp.checked = false;
							}

							//COMPLETE FOR OTHER FIELD TYPES HERE...

						}
					}
				}

			}
		}
	http.send(null);

}

/* The following function creates an XMLHttpRequest object... */
function createRequestObject(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}

function isTextbox(aTextbox)
{
	if (typeof(aTextbox)=="object" && aTextbox.tagName && aTextbox.tagName=="INPUT" && typeof(aTextbox.value)=="string")
		return true;
	else
		return false;
}

function isTextarea(aTextbox)
{
	if (typeof(aTextbox)=="object" && aTextbox.tagName && aTextbox.tagName=="TEXTAREA" && typeof(aTextbox.value)=="string")
		return true;
	else
		return false;
}

function isRadioGroup(aRadioGroup)
{
	if (typeof(aRadioGroup)=="object" && aRadioGroup.length > 0 && aRadioGroup[0].type && aRadioGroup[0].type=="radio")
		return true;
	else
		return false;
}

function isCheckboxList(aCheckboxList)
{
	if (typeof(aCheckboxList)=="object" && aCheckboxList.length > 0 && aCheckboxList[0].type && aCheckboxList[0].type=="checkbox")
		return true;
	else if (typeof(aCheckboxList)=="object" && aCheckboxList.type == "checkbox") // checkbox list with only one checkbox
		return true;
	else
		return false;
}

function IsEmpty(aTextField) {
	if ((aTextField.value.length==0) || (aTextField.value==null) || (aTextField.value=="undefined"))
		return true;
	else
		return false;
}

function RadioGroupIsEmpty(aRadioGroup) {
	for (var i=0; i<aRadioGroup.length; i++)
	{
		if (aRadioGroup[i].checked)
		{
			return false;
		}
	}

	return true;
}

function clearRadioGroup(aRadioGroup) {
	for (i=0; i < aRadioGroup.length; i++)
	{
		if (aRadioGroup[i].checked == true)
		{
			aRadioGroup[i].checked = false
		}
	}
}

// Instead of <code>document.getElementById('a')</code>
// Use <code>$('a')</code>
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

/********************************************************************\
* Revision History
* 
* $Log: ajax.js,v $
* Revision 1.20  2007/10/30 00:36:32  jeastburn
* Fixed bug with AJAX editing then deleting
*
* Revision 1.19  2007/09/20 03:41:00  jeastburn
* Resolved bug with escape/unescape of ajax tables
*
* Revision 1.18  2007/09/07 00:52:12  jeastburn
* Added checkbox functionality to ajax edit and fixed an IE bug
*
* Revision 1.17  2007/09/03 01:18:31  jeastburn
* Continued ajax table editing
*
* Revision 1.16  2007/08/29 02:07:45  jeastburn
* Modified ajax insert code to allow for editing a specific row
*
* Revision 1.15  2007/08/26 00:31:33  jeastburn
* Continued AJAX edit functionality
*
* Revision 1.14  2007/08/23 00:44:50  jeastburn
* Started ajax edit functionality
*
* Revision 1.13  2007/08/09 23:31:34  jeastburn
* Added textarea as acceptable ajax table question type
*
* Revision 1.12  2007/06/26 14:07:25  jeastburn
* Removed Confirm box on AJAX button click
*
* Revision 1.11  2007/06/25 01:35:40  jeastburn
* Switched all table fields over to list_id generated radio and checkbox lists
*
* Revision 1.10  2007/06/22 01:07:27  jeastburn
* Completed implementation of AJAX on all tables in OFP
*
* Revision 1.9  2007/06/20 01:01:38  jeastburn
* Added AJAX checkbox list support
*
* Revision 1.8  2007/06/19 02:13:32  jeastburn
* Completed Delete Table Row via AJAX functionality
*
* Revision 1.7  2007/06/18 01:43:36  jeastburn
* Fixed IE7 AJAX issue with setTimeout()
*
* Revision 1.6  2007/06/17 19:18:41  jeastburn
* Added CVS tags
*
* Revision 1.5  2007/06/17 19:16:31  jeastburn
* Added header/footer CVS tags
*
*
*
* 
/********************************************************************/
