var KADresult = document.getElementById("KADresult");
var quotaResult = document.getElementById("quotaResult");

// Function to pass fuzzy name to cgi to check for match.
function getKAD(name) {
	KADresult = document.getElementById("KADresult");
	quotaResult = document.getElementById("quotaResult");

	// If this is the full ThayerFS lookup page then reset drop-down menus.
	if ( document.getElementById("share-dd") ) {
		shareDD = document.getElementById("share-dd");
		dirDD = document.getElementById("dir-dd");

		shareDD.selectedIndex = 0;
		if ( dirDD.length > 1 ) {
			for ( i = dirDD.length; i > 0; i-- ) {
				dirDD.remove(i);
			}
		}

		dirDD.className = "hide";
	}

	// if no text do nothing
	if (name == '') {
		KADresult.innerHTML = '';
		KADresult.className = "empty";
		quotaResult.innerHTML = '';
		quotaResult.className = "empty";
		return;
	}

	// minor cleaning of name: if present, change unicode for left-ponting single quote (see below) back to apostrophe
	name = name.replace("\u2019", "'");

	lookupname = name;

	// Minor cleaning of name: replace any periods with a space.
	while (name.indexOf(".") != -1) {
		name = name.replace(".", " ");
		name = name.replace('/\w+/', " ");
	}
	// Minor cleaning of name: replace underscores with a space (user may have entered their KAD username)
	while (name.indexOf("_") != -1) {
		name = name.replace("_", ' ');
	}

	// Build and pass cgi url and display waiting graphic while waiting.
	var url = "http://computing.thayer.dartmouth.edu/tools/dnd_kad_lookup.cgi";
	url = url+"?fuzzyname="+name;
	quotaResult.className = "empty";
	quotaResult.innerHTML = '';
	KADresult.className = "response";
	KADresult.innerHTML = "Checking <strong>"+name+"</strong>...<br /><img class=\"waiting\" src=\"/wp-content/themes/blogtxt_46_thayer/images/waiting.gif\" />";
	http.open("GET", url, true);
	http.onreadystatechange = useHttpResponseKAD;
	http.send(null);
}

// response back from server for KAD
function useHttpResponseKAD() {   
	if (http.readyState == 4) {
		// style element for response and assign response to variable
		var fullKADresponse = http.responseText;

		var errMessage = '';

		// If response begins with '~' then output error message
		if ( fullKADresponse.indexOf("\~") == 0 ) {
			var errNum = fullKADresponse.replace("\~", '');
			switch (errNum) {
				case "err1":
					errMessage = "Only letters, numbers, space, apostrophe (\') and dash (-) are allowed.<br />Please try again.";
					break;
				case "err2":
					errMessage = "No match found for <strong>" + lookupname + "</strong>.";
					break;
				case "err3":
					errMessage = "User account is not yet in KAD. Please try again in 30 minutes.";
					break;
				default:
					errMessage = "Unknown error with lookup.";
			}
		}

		if ( errMessage ) {
			KADresult.className = "response";
			KADresult.innerHTML = errMessage;
			return;
		}
	
		// If response has '!' delimiter character then multiple matches found. process accordingly and output to original page.
		if (fullKADresponse.indexOf("!") != -1) {
			var KADmatches = new Array();
			KADmatches = fullKADresponse.split("!");
			if ( (KADmatches.length) < 25 ) {
				var listmatches = (KADmatches.length-1)+" matches found for <strong>"+lookupname+"</strong>.<br />Please select from below:<div class=\"indent1\">";
			}
			else {
				var listmatches = "More than 25 matches found for <strong>"+lookupname+"</strong>.<br />Only the first 25 are shown. Please select a match below or refine the search:<div class=\"indent1\">";
			}
	 
			for (var i = 0; i < KADmatches.length-1; i++) {
				// Replace any apostrophe with unicode for right-angled single quote. this is because apostrophe will break html for onClick method.
				KADmatches[i] = KADmatches[i].replace("'", "\u2019");
				listmatches = listmatches+"<span id=\"match"+i+"\" class=\"matchselect nohover\">"+KADmatches[i]+"</span><br />";
			}
			listmatches = listmatches+"</div>";

			KADresult.className = "response";
			KADresult.innerHTML = listmatches;

			// Initialize eventhandlers for selecting a match from the list
			for (i = 0; i < KADmatches.length-1; i++) {
				mouseOverToggle("match" + i);
				chooseMatch("match" + i, KADmatches[i]);
			}
		}
	 
		// Otherwise must be a successful single-name match!
		// Server response syntax is KAD username and full DND name separated by a '^'
		else {
			var names = [];
			names = fullKADresponse.split("\^");
			KADusername = names[0];
			fullname = names[1];

			KADresult.className = "response";
			KADresult.innerHTML = "Kiewit Active Directory username:<br /><span class=\"indent2 highlight\">"+names[0]+"</span>";

			// Replace search field with full DND name
			document.getElementById("DNDlookup").value = fullname;

			// Get quota info for the KAD username
			getQuota("home", KADusername);
		}
	}
}

// Function to populate DNDlookup field and run search when user clicks on a name from the list.
function chooseMatch(id, matchedName) {
        selectedMatch = document.getElementById(id);

        if (selectedMatch) {
                selectedMatch.onclick = function () {
                        KADresult.className = "empty";
                        KADresult.innerHTML = '';
                        document.getElementById("DNDlookup").value = matchedName;
                        getKAD(matchedName);
                }
        }
}

// Function to pass share name to cgi to build drop-down menu of qtree directories, or to pass both share and dir names to cgi to display quota info.
function getQuota(share, dir) {
        quotaResult = document.getElementById("quotaResult");
	KADresult = document.getElementById("KADresult");
        quotaURL = "http://computing.thayer.dartmouth.edu/tools/quota.cgi";
	getShare = share;
	getDir = dir;

	if ( getShare != "home" ) {
		KADresult.innerHTML = '';
		KADresult.className = "empty";
	}

	quotaResult.innerHTML = '';
	quotaResult.className = "empty";

	if ( getShare != '' ) {
                quotaURL = quotaURL + "?quiet=1&share=" + share + "&dir=" + dir;

	        http.open("GET", quotaURL, true);

		if ( getDir != '' ) {

			if ( getShare == "home" ) {
				thayerfsShare = getDir;
			} else {
				thayerfsShare = getShare + "/" + getDir;
			}

		        quotaResult.className = "response";
		        quotaResult.innerHTML = "Checking ThayerFS quota info for <strong>" + thayerfsShare + "</strong>...<br /><img class=\"waiting\" src=\"/wp-content/themes/blogtxt_46_thayer/images/waiting.gif\" />";
		}

	        http.onreadystatechange = useHttpResponseQuota;
	        http.send(null);
	}
}

// Response from server for quota.
function useHttpResponseQuota() {
	if (http.readyState == 4) {
		var fullQuotaResponse = http.responseText;

		//If response comes back "badvol" then we have an invalid share volume name
		if ( fullQuotaResponse.indexOf("badvol") != -1 ) {
			quotaResult.className = "response";
			quotaResult.InnerHTML = "Error: <strong>" + share + "</strong> is not a valid ThayerFS share."
		return;
		}

		// If response comes back "baddir" then we have an invalid directory name.
		if ( fullQuotaResponse.indexOf("baddir") != -1 ) {
			quotaResult.className = "response";
			// If share is 'home', then assume user has not been provisioned for Thayer.
			if ( getShare == "home" ) {
				quotaResult.innerHTML = "<strong>" + fullname + "</strong> does not appear to be a current Thayer user.";
                        } else {
				quotaResult.InnerHTML = "Error: <strong>" + share + "/" + dir + "</strong> is not a valid ThayerFS directory."
			}
		return;
		}

		// If query contains only a share name, create dorp-down menu with all qtrees for that share.
		if ( getShare != '' && getDir == '' ) {
			shareQtreeForm = document.getElementById("share-qtree-lookup");

			// If there is an existing directory drop-down menu, remove it.
			var dirDD = document.getElementById("dir-dd");

			// Remove any existing items from dir drop-down menu
			if ( dirDD.length > 1 ) {
				for ( i = dirDD.length; i > 0; i-- ) {
					dirDD.remove(i);
				}
			}

			// If response contains semi-colon, then all is good for processing.
			if ( fullQuotaResponse.indexOf("\;") != -1) {
				var qtreeIndex = [];
				qtreeIndex = fullQuotaResponse.split("\;");

				// Populate qtree drop-down menu.
				qtreeOption = [];
				for (i = 0; i < qtreeIndex.length; i++) {
					qtreeOption[i] = document.createElement('option');
					qtreeOption[i].setAttribute("value", qtreeIndex[i]);
					qtreeOption[i].innerHTML = qtreeIndex[i];
					dirDD.appendChild(qtreeOption[i]);
				}
			}

			dirDD.className = "show";
			dirDD.focus();

		// If there is both a share and a dir name then display quota information.
		} else if ( getShare != '' && getDir != '' ) {

			// If response contains semi-colon, then all is good for processing.
			if ( fullQuotaResponse.indexOf("\;") != -1 ) {
				var tfsquota = [];
				tfsquota = fullQuotaResponse.split("\;");

				// Convert to human-readable data.
				hr_type = ['K', 'M', 'G', 'T'];
				for (i = 0; i < 3; i++) {
					x = 0;
					while ( tfsquota[i] > 1023 ) {
						x++;
						tfsquota[i] /= 1024;
					}
					// js is buggy when it comes to rounding with floats, so do a bit of shell game to get around this.
					if ( parseFloat(tfsquota[i]) != parseInt(tfsquota[i]) ) {
						tfsquota[i] = parseFloat(tfsquota[i]);
						tfsquota[i] = tfsquota[i].toFixed(2);
					}
					tfsquota[i] += hr_type[x];
				}

				quotaResult.className = "response";

				if ( getShare == "home" ) {
					thayerfsShare = getDir;
				} else {
					thayerfsShare = getShare + "/" + getDir;
				}

				quotaResult.innerHTML = "ThayerFS quota info for <strong>" + thayerfsShare + "</strong>:<br /><div class=\"indent2\">Quota: <strong>"+tfsquota[0]+"</strong><br />Used: <strong>"+tfsquota[1]+"</strong><br />Remaining: <strong>"+tfsquota[2]+"</strong><br /><a href=\"http://wiki.thayer.dartmouth.edu/display/computing/ThayerFS+Quotas\">About ThayerFS quotas</a></div>";
			}

			// This last condition should never occur, but gotta provide some contingency.
		} else {
			quotaResult.className = "response";
			quotaResult.innerHTML = "<p>There has been been an error processing this quota request. Don't take it personally, though.</p>";
		}
	}
}

// Function to populate DNDlookup field and run search when user clicks on a name from the list.
function chooseMatch(id, matchedName) {
	selectedMatch = document.getElementById(id);

	if (selectedMatch) {
		selectedMatch.onclick = function () {
			KADresult.className = "empty";
			KADresult.innerHTML = '';
			document.getElementById("DNDlookup").value = matchedName;
			getKAD(matchedName);
		}
	}
}

// Preload image
openImg = new Image();
openImg.src = "/wp-content/themes/blogtxt_46_thayer/images/waiting.gif";
