var configuration = "";

/**
 * Show additional questions according to category.
 *
 * @param relevance One of "entire", "none" or "part".
 */
function showConfiguration(relevance) {
    hide('relevancewarning');  // in case it is showing
	configuration = relevance;
	if (relevance == "entire") {
		enableHierarchy(true, true);
		show('evaltablepart');
		hide('partialspecpart');
	} else if (relevance == "none") {
		enableHierarchy(false, false);
		hide('evaltablepart');
		hide('partialspecpart');
	} else if (relevance == "part") {
		enableHierarchy(true, false);
		hide('evaltablepart');
		show('partialspecpart');
	} else if (relevance == "") {
		enableHierarchy(true, false);
		hide('evaltablepart');
		hide('partialspecpart');
	} else {
		alert("Unknown parameter to showConfiguration(): " + relevance);
	}
}

/** Direct a click in the hierarchy to the right control, depending on config. */
function ctxProcessClick(lookupstr, name, aui, relationship, fromaui, fromcxn) {
	if (configuration == "entire") {
		addRow(lookupstr, name, aui, relationship, null, fromaui, fromcxn);
	} else if (configuration == "part") {
		setLowestRelevantLevel(name, aui);
		hide('betterwarning');  // in case it is showing
	}
	/* else: ignore click */
}

/** Set visibility/enabledness of the hierarchy view. */
function enableHierarchy(enable, showchildren) {
	var hier = document.getElementById('hierarchy');
	hier.style.color = enable?"black":"gray";
	var children = document.getElementById('children');
	if (children != null)
		children.style.display = showchildren?"block":"none";
}

/** Set the current suggestion for lowest relevant level. */
function setLowestRelevantLevel(name, aui) {
	document.getElementById('nearest_concept').value = name;
	document.getElementById('nearest_aui').value = aui;
}

/**
 * Generate list of relations.
 *
 * @param symptstr String describing symptom/lookup string.
 * @param concstr  String describing concept/lookup result.
 *
 * @return Associative array of (DB key) => (UI description)
 */
function generateRelations(symptstr, concstr) {
	var allContexts = new Object();
	allContexts["synonym"] = symptstr + " is a synonym of " + concstr;
	allContexts["parent_of"] = symptstr + " is parent of " + concstr;
	allContexts["child_of"] = symptstr + " is child of " + concstr;
	allContexts["is_location_of"] = symptstr + " is location of " + concstr;
	allContexts["has_location_of"] = symptstr + " has location of " + concstr;
	allContexts["part_of"] = symptstr + " is part of " + concstr;
	allContexts["has_part"] = symptstr + " has part " + concstr;
	allContexts["causes"] = symptstr + " causes " + concstr;
	allContexts["caused_by"] = symptstr + " is caused by " + concstr;
	allContexts["other"] = "Other...";
	return allContexts;
}

/**
 * Generate one option tag.
 *
 * @param value Value attribute of option tag.
 * @param text  Text to show in option list.
 *
 * @return HTML code for one option tag.
 */
function relationOption(value, text, selected) {
	return "<option value=\"" + value + "\""
		+ (selected?" selected=\"selected\"":"")
		+ ">" + text + "</option>\n";
}

/**
 * Generate whole selection list.
 *
 * @param name     Name of select tag.
 * @param symptstr String describing symptom/lookup string.
 * @param concstr  String describing concept/lookup result. 
 * @param selvalue Value that will be selected.
 */
function relationOptionList(name, rowid, symptstr, concstr, selvalue) {
	var changeHandler = "onchange=\"if (this.options[this.selectedIndex].value=='other') {replaceOptionList('"+rowid+"', '"+name+"');}\"";
	var result = "<select name=\"" + name + "\"" + changeHandler + ">\n";
	var rels = generateRelations(symptstr, concstr);
	for (var value in rels)
		result += relationOption(value, rels[value], value==selvalue);
	result += "</select>\n";
	return result;
}

/** Generate text box for entering custom relations. */
function otherRelationTextBox(name, value) {
	//alert("Call to otherRelationTextBox('" + name + "', '" + value + "')");
	var box = '<input type="hidden" name="'+name+'" value="other" />' +
		   '<input type="text" name="other_'+name+'" value="'+((value!=null)?value:"")+'" size="16" />';
	//alert(box);
	return box;
}

/**
 * Add a row to the context evaluation table.
 *
 * @param lookupstr    String [in] String that was looked up in the database (currently unused)
 * @param name         String [in] String representing the atom with aui `aui'
 * @param relationship String [in] Default relationship (@see generateRelations()).
 * @param otherRel     String [in] User-entered relation string (if `relationship' is `other'), or null.
 * @param fromaui      String [in] Key for the atom being evaluated, aui part.
 * @param fromcxn      String [in] Key for the atom being evaluated, cxn part. 
 */
function addRow(lookupstr, name, aui, relationship, otherRel, fromaui, fromcxn) {
	var table = document.getElementById('evaltable');
	var row = table.insertRow(table.rows.length);
	row.id = "eval_row_" + aui;
	
	var lookupCell = row.insertCell(0);
	lookupCell.innerHTML = lookupstr;
	
	var ctlName = "ctx_rel_" + aui + "-" + fromaui + "-" + fromcxn;
	var evalCell = row.insertCell(1);
	//alert("Figured out ctlName=" + ctlName);
	if (relationship == "other")
		evalCell.innerHTML = otherRelationTextBox(ctlName, otherRel);
	else
		evalCell.innerHTML = relationOptionList(ctlName, row.id, /*lookupstr*/ '', /*name*/ '', relationship);
	
	var conceptCell = row.insertCell(2);
	conceptCell.innerHTML = name + '<input type="hidden" name="str_'+ctlName+'" value="'+name+'" />';
	
	var deleteCell = row.insertCell(0);
	deleteCell.innerHTML = "<span style=\"cursor:pointer;\" onclick=\"deleteRow('" + row.id + "');\"><img src=\"img/delete.gif\" alt=\"delete relationship\" /></span>";
}

/** Delete the given row from the context evaluation table. */
function deleteRow(id) {
	var table = document.getElementById('evaltable');
	for (var i = 0; i < table.rows.length; i++) {
		if (table.rows[i].id == id) {
			table.deleteRow(i);
			break;
		}
	}
}

/** Replace the option list with */
function replaceOptionList(rowId, ctlName) {
	var table = document.getElementById('evaltable');
	var row = null;
	for (var i = 0; i < table.rows.length; i++) {
		if (table.rows[i].id == rowId) {
			row = table.rows[i];
			break;
		}
	}
	if (row == null) {
		alert("Could not replace option list with text box: Unable to find row!");
		return;
	}
	
	var cell = row.cells[2];
	cell.innerHTML = otherRelationTextBox(ctlName, null);
}

