/**
 * The lookup function takes a string (inputString) and makes a call
 *   to a server side script (index.php) with the parameters functionToCall
 *   and input using Ajax.
 * When the AJAX call returns, it calls the handleResponse function.
 * I believe that this function returns immediately????
 */
function lookup(inputString, cbFunction) {
	if (inputString.length > 1) {
		var jsonObj = {
			input: inputString
		};
		var input = JSON.stringify(jsonObj);
		ajax("getSuggestionsList", input, cbFunction);
	}
}

function lookup_event(inputString, cbFunction) {
	if (inputString.length > 1) {
		var jsonObj = {
			input: inputString
		};
		var input = JSON.stringify(jsonObj);
		ajax("getEventsList", input, cbFunction);
	}
}
/**
 * Retrieves the route given the parameters oulined in the param variable
 */
function getRoute(param, cbFunction) {
	var input = JSON.stringify(param);
	ajax("getRoute", input, cbFunction);
}

// ---------- General AJAX API ------------
// global xmlHttp variable
var xmlHttp;
/**
 * This function initializes the xmlHttp global variable.  Applies a singleton
 * design pattern approach to this object.
 */
function initxmlHttp() {
	xmlHttp = null;
	try {
		xmlHttp = new XMLHttpRequest(); 
	}
	catch(e) {
		try {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e) {
			try{
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e) {
				alert("Browser does not support AJAX!");
				return false;
			}
		}
	}
}

/**
 * Performs an ajax call passing into index.php the functionToGet parameter
 *   as a GET request and then the input parameter as the POST request.
 */
function ajax(functionToGet, input, cbFunction) {
	// instantiate the xmlHttp singleton if needed
	//if (xmlHttp == null) {
		initxmlHttp();
	//}
	//if (xmlHttp.readyState != 4) {
	//	xmlHttp.abort();
	//}
	// create parameter list for POST request via XHR
	var paramString = "input=" + input;
	
	// ---- for debugging ----
	//alert(paramString); return;
	
	// form url
	var url = "./php/index.php?functionToCall=" + functionToGet;
	
	// --------- make XHR call -----------
	// define Ajax callback function
	xmlHttp.onreadystatechange = cbFunction;
	
	// open POST connection
	xmlHttp.open("POST", url, true);
	
	// define POST headers
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", paramString.length);
	xmlHttp.setRequestHeader("Connection", "close");
	
	// send Ajax call
	xmlHttp.send(paramString);
}
