// Save data on client
var c_data = new Array();

// The ID of the current item to view
var c_id;

// When the page is finished loading
function initialize() {
	c_id = getQueryVariable("id");
	changeData();
}

function changeData() {
	
	updateLogic();
	
	//// See if the client already has the data ////
	if (clientAlreadyHasData()) {
		displayData();
	} else {
		getDataFromServer();
	}
	
}

// Update the logic based on user input
function updateLogic() {
	c_id = document.getElementById("id").value;
}

// Determine whether the client has data saved on the computer
function clientAlreadyHasData() {
	if (c_data == null) { return false; }
	if (c_data[c_id] == null) { return false; }
	return true;
}

// Make a call to the server
// Continues in "whenRequestReceived"
function getDataFromServer() {
	var url = "ajax/record.php"
	
	var query = new Array(); // An array of $_GET variables
	query.push("id="+c_id);
	if (query) { url += "?"+query.join("&"); }
	
	// Send request to server
	loadXMLDoc(url)
}


function whenRequestReceived(req) {
	
	// Raw HTML
	var data = req.responseText;
	
	// Pull out the ID of the item
	var data_id = 0;
	if (m = /<!-- ID:(\d+) -->/.exec(data)) { data_id = m[1]; }
	
	if (data_id > 0) {
		// No errors in data
		saveClientData(data_id, data);
		if (stillFocused(data_id)) {
			displayData();
		}
	} else {
		alert("error");
	}
}

function saveClientData(id, data) {
	if (c_data[id] == null) { c_data[id] = data; }
}

// See if the user is still selecting that item
function stillFocused(id) {
	return (id == c_id);
}

// Fill the AJAX file
function displayData() {
	var result = "";
	if (c_data[c_id]) {
		result = c_data[c_id];
	}
	document.getElementById("ajax_table").innerHTML = result;
	
}


//// Code from http://snipplr.com/view.php?codeview&id=623 ////
//// 2008-03-14
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}