/**
*	Ajax controller class
* @author Lawrence Walters
*/
function ELCHttp()
{
	this._request = this._getXMLHTTPRequest();
}

/**
*	url we are trying to reach
*	@see ELCHttp
*/
ELCHttp.prototype._url = undefined;

/**
*	define callback function
*	@see ELCHttp
*/
ELCHttp.prototype._callback = undefined;

/**
*	check if we're working on a previous request
*	@see ELCHttp
*/
ELCHttp.prototype._is_working = false;

/**
*	hold request object
*	@see ELCHttp
*/
ELCHttp.prototype._request = undefined;

/**
 * Standard function to get an http object, multi-browser support
*	@see ELCHttp
* @author Lawrence Walters
 */
ELCHttp.prototype._getXMLHTTPRequest = function()
{
	var xmlhttp;
	// conditional compilation stuff to run this on microsoft software
	/*@cc_on
		@if (@_jscript_version >= 5)
			try
			{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e)
			{
				try
				{
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (E)
				{
					xmlhttp = false;
				}
			}
		@else
			xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{
		try
		{
			xmlhttp = new XMLHttpRequest();
		}
		catch (e)
		{
			xmlhttp = false;
		}
	}
	return xmlhttp;
}

/**
*	standard handler for httpObject response
*	this calls an earlier defined function to handle returned XML data
*	@see ELCHttp
* @author Lawrence Walters
*/
ELCHttp.prototype._HTTPCallbackHandler = function()
{
	// "complete"
	if (this._request.readyState == 4) {
		// http OK
		if(this._request.status == 200)
		{
			// something was sent back!
			// check for error condition
			if(typeof(this._request.responseXML) == "object"
				&& this._request.responseXML != null)
			{
				if(this._callback != null)
				{
					// call real callback function here, with XML as parameter
					this._callback(this._request.responseXML);
				}
			}
			// show an error if a call back function is defined, and there is no data returned
			// (when no call back function is defined, we don't care if there is no response)
			else if(this._callback != null)
			{
				alert("Error: no XML returned from url: '" + this._url + "'\nActual data:\n" + this._request.responseText);
			}
			this._is_working = false;
		}
		else
		{
			alert("Error retrieving data via AJAX. Request response code: " + this._request.status);
		}
	}
}

/**
*	Get the data, assign a callback handler
*	@see ELCHttp
* @author Lawrence Walters
*
*	@param string	url	the url that will provide the XML data, including any GET parameters
*	@param string	callback	name of the function that will handle the XML dataset. Don't specify if you don't need to handle the response
*/
function HTTPGetData(url, callback)
{
	if (!this._is_working && this._request)
	{
		if(callback != null)
		{
			this._callback = callback;
		}
		this._url = url;
		this._request.open("GET", url, true);
		var _this = this;
		this._request.onreadystatechange = function(){_this._HTTPCallbackHandler()};
		this._is_working = true;
		this._request.send(null);
	}
	else
	{
		//todo: log some kind of error here - or decide whether to show the user this error?
		//alert("busy!");
		return false;
	}
}
ELCHttp.prototype.HTTPGetData = HTTPGetData

// Local working variables
var ajax = new ELCHttp(); // We create the HTTP Object
var ajaxUserInfo = new ELCHttp(); // We create the HTTP Object

/**
* jquery setup - when the document is ready, attach a bunch of event handlers, hide some blocks
*/
$(document).ready(function() {
	// bind the click event for the vista group id radio buttons
	$("input[id^=VISTA_GROUP_ID_]").bind("click", ToggleRosterDisplay);
});

// Local working variables
var _userInfoRequest = new Array(); // list of users to lookup via AJAX

/**
* Passes a command and gets the current menu from the server
* @author Lawrence Walters
*/
function ToggleRosterDisplay()
{
	vista_group_id = this.id.replace("VISTA_GROUP_ID_", "");

	// if this is already displayed, don't do anything.
	if($("div[id^=head_" + vista_group_id + "]:visible").length > 0)
	{
		return;
	}

	// close any other expanded classes
	if($("div[id^=head_]:visible").length > 0)
	{
		$("div[id^=head_]:visible").slideUp("slow");
		$("div[id^=roster_]:visible").slideUp("slow");
	}

	// if the roster has already been loaded, don't do anything more
	if($("div[id^=roster_" + vista_group_id + "]").children().length > 0)
	{
		$("div[id^=head_" + vista_group_id + "]").slideDown("slow");
		$("div[id^=roster_" + vista_group_id + "]").slideDown("slow");
		return;
	}

	// show the "loading" message
	$("div[id^=head_" + vista_group_id + "]").text("Loading...").slideDown("slow");

	// load the class info
	$.get("/~d-elearn/support/vista_custom/getClassEnrollment.php",
		{
			vistaGroupId: vista_group_id,
			roles: 1
		},
		function(xml)
		{
			// check if the call was successful - the xml contains a "status" element with 0 or 1
			if($('status', xml).text() == "1")
			{
				// create a table to display the results in
				html = "<table class=\"roster\">\n";

				// loop through each row - adding the student
				$("row", xml).each
				(
					function(i)
					{
						html += "<tr class=\"classList\">\n<td class=\"rosterCheckbox\"><input type=\"checkbox\" id=\"USERID-" + $("userid", this).text() + "\" name=\"USERID-" + $("userid", this).text() + "\" /></td>\n<td>" + $("userid", this).text() + "</td>\n";

						if($("user_last_name", this).text() == "")
						{
							firstName = "Loading...";
							lastName = "";
							// request the info be loaded later
							_userInfoRequest[_userInfoRequest.length] = $("userid", this).text();
						}
						else
						{
							firstName = $("user_first_name", this).text();
							lastName = $("user_last_name", this).text();
						}

						html += "<td id=\"firstName_" + $("userid", this).text() + "\">" + firstName + "</td>\n";
						html += "<td id=\"lastName_" + $("userid", this).text() + "\">" + lastName + "</td>\n";

						html += "</tr>\n";
					}
				);

				html += "</table>\n";

				$("div[id^=head_" + vista_group_id + "]").text("Class Roster:");
				$("div[id^=roster_" + vista_group_id + "]").hide().append(html).slideDown("slow");

				// load any missing user info
				// load first/last name for each student
				//alert("Setting timeout now (" + _userInfoRequest.length + " users to look up)");
				setTimeout("LoadUserInfo()", 1000);

			}
			else
			{
				alert("Error loading roster for this class:\n"
					+ $('message', xml).text()
					+ "\n" + $(xml).text());
			}

		}
	);
}

/**
* request user info - look through array _userInfoRequest to find user id's,
* then request each one via ajax, and fill in the table
* @author Lawrence Walters
*
*/
function LoadUserInfo()
{
	//alert("LoadUserInfo()");
	if(_userInfoRequest.length > 0)
	{
		var userId = _userInfoRequest[0]
		//alert("LoadUserInfo() id: " + userId + " (" + _userInfoRequest.length + " names left)");
		// remove the first item from the array
		_userInfoRequest.splice(0, 1);

		// load the user info
		$.get("/~d-elearn/support/vista_custom/getUserInfo.php",
			{ id: userId},
			function(xml)
			{
				// check if the call was successful - the xml contains a "status" element with 0 or 1
				if($('status', xml).text() == "1")
				{
					// there should be only one row, actually
					$("row", xml).each(
						function(i)
						{
							$("#firstName_" + $("nau_user_name", this).text()).text($("first_name", this).text());
							$("#lastName_" + $("nau_user_name", this).text()).text($("last_name", this).text());
						}
					);

					if(_userInfoRequest.length > 0)
					{
						setTimeout("LoadUserInfo()", 10);
					}

				}
				else
				{
					alert("Error loading roster for this class:\n"
						+ $('message', xml).text()
						+ "\n" + $(xml).text());
				}
			}
		);

	}
}

/**
* ajax callback function to add faq entry from list of potential faqs
* @author Lawrence Walters
*
*	@param string	info pipe (|) separated values for term, course prefix, course number, section and class number
*/
function SetUnlistedClass(info)
{
	ul_vista_group_id = document.getElementById("ul_vista_group_id");
	ul_term = document.getElementById("ul_term");
	ul_course_prefix = document.getElementById("ul_course_prefix");
	ul_course_number = document.getElementById("ul_course_number");
	ul_course_section = document.getElementById("ul_course_section");
	ul_class_number = document.getElementById("ul_class_number");

	if(info != "unlisted")
	{
		values = info.split("|");
		ul_term.disabled = true;
		ul_course_prefix.disabled = true;
		ul_course_number.disabled = true;
		ul_course_section.disabled = true;
		ul_class_number.disabled = true;
	}
	else
	{
		values = new Array("", "", "", "", "", "");
		ul_term.disabled = false;
		ul_course_prefix.disabled = false;
		ul_course_number.disabled = false;
		ul_course_section.disabled = false;
		ul_class_number.disabled = false;
	}

	ul_vista_group_id.value = values[0];
	ul_term.value = values[1];
	ul_course_prefix.value = values[2];
	ul_course_number.value = values[3];
	ul_course_section.value = values[4];
	ul_class_number.value = values[5];
}

/**
* submit ajax request to find a user in LDAP
* @author Lawrence Walters
*/
function UserSearch()
{
	// get search parameters
	var search_firstName = document.getElementById("search_firstName");
	var search_lastName = document.getElementById("search_lastName");
	var search_nauUserName = document.getElementById("search_nauUserName");

	// hide earlier results
	ClearUserSearchResults();

	// do ajax request
	var callback = ShowUserSearchResults;
	ajax.HTTPGetData("getUserSearch.php?firstName=" + search_firstName.value +
		"&lastName=" + search_lastName.value +
		"&nauUserName=" + search_nauUserName.value, callback);

}

/**
* ajax callback function to show users found from search
* @author Lawrence Walters
*
*	@param XMLDocument	xml with list of faq entries to remove
*/
function ShowUserSearchResults(xml)
{
	var resultArea = document.getElementById("studentSearchResults");
	var statusMessage = document.getElementById("statusMessage");
	var resultTableBody = document.getElementById("resultTableBody");

	// show result area
	resultArea.style.display = "block";

	// show the message loading
	statusMessage.childNodes[0].nodeValue = "Loading results...";

	// clear entire table
	while(resultTableBody.childNodes.length > 0)
	{
		resultTableBody.removeChild(resultTableBody.childNodes[0]);
	}

	var rows = xml.getElementsByTagName("row");
	if(rows.length > 0)
	{
		//rosterArea.style.display = "block";
		for(index = 0; index < rows.length; index++)
		{
			var row = $(rows[index]);
			// add a new row
			newRow = document.createElement("TR");
			newRow.setAttribute("class", "classList");
			// checkbox cell
			newCell = document.createElement("TD");
			newCell.setAttribute("class", "rosterCheckbox classList");

			// create checkbox
			newCheckBox = document.createElement("input");
			newCheckBox.setAttribute("type", "radio");
			newCheckBox.setAttribute("id", "NAU_USER_NAME");
			newCheckBox.setAttribute("name", "NAU_USER_NAME");
			newCheckBox.setAttribute("value", $("nau_user_name", row).text());

			// enable the submit unlisted button when clicked - yeah, this is not perfect,
			// but it provides some validation
			newCheckBox.onclick = function () {Enable('submit');}
			newCell.appendChild(newCheckBox);
			newRow.appendChild(newCell);

			// user name cell
			newCell = document.createElement("TD");
			newCell.setAttribute("class", "classList");

			newText = document.createTextNode($("nau_user_name", row).text());
			newCell.appendChild(newText);
			newRow.appendChild(newCell);

			// fisrt name cell
			newCell = document.createElement("TD");
			newCell.setAttribute("class", "classList");
			newText = document.createTextNode($("first_name", row).text());
			newCell.appendChild(newText);
			newRow.appendChild(newCell);

			// last name cell
			newCell = document.createElement("TD");
			newCell.setAttribute("class", "classList");
			newText = document.createTextNode($("last_name", row).text());
			newCell.appendChild(newText);
			newRow.appendChild(newCell);

			// add the row to the table
			resultTableBody.appendChild(newRow);
		}
		statusMessage.childNodes[0].nodeValue = "Search results: (sorted by last name)";
	}
	else
	{
		statusMessage.childNodes[0].nodeValue = "No students found matching your criteria";
	}
}

/**
* clear search results when user presses reset button
* @author Lawrence Walters
*/
function ClearUserSearchResults()
{
	var submit = document.getElementById("submit");
	if(submit)
	{
		submit.disabled = true;
	}

	var resultTableBody = document.getElementById("resultTableBody");

	// clear entire table
	while(resultTableBody.childNodes.length > 0)
	{
		resultTableBody.removeChild(resultTableBody.childNodes[0]);
	}

	var studentSearchResults = document.getElementById("studentSearchResults");
	if(studentSearchResults)
	{
		studentSearchResults.style.display = "block";
	}
	var statusMessage = document.getElementById("statusMessage");
	if(statusMessage)
	{
		statusMessage.childNodes[0].nodeValue = "Loading...";
	}
}

/**
* enable an object, given its id
* @author Lawrence Walters
* @param string	id	id of element to enable
*/
function Enable(id)
{
	var obj = document.getElementById(id);
	if(obj)
	{
		obj.disabled = false;
	}
}

/**
* uncheck a checkbox, given its id
* @author Lawrence Walters
* @param string	id	id of element to enable
*/
function UnCheck(id)
{
	var obj = document.getElementById(id);
	if(obj)
	{
		obj.checked = false;
	}
}
