var xhr = getXMLHttpRequest();
var sessionID = 0;
var ajaxURLBase="http://www.surewestkc.net/modules/FamilyEmail/ajax/";
var adminEmailAddress = ""; 

window.onload=requestLoginForm;

// Standard function for parsing HTTP/XML requests.
// Note: IE doesn't like UTF-8 encoding.
function parseResponse() {
	if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			var xmlDoc = xhr.responseXML;
			var rootNode = xmlDoc.getElementsByTagName("document")[0];
			var responseType = rootNode.getElementsByTagName("responseType")[0].firstChild.data;
			switch (responseType) {
				case "userLoginResult":
					userLoginBack(rootNode);
					break;
				case "loginForm":
					displayForm(rootNode.getElementsByTagName("loginFormHtml")[0].firstChild.data, "familyEmailDiv");
					break;
				case "userLogout":
					requestLoginForm();
					break;
				case "familyGroupInfo":
					displayFamilyGroupInfo(rootNode);
					break;
				case "emailAddressModifyForm":
					displayForm(rootNode.getElementsByTagName("modifyAddressForm")[0].firstChild.data, "familyEmailDiv");
					fillInModifyForm(rootNode);
					break;
				case "modifyEmailAddress":
					getFamilyGroupInfo();
					break;
				case "deleteEmailAddress":
					getFamilyGroupInfo();
					break;
				case "createdAddress":
					if (rootNode.getElementsByTagName("status")[0].firstChild.data == "fail") {
						document.getElementById("newEmailAddressError").innerHTML = rootNode.getElementsByTagName("errorMsg")[0].firstChild.data;
					} else {
						getFamilyGroupInfo();
					}
					break;
				default:
					//alert("Error..." + responseType);
					requestLoginForm();
					break;
			}
		}
	}
}

// This function returns a valid XMLHttpRequest object independenant
// of the browser used.  The first two are for different versions of IE.
// The last one is for the rest of the browsers.
function getXMLHttpRequest() {
	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} ;
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} ;
	try { return new XMLHttpRequest(); } catch(e) {} ;
}


// Thus function POSTs the username and password.
function userLogin() {
	emailAddress = document.getElementById("adminEmailAddress").value;
	password = document.getElementById("password").value;
	displayForm("Logging in....", "errorMsgSpace");
	xhr.open("POST", ajaxURLBase+"userLogin.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("password="+password+"&adminEmailAddress="+emailAddress);
}

// This function parses the result of the userLogin().
function userLoginBack(xml) {
	var authResult = xml.getElementsByTagName("authResult")[0].firstChild.data;
	if (authResult == "FALSE") {
		displayForm("Invalid Login", "errorMsgSpace");
	} else {
		adminEmailAddress = xml.getElementsByTagName("adminEmailAddress")[0].firstChild.data;
		sessionID = xml.getElementsByTagName("sessionId")[0].firstChild.data;
		getFamilyGroupInfo();
	}
	return(authResult);
}

// This function displays the login form.
function requestLoginForm() {
	adminEmailAddress = "";
	xhr.open("POST", ajaxURLBase+"displayLoginForm.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("");
}

// This function displays the 'html' at the specified 'div'.
function displayForm(html, div) {
	document.getElementById(div).innerHTML = html;
}

// This function calls the logout script.
function userLogout() {
	adminEmailAddress = "";
	xhr.open("POST", ajaxURLBase+"userLogout.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("sessionId="+sessionID);
}

function getFamilyGroupInfo() {
	if (document.getElementById("familyGroupRefreshButton") != undefined) {
		document.getElementById("familyGroupRefreshButton").disabled = true;
	}
	xhr.open("POST", ajaxURLBase+"getFamilyGroupInfo.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("adminEmailAddress="+adminEmailAddress+"&sesssionId="+sessionID);
}

function displayFamilyGroupInfo(xml) {
	displayForm(xml.getElementsByTagName("mainFormHtml")[0].firstChild.data, "familyEmailDiv");
	var memberAddresses = xml.getElementsByTagName("memberEmailAddress");
	var familyGroupTable = document.getElementById("familyGroupMembers");
	clearTable(familyGroupTable);
	var lastRow = familyGroupTable.rows.length;
	var i;
	for (i=0; i < memberAddresses.length; i++) {
		var row = familyGroupTable.insertRow(i);
		var cell = row.insertCell(0);
		var newText = document.createTextNode(memberAddresses[i].firstChild.data);
		cell.appendChild(newText);
		cell.width = "60%";
		cell = row.insertCell(1);
		newText = '<INPUT TYPE="BUTTON" VALUE="Modify" onClick="getModifyEmailAddressForm(\'';
		newText += memberAddresses[i].firstChild.data;
		newText += '\');">';
		cell.innerHTML=newText;
		cell = row.insertCell(2);
		newText = '<INPUT TYPE="BUTTON" VALUE="Delete" onClick="deleteEmailAddress(\'';
		newText += memberAddresses[i].firstChild.data;
		newText += '\');">';
		cell.innerHTML=newText;
	}
	// Treat the admin account a touch differently - don't allow it's deletion.
	var row = familyGroupTable.insertRow(i);
	var cell = row.insertCell(0);
	cell.appendChild(document.createTextNode(adminEmailAddress+ ' *Admin Account*'));
	cell.width="60%";
	cell = row.insertCell(1);
	newText = '<INPUT TYPE="BUTTON" VALUE="Modify" onClick="getModifyEmailAddressForm(\'';
	newText += adminEmailAddress;
	newText += '\');">';
	cell.innerHTML=newText;
	cell = row.insertCell(2);
	cell.innerHTML = "&nbsp;";
	
	i = memberAddresses.length+1;
	var text = "Your family group has " + i + " addresses:";
	displayForm(text, "numFgAddresses");
	displayForm(xml.getElementsByTagName("newEmailAddressForm")[0].firstChild.data, "newEmailAddressForm");

	// This displays the text box for selecting the domain for the new email address.
	// Please don't mess with the capitalization of the attributes (id and value) because IE
	// depends on the capitalization for setting the values in the DOM.  Grr.
	var newAddrDomainDiv = document.getElementById("newAddrDomainDiv");
	if (newAddrDomainDiv != undefined) {
		newSelect = document.createElement("SELECT");
		newSelect.setAttribute("id", "newAddrDomainSelect");
		var possibleDomains = xml.getElementsByTagName("possibleDomain");
		for (i=0; i < possibleDomains.length; i++) {
			newOption = document.createElement("OPTION");
			newOption.setAttribute("value", possibleDomains[i].firstChild.data);
			newText = document.createTextNode(possibleDomains[i].firstChild.data);
			newOption.appendChild(newText);
			newSelect.appendChild(newOption);
		}
		newAddrDomainDiv.appendChild(newSelect);
	}
	var test = document.getElementById("newAddrDomainSelect");
}

function clearTable(table){
	for (var i=table.rows.length; i > 0; i--) {
		table.deleteRow(0);
	}
}

function createEmailAddress() { 
	var newEmailAddress = document.getElementById("newEmailAddress").value;
	var newEmailPass = document.getElementById("newEmailPass").value;
	var newAddrDomainSelect = document.getElementById("newAddrDomainSelect");
	var newEmailDomain = newAddrDomainSelect.options[newAddrDomainSelect.selectedIndex].value;

	xhr.open("POST", ajaxURLBase+"createEmailAddress.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("newEmailAddress="+newEmailAddress+"&adminEmailAddress="+adminEmailAddress+"&newEmailPass="+newEmailPass+"&newEmailDomain="+newEmailDomain+"&sesssionId="+sessionID);
}

function fillInModifyForm(xml) {
	var field = document.getElementById("givenName");
	field.value = xml.getElementsByTagName("givenName")[0].firstChild.data;
	field = document.getElementById("surname");
	field.value = xml.getElementsByTagName("surname")[0].firstChild.data;
	field = document.getElementById("emailAddress");
	field.value = xml.getElementsByTagName("emailAddress")[0].firstChild.data;
}

function getModifyEmailAddressForm(addr) { 
	xhr.open("POST", ajaxURLBase+"getModifyEmailAddressForm.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("emailAddress="+addr+"&sesssionId="+sessionID);
}

function modifyEmailAddress() {
	var addr = document.getElementById("emailAddress").value;
	var givenName = document.getElementById("givenName").value;
	var surname = document.getElementById("surname").value;
	var newPassword = document.getElementById("newPassword").value;
	xhr.open("POST", ajaxURLBase+"modifyEmailAddress.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("emailAddress="+addr+"&givenName="+givenName+"&surname="+surname+"&newPassword="+newPassword+"&sesssionId="+sessionID);
}

function deleteEmailAddress(addr) {
	xhr.open("POST", ajaxURLBase+"deleteEmailAddress.php", true);
	xhr.onreadystatechange = parseResponse;
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xhr.send("emailAddress="+addr+"&sesssionId="+sessionID);
}


