
/*** start: suggest setup *************************************************************************/

// we only want one request out at a time
var requestInProgress = false;

// callback function for suggest_lookup.js
function do_suggest_lookup(obj, search, url_base) {

	if (requestInProgress)
		return;

	if (!search) return;
	search = search.replace(/^\s*(.*?)\s*$/, "$1");
	if (search.length < 2) {
		obj.hiddenInput.value = '';
		return;
	}
	else if (search == 'Enter Your School Name') {
		obj.input.value = '';
		obj.hiddenInput.value = '';
		return;
	}

	search = escape(search.replace(/\s/g, "+"));
	if (url_base.indexOf('?') >= 0) var join = '&';
	else var join = '?';
	var url = url_base + join + obj.input.name + "=" + search;
	var request = RequestObject();
	if (!request) {
		window.status = "Web 2.0 not supported.";
		return;
	}

	requestInProgress = true;

	request.open("GET", url, false);
	request.send(null);

	if (request.status == 200 && request.responseXML) {

		var matches = request.responseXML.getElementsByTagName('matches');

		if(matches.length == 1){
			var results = matches[0].childNodes;
			var matchFound = false;
			for (var i=0;i<results.length;i++) {
				if (results[i].hasChildNodes()) {

					var match = results[i].childNodes;

					var deptkey = '';
					var deptname = '';

					for (var j=0;j<match.length;j++) {
						if (match[j].hasChildNodes()) {

							if (match[j].nodeName == 'deptkey') {

								for (node = match[j].firstChild; node; node = node.nextSibling) {
									if (node.nodeType == 3)
										deptkey += node.nodeValue;
								}
							}
							else if (match[j].nodeName == 'deptname') {
								
								for (node = match[j].firstChild; node; node = node.nextSibling) {
									if (node.nodeType == 3)
										deptname += node.nodeValue;
								}
							}
						}
					}

					obj.add(deptname, deptkey);
					matchFound = true;
				}
			}
			obj.show();

			// if no results, make sure our selected site is cleared
			if (!matchFound && obj.hiddenInput.value != '')
				obj.hiddenInput.value = '';
		}
		/*
		else
			window.status = "No matches found.";
		*/

	}
	else
		window.status = "Failed looking up from the database";

	requestInProgress = false;
}

// add suggest script to form fields
function InstallSuggestLookup(control, control_data, list_class, url_base) {

	var url = window.location.href.replace(/^https?:\/\/([^\/]*)\/.*$/, "http://$1") + url_base;

	new IncrementalSearch(control, control_data, function (o,s) { do_suggest_lookup(o,s,url); }, function () { siteChanged(); }, list_class);
}

/*** end: suggest setup ***************************************************************************/



/*** start: select fill setup *********************************************************************/

/**
 * var provider
 * The provider number - need it to make requests to the server.
 * The php code writes out javascript that will change this to the
 * user's provider.
 */
var provider = 0;

/**
 * var webservice
 * The path (minus query var) that ajax gets xml from.
 * The php code writes out javascript that will change this to the
 * correct absolute path.
 * THIS IS AN ABSOLUTE PATH! AJAX MUST HIT THE SAME DOMAIN, SO IT IS
 * NOT INCLUDED IN THIS VARIABLE!
 */
var webservice = '';

/**
 * var change_lock_count
 * Keeps track of change locks. Use LockChanges() and UnlockChanges().
 * This enables "disabling" onchange events from doing anything, which we
 * want to do when we are manually setting the selectedIndex for a select.
 */
var change_lock_count = 0;

/**
 * void LockChanges()
 * "Lock" the selects so that if code changes the selectedIndex and if it does
 * fire an onchange event, will not do anything. Can be called multiple times,
 * but code MUST have a matching UnlockChanges() for every LockChanges().
 */
function LockChanges() {
	change_lock_count++;
}

/**
 * void UnlockChanges()
 * "Unlock" the selects so that when onchange fires it will be processed.
 */
function UnlockChanges() {
	if (change_lock_count > 0)
		change_lock_count--;
}

/**
 * bool ChangesLocked()
 * Returns true if select onchange handlers should NOT process, false if
 * there is no lock and they should therefore process.
 */
function ChangesLocked() {
	return (change_lock_count > 0);
}

/**
 * void DisableSelect()
 * Disable the select whose id is baseName+"Select". If the loading parameter is true
 * then all options will be removed from the select and one displaying "Loading..."
 * will be inserted; if loading parameter is false then the select is just left
 * on the first option.
 */
function DisableSelect(baseName, loading) {
	if (!document.getElementById) return;
	var ctl = document.getElementById(baseName + 'Select');
	if (!ctl) return;
	ctl.selectedIndex = 0;
	ctl.disabled = true;
	ctl.className = 'pulldown1';
	if (loading) {
		for (var i = ctl.options.length - 1; i >= 0; i--)
			ctl.options[i] = null;
		ctl.options[0] = new Option('Loading...', '');
	}
}

/**
 * void RestoreSelect()
 * DO NOT CALL FOR "section" - DOES NOT APPLY!
 * Restores the last good selectedIndex for the select whose
 * id is baseName+"Select".
 */
function RestoreSelect(baseName) {
	if (!document.getElementById) return;
	var ctl = document.getElementById(baseName + "Select");
	if (!ctl) return;
	LockChanges();
	ctl.selectedIndex = 0;
	UnlockChanges();
}

/**
 *
 */
function RestoreText(id) {
	if (!document.getElementById) return;
	var ctl = document.getElementById(id);
	if (!ctl) return;
	LockChanges();
	ctl.value = '';
	UnlockChanges();
}

/**
 * void DisableSemesterSelect()
 * Disable the semester select input. If the loading parameter is true
 * will display "Loading..."; otherwise will display "Select your Semester".
 */
function DisableSemesterSelect(loading) {
	DisableSelect('semester', loading);
	DisableDeliverySelect(false);
}

/**
 * void DisableDeliverySelect()
 * Disable the delivery select input. If the loading parameter is true
 * will display "Loading..."; otherwise will display "Select your Delivery I.D.".
 */
function DisableDeliverySelect(loading) {
	DisableSelect('delivery', loading);
}

/**
 * void FillSelect()
 * For the select whose id is baseName+"Select", will clear any options in the select,
 * add an option with a blank value called "Select "+capitalized(baseName)
 * (eg if baseName = "section" then the option will be "Select Section"),
 * and add options for each xml element in elems[] where the text and value
 * for the option is the text from the xml element. Eg if elems[] looks like:
 *	elems[0] = xml for "<section>1234</section>"
 *	elems[1] = xml for "<section>abcd</section>"
 * then will add options that look like (in markup):
 *		<option value='1234'>1234</option>
 *		<option value='abcd'>abcd</option>
 *
 * ELEMS[] SHOULD NOT BE EMPTY!
 *
 * However, if it is then the select will be disabled.
 */
function FillSelect(baseName, elems, optionValue, optionName, selectText) {
	if (!document.getElementById) return;
	var ctl = document.getElementById(baseName + 'Select');
	if (!ctl) return;
	for (var i = ctl.options.length-1; i >= 0; i--)
		ctl.options[i] = null;

	var idx = 0;

	if (!selectText)
		selectText = 'Select your ' + baseName.substr(0,1).toUpperCase() + baseName.substr(1, baseName.length);
	ctl.options[idx++] = new Option(selectText, '');

	// special code for 'Not Sure' option on the Delivery ID select
	if (baseName == 'delivery')
		ctl.options[idx++] = new Option('Not Sure', '*ALL');
	
	for (var i = 0; i < elems.length; i++) {
		if (elems[i].hasChildNodes()) {

			var value = '';
			var name = '';
			var results = elems[i].childNodes;

			for (var j=0;j<results.length;j++) {
				if (results[j].hasChildNodes()) {

					if (results[j].nodeName == optionValue) {
						for (node = results[j].firstChild; node; node = node.nextSibling) {
							if (node.nodeType == 3)
								value += node.nodeValue;
						}
					}
					if (results[j].nodeName == optionName) {
						
						for (node = results[j].firstChild; node; node = node.nextSibling) {
							if (node.nodeType == 3)
								name += node.nodeValue;
						}
					}
				}
			}
			name = decodeURIComponent(name);
			value = decodeURIComponent(value);
			ctl.options[idx++] = new Option(name, value);
		}
	}

	ctl.selectedIndex = 0;
	ctl.disabled = (elems.length == 0);
	ctl.className = ctl.disabled ? 'pulldown1' : 'pulldown1';
	if (!ctl.disabled) ctl.focus();
	//else alert('Failed getting the ' + baseName + ' - please try again.');
}

/**
 * void SemesterHandler()
 * This is the function called after a site change to process the
 * xml received from the server for the new site.
 */
function SemesterHandler(xml) {
	FillSelect('semester', xml.documentElement.getElementsByTagName('semester_row'), 'SEMESTER', 'SEMESTER', 'Select your Semester');
}

/**
 * void SemesterErrorHandler()
 * This is the function called after a site change when we had an error
 * getting the semester xml from the server.
 */
function SemesterErrorHandler(status, text) {
	RestoreText("siteSelect");
	FillSelect('semester', Array(), null, null, 'Select your Semester');
	DisableSemesterSelect();
	if (status == 404)
		alert('There were no semesters found for that site.');
	else
		alert('Failed getting the semesters - please try again.');

}

/**
 * void DeliveryHandler()
 * This is the function called after a semesterSelect change to process
 * the xml received from the server for the new semester.
 */
function DeliveryHandler(xml) {
	FillSelect('delivery', xml.documentElement.getElementsByTagName('delivery_row'), 'DELIVERYID', 'DELIVERYID', 'Select your Delivery I.D.');
}

/**
 * void DeliveryErrorHandler()
 * This is the function called after a semesterSelect change when we had an
 * error getting the delivery xml from the server.
 */
function DeliveryErrorHandler(status) {
	RestoreSelect("semester");
	DisableDeliverySelect();
	if (status == 404)
		alert('There were no Delivery IDs found for that semester.');
	else
		alert('Failed getting the Delivery IDs - please try again.');
}

/**
 * string MakeURL()
 * Construct a URL to get data from the server via Ajax. While semester is required,
 * the others can be null as appropriate depending on if you want a department
 * list or a delivery list.
 */
function MakeURL(site, semester) {
	var url = window.location.href.replace(/^https?:\/\/([^\/]*)\/.*$/, "http://$1") + webservice;
	if (semester) url += "?ACTION=delivery";
	else url += "?ACTION=semester";
	url += "&provider=" + provider;
	url += "&site=" + escape(site);
	if (semester) url += "&semester=" + escape(semester);
	return url;
}

/**
 * void siteChanged()
 * This is the onchange handler for siteSelect.
 */
function siteChanged() {
	if (ChangesLocked()) return;
	if (!document.getElementById) return;
	var site = document.getElementById('siteSelect');
	if (!site) return;

	if (site.value <= 0) {
		LockChanges();
		KillPendingRequest();
		DisableSemesterSelect(false);	/* Will also disable delivery select */
		UnlockChanges();
	}
	else {
		LockChanges();
		DisableSemesterSelect(true);
		UnlockChanges();
		SendRequest(MakeURL(site.value, null), SemesterHandler, SemesterErrorHandler);
	}
}

/**
 * void semesterChanged()
 * This is the onchange handler for semesterSelect.
 */
function semesterChanged() {
	if (ChangesLocked()) return;
	if (!document.getElementById) return;
	var site = document.getElementById('siteSelect');
	if (!site) return;
	var semester = document.getElementById('semesterSelect');
	if (!semester) return;
	if (semester.selectedIndex == 0) {
		LockChanges();
		KillPendingRequest();
		DisableDeliverySelect(false);
		UnlockChanges();
	}
	else {
		LockChanges();
		DisableDeliverySelect(true);
		UnlockChanges();
		SendRequest(MakeURL(site.value, semester.value), DeliveryHandler, DeliveryErrorHandler);
	}
}

function ValidateDeptSubmit(frm){
	if(!frm)
		return false;

	if(frm.site.value == '' || frm.q.value == '' || frm.q.value == 'Enter Your School Name')
		return DoFail(frm.q, 'Please Enter Your School Name');
	else if(frm.semester.value == '')
		return DoFail(frm.semester, 'Please Select Your Semester');
	else if(frm.delivery.value == '')
		return DoFail(frm.delivery, 'Please Select Your Delivery I.D.');

	return true;
}


/*** end: select fill setup ***********************************************************************/
