// ----------------------------------------------------------------------------
//  AJAX Functions
// ----------------------------------------------------------------------------

// Purpose: Create an HTTP query string out a form (which is passed by reference to the function).
// By Matthew Eernisse (http://www.onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprequest.html)
function formData2QueryString (docForm) {
	var submitContent = '';
	var formElem;
	var lastElemName = '';
	
	for (var i = 0; i < docForm.elements.length; ++i) {
		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'select-one':
				submitContent += formElem.name + '=' + escape(formElem.value) + '&'
				break;
			// Radio buttons
			case 'radio':
				if (formElem.checked) {
					submitContent += formElem.name + '=' + escape(formElem.value) + '&'
				}
				break;
			// Checkboxes
			case 'checkbox':
				if (formElem.checked) {
					// Continuing multiple, same-name checkboxes
					if (formElem.name == lastElemName) {
						// Strip of end ampersand if there is one
						if (submitContent.lastIndexOf('&') == submitContent.length-1) {
							submitContent = submitContent.substr(0, submitContent.length - 1);
						}
						// Append value as comma-delimited string
						submitContent += ',' + escape(formElem.value);
					}
					else {
						submitContent += formElem.name + '=' + escape(formElem.value);
					}
					submitContent += '&';
					lastElemName = formElem.name;
				}
				break;
		}
	}
	// Remove trailing separator
	submitContent = submitContent.substr(0, submitContent.length - 1);
	return submitContent;
};

// Function: Parse a JSON text to produce an object or array. It will return false if there is an error.
// Derived from JSON.org parser (http://www.json.org/js.html)
function parseJSON (jsonString) {
	try {
		return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
			jsonString.replace(/"(\\.|[^"\\])*"/g, ''))) && //"// (syntax-highlighting fix)
			eval('(' + jsonString + ')');
	} catch (e) {
		return false;
	}
};

// ----------------------------------------------------------------------------
//  Utility Functions
// ----------------------------------------------------------------------------

// Turns wait (hourglass) cursor on or off for the whole page depending on status argument.
function switchWaitCursor (status) {
	$('#waitoverlay').css('display', status ? 'block' : 'none');
};

// Add function to String class to trim white space from beginning and end of string.
String.prototype.trim = function () {
  return this.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

// Set up the client-side functionality for an AJAX-powered user selector.
function startUserSelector (selector, fnfield, lnfield, excludestatus) {
	var note = $(selector.parentNode).find('span').get(0);
	var indicator = $(selector.parentNode).find('img').get(0);
	
	$(selector.form).reset ( function () {
		selector.style.display = 'none';
		$(note).html('(begin entering a name)').css('display', 'inline');
	} );
	$(lnfield).add(fnfield).keydown ( function () {
		if (window.suggestTimeout) window.clearTimeout(suggestTimeout);
		suggestTimeout = window.setTimeout ( function () {
			if ($(fnfield).val().length + $(lnfield).val().length < 2) {
				selector.style.display = 'none';
				selector.selectedIndex = -1;
				$(note).html('(begin entering a name)').css('display', 'inline');
				return;
			}
			indicator.style.display = 'inline';
			$.post('userbyname.php', {
				firstname : fnfield.value,
				lastname : lnfield.value,
				excludestatus : excludestatus
			}, function (response) {
				var users = parseJSON(response);
				if (users && users.length) {
					selector.size = users.length < 4 ? users.length : 4;
					while (selector.firstChild) selector.removeChild(selector.firstChild);
					for (var i = 0; i < users.length; ++i) {
						option = document.createElement('option');
						option.value = users[i]['userid'];
						option.appendChild(document.createTextNode(users[i]['name'] + ' (' + users[i]['userstatus']  + ')'));
						selector.appendChild(option);
					}
					selector.firstChild.selected = true;
					note.style.display = 'none';
					selector.style.display = 'inline';
				} else {
					selector.style.display = 'none';
					$(note).html('(no matching users)').css('display', 'inline');
				}
				indicator.style.display = 'none';
			} );
		} , SUGGEST_DELAY);
	} );
}