/**************************************************************************************************************/
// Create xmlhttp object based on browsertype
function getHTTPObject() {
	if (window.XMLHttpRequest)
	{
		  // If IE7, Mozilla, Safari, etc: Use native object
		  var xmlHttp = new XMLHttpRequest();
	} else {
		if (window.ActiveXObject)
		{
		  // ...otherwise, use the ActiveX control for IE5.x and IE6
		  var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}
/**************************************************************************************************************/
// Define global variables to be used throughout
var tableBusy = false;
var tableHttp = getHTTPObject();
var tblName;
var offset = 0;
var totalRecords = 0;
var lmtResults = 10;
var primaryKey;
var searchField;
var searchValue;
var lastFocused = '';
var newRecord = [];
setTimeout("getTable()",1000);
/**************************************************************************************************************/
function getTable()
{
	// Main driver function for this application
	// Determines the table primary key, and filters, and sends an AJAX query
	// to the backend DB, then parses and outputs the records
	document.getElementById('debug').innerHTML = '<span style="color: red;">Processing...</span><br />---------------<br />' + document.getElementById('debug').innerHTML;
	document.getElementById('imgProgress').style.display = 'inline';
	tblName = document.getElementById('tblSelect').options[document.getElementById('tblSelect').selectedIndex].innerHTML;
	primaryKey = document.getElementById('tblSelect').value;
	searchField = document.getElementById('searchField').options[document.getElementById('searchField').selectedIndex].innerHTML;
	searchValue = document.getElementById('searchValue').value;

	if (!tableBusy)
	{
		var url = "getTable.php?pk=" + primaryKey + "&tblName=" + tblName + '&offset=' + offset + '&lmtResults=' + lmtResults + '&searchField=' + searchField + '&searchValue=' + searchValue;
		tableHttp.open("GET", url, true);
		tableHttp.onreadystatechange = tablesResponse;
		tableBusy = true;
		tableHttp.send(null);
	}
}
function tablesResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var xmlRecord = tableHttp.responseXML.getElementsByTagName('record');
				var output = '<table id="liveData">';

				// Use the first data record to supply status, summary, etc
				var recordCount = xmlRecord[0].getElementsByTagName('status').item(0).firstChild.data;
				totalRecords = xmlRecord[0].getElementsByTagName('total').item(0).firstChild.data;
				var sql = xmlRecord[0].getElementsByTagName('sql').item(0).firstChild.data;
				offset = parseInt(xmlRecord[0].getElementsByTagName('offset').item(0).firstChild.data);
				lmtResults = parseInt(xmlRecord[0].getElementsByTagName('lmtResults').item(0).firstChild.data);
				document.getElementById('debug').innerHTML = sql + '<br />---------------<br />' + document.getElementById('debug').innerHTML;

				// Populate array of field names by using names of the fields in the second record
				fieldNames = [];
				var xmlNumFields = xmlRecord[1].childNodes.length;
				for (var i=0; i < xmlNumFields; i++)
					fieldNames[fieldNames.length] = xmlRecord[1].childNodes[i].tagName;

				// Output field names as table headers
				output += '<tr><th>Record</th>';
				for (var i=0; i < fieldNames.length; i++)
					output += '<th>'+fieldNames[i]+'</th>';
				output += '</tr>';

				// For each record, loop through fields, recording data
				for (var i=1; i < xmlRecord.length; i++)
				{
					// Find the primary key value before outputting entire row
					var pkValue = '';
					for (var j=0; j < fieldNames.length; j++)
						if (fieldNames[j] == primaryKey) pkValue = xmlRecord[i].getElementsByTagName(fieldNames[j]).item(0).firstChild.data;

					output += '<tr>';
					output += '<td><input type="button" style="background: #FFFFFF; border: solid 1px #C00000; color: #0000C0; cursor: pointer;" value="Delete" onclick="updateRecord(\'' + tblName + '\', \'' + primaryKey + '\',\'\',\'' + pkValue + '\',\'\',true);" /></td>';
		
					// For each column, display input box with value + pkValue
					for (var j=0; j < fieldNames.length; j++)
					{
						var fieldName = fieldNames[j];
						var fieldValue = '';
						
						// Try / catch, to account for errors thrown by bad xml or empty fields
						try	{
							fieldValue = xmlRecord[i].getElementsByTagName(fieldName).item(0).firstChild.data; 
						}
						catch (e){};

						output += '<td><input type="text" size="'+(100/(xmlNumFields))+'%" onchange="updateRecord(\'' + tblName + '\', \'' + primaryKey + '\', \'' + fieldName + '\', \'' + pkValue + '\', this.value, false);" value="'+unescape(fieldValue)+'" /></td>';
					}
					output += '</tr>';
				}

				// Fill in gaps for output table;
				for (var i=xmlRecord.length; i < lmtResults; i++)
				{
					output += '<tr>';
					for (var j=0; j < fieldNames.length+1; j++)
							output += '<td>&nbsp;</td>';
					output += '<tr>';
				}

				// ADD new Record
				output += '<tr>';
				output += '<td><input type="button" onclick="addRecord();" style="background: #FFFFFF; border: solid 1px #C00000; color: #C00000; cursor: pointer;" value="&nbsp;Add&nbsp;" /></td>';
				for (var j=0; j < fieldNames.length; j++)
					output += '<td><input type="text" id="'+fieldNames[j]+'" size="'+(100/(xmlNumFields))+'%" /></td>';
				output += '</tr>';

				output += '</table>';

				// Add summary and controls to output
				output += recordCount + '<br />';
				output += '<input type="button" value="&nbsp;<&nbsp;<&nbsp;" onclick="offset = 0; getTable();" />';
				output += '<input type="button" value="&nbsp;<&nbsp;" onclick="offset -= lmtResults; getTable();"/>';
				output += '<input type="button" value="&nbsp;>&nbsp;" onclick="offset += lmtResults; getTable();"/>';
				output += '<input type="button" value="&nbsp;>&nbsp;>&nbsp;" onclick="offset = ('+totalRecords+' - lmtResults); getTable();" />';
				
				// Draw Record status and nav buttons
				document.getElementById('database').innerHTML = output;

				// Create menu to jump to page
				var jump = ' Jump to Page: <select onchange="offset = this.value; getTable();" class="customform">';
				var pageNum = 0;
				for (var q = 0; q <= totalRecords; q += lmtResults)
				{
					++pageNum;
					// Set option selected when the offset patches the page
					if (q == offset || (q >= totalRecords-lmtResults) && (offset == totalRecords - lmtResults))
					{
						jump += '<option selected value="'+ q +'"> '+ pageNum +' </option>';
					}
					else
					{
						jump += '<option value="'+ q +'"> '+ pageNum +' </option>';
					}
				}
				jump += '</select>';
				document.getElementById('jump').innerHTML = jump;

				// Create option to select field to filter by
				var filter = ' Filter by field: <select id="searchField" onchange="getTable();" class="customform">';
				for (var i=0; i < fieldNames.length; i++)
					filter += (fieldNames[i] == searchField) ? '<option selected>'+ fieldNames[i] +'</option>' : '<option>'+ fieldNames[i] +'</option>';
				filter += '</select>';
				document.getElementById('field').innerHTML = filter;
				
				tableBusy = false;
				document.getElementById('imgProgress').style.display = 'none';
				addHighlights();
			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function
/**************************************************************************************************************/
function updateRecord(tblName, primaryKey, fieldName, pkValue, newValue, boolDelete)
{
	document.getElementById('debug').innerHTML = '<span style="color: red;">Processing...</span><br />---------------<br />' + document.getElementById('debug').innerHTML;

	var url = "updateTable.php?tblName=" + tblName
			+ "&fieldName=" + fieldName
			+ "&primaryKey=" + primaryKey
			+ "&pkValue=" + pkValue
			+ "&newValue=" + newValue
			+ "&boolDelete=" + boolDelete;

	updateHttp = getHTTPObject();
	updateHttp.open("GET", url, true);
	updateHttp.onreadystatechange = function()
	{
		if (updateHttp.readyState == 4)
		{
			if (updateHttp.responseText.indexOf('invalid') == -1)
			{
				var xmlRecord = updateHttp.responseXML.getElementsByTagName('query');

				// Use the first data record to supply status, summary, etc
				var sql = xmlRecord[0].getElementsByTagName('sql').item(0).firstChild.data;
				var result = xmlRecord[0].getElementsByTagName('result').item(0).firstChild.data;

				document.getElementById('debug').innerHTML = sql + '<br /><span style="color: blue">Result: ' + result + '</span><br />---------------<br />' + document.getElementById('debug').innerHTML;
				getTable();
			} // if index valid
		}	// End Readystate change
	};
	updateHttp.send(null);
}
/**************************************************************************************************************/
function addRecord()
{
	document.getElementById('debug').innerHTML = '<span style="color: red;">Processing...</span><br />---------------<br />' + document.getElementById('debug').innerHTML;

	var url = "addRecord.php?tblName=" + tblName;
	for (var j=0; j < fieldNames.length; j++)
		url += "&field" + j + "=" + document.getElementById(fieldNames[j]).value;

	addHttp = getHTTPObject();
	addHttp.open("GET", url, true);
	addHttp.onreadystatechange = function()
	{
		if (addHttp.readyState == 4)
		{
			if (addHttp.responseText.indexOf('invalid') == -1)
			{
				var xmlRecord = addHttp.responseXML.getElementsByTagName('query');

				// Use the first data record to supply status, summary, etc
				var sql = xmlRecord[0].getElementsByTagName('sql').item(0).firstChild.data;
				var result = xmlRecord[0].getElementsByTagName('result').item(0).firstChild.data;

				document.getElementById('debug').innerHTML = sql + '<br /><span style="color: blue">Result: ' + result + '</span><br />---------------<br />' + document.getElementById('debug').innerHTML;

				offset = (totalRecords - lmtResults+1);
				getTable();
			} // if index valid
		}	// End Readystate change
	};
	addHttp.send(null);
}
/******* INTERACTIVE DB_ADMIN TABLES (used for colorized visual effects) ************************/
function addHighlights()
{
	var liveTable = document.getElementById('liveData');
   	var inputs = liveTable.getElementsByTagName("input");

	/* Retrieve the number of TD's in the table */
	var numInputs = inputs.length;

	/* Now loop through the table cells */
	for ( i=0; i < numInputs; i++ )
	{
		/* Set an object reference to the current table cell */
		var currentInput = inputs[i];
		currentInput.onfocus = onFocus;
		currentInput.onblur = onBlur;
		currentInput.onmouseover = onOver;
		currentInput.onmouseout = onOut;
	}
}
function onFocus()
{
	if (this.type != "button")
	{
		lastFocused = this;
		this.style.background = '#FFFFFF';
		this.style.border = '1px solid #C00000';
		this.style.color = '#0000C0';
	}
}
function onBlur()
{
	if (this.type != "button")
	{
		this.style.background = '#ECECEC';
		this.style.border = 'solid 1px #B0B0B0';
		this.style.color = '#000000';
	}
}
function onOver()
{
	if (this.type != "button" && this != lastFocused)
	{
		this.style.background = '#F8F8F8';
	}
	else if (this.type == "button")
	{
		this.style.background = '#ECECEC';
	}
}
function onOut()
{
	if (this.type != "button" && this != lastFocused)
	{
		this.style.background = '#ECECEC';
		this.style.border = 'solid 1px #B0B0B0';
		this.style.color = '#000000';
	}
	else if (this.type == "button")
	{
		this.style.background = '#FFFFFF';
	}
}
/*********************************************************/
