// send an ajax request to the server to get
// auto suggest info and return the results

// maximum number of auto suggestions to display
var maxAutoSuggest = 8;

// preset request and field id variables
var request = false;
var fldId = '';

// send the request to suggest_xml.php
function sendRequest(url, parameters) {
	request = false;
	if (window.XMLHttpRequest) { // every browser but older IE
		request = new XMLHttpRequest();
		if (request.overrideMimeType) {
			// set type accordingly to anticipated content type
			request.overrideMimeType('text/xml');
			//request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // old IE
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!request) {
		alert('Cannot create XMLHttp request');
		return false;
	}
	request.onreadystatechange = getReply;
	request.open('POST', url, true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", parameters.length);
	request.setRequestHeader("Connection", "close");
	request.send(parameters);
}

// read the reply from suggest_xml and create the auto suggest list
function getReply() {
	if (request.readyState == 4) { // response is ready
		if (request.status == 200) { // status was ok
			//alert(request.responseText); // for debugging
			var xml = request.responseXML;
            var results = xml.getElementsByTagName('results')[0].childNodes;
			// if we got results
			if(results.length){
				var suggest = new Array();
				var idx=0;
				// cycle results and store them in an array
				for(var i=0;i<results.length;i++){
					if(results[i].hasChildNodes())
						suggest[idx++]=results[i].childNodes[0].nodeValue;
				}
				// create the new auto suggest list
				AutoComplete_Create(fldId, suggest, maxAutoSuggest);
			}
			return;
		} else {
			alert('There was a problem getting your suggestions. Please try again later.');
		}
	}
}

// process the form fields to build the post data and call sendRequest
function ajaxForm(form,field){
	// build the post variable - add input name/value and call processForm
	// to build the rest of the post using the form elements
	var post='input='+field+processForm(form,false);
	//alert(post); // for debugging
	
	// extract the field id (first 4 chars after the comma)
	fldId=field.substr(field.indexOf(',')+1,4);
	
	// send the request
	sendRequest('http://www.fivestargulfrentals.com/wp-content/themes/fivestargulfrentals/php/suggest_xml.php', post);
}

