// ====== nqf_standards_control functions start ====== // 

/**
 * Display a loading image while the elements of the NQF control load.
 * 
 * @param	String	id	the unique_name of the nqf_standards_control
 */
function showNQFLoading(id) {
	jQuery("#" + id + " .standards_loading").show();
}

/**
 * Hide the loading image of the NQF control.
 * 
 * @param	String	id	the unique_name of the nqf_standards_control
 */
function hideNQFLoading(id) {
	jQuery("#" + id + " .standards_loading").hide();
}

/**
 * Show/hide the main display area of the nqf_standards_control.
 * 
 * @param	String	id	the unique_name of the nqf_standards_control
 */
function toggleNQFStandards(id) {
	var elem = jQuery("#" + id + " .standard_contents_wrapper");
	if (elem.is(":visible")) {
		jQuery("#" + id + " .close_image").addClass("prehidden");
		jQuery("#" + id + " .open_image").removeClass("prehidden");
	} else {
		jQuery("#" + id + " .open_image").addClass("prehidden");
		jQuery("#" + id + " .close_image").removeClass("prehidden");
	}

	elem.slideToggle("fast");
}

/**
 * Hide the main display area of the nqf_standards_control.
 * 
 * @param	String	id	the unique_name of the nqf_standards_control
 */
function hideNQFStandards(id) {
	jQuery("#" + id + " .standard_contents_wrapper").slideUp("fast");
}

/**
 * Re-populate the sub area select box with values from the selected
 * NQF level and Area fields.
 * Called onchange by NQF Level and Area select boxes.
 * 
 * @param	String	id				the unique_name of the nqf_standards_control
 * @param	Object	titleFunc		the standard title autocomplete instance
 * @param	Object	numberFunc		the standard number autocomplete instance
 * @param	int		restrictChars	the number of characters to truncate display text to
 */
function resetNQFSubAreas(id, titleId, titleFunc, numberId, numberFunc, restrictChars) {
	// get the values for NQF level and area code
	var nqfLevel = jQuery("#" + id + " .nqf_val select").val();
	var areaCode = jQuery("#" + id + " .area_val select").val();
	
	if (nqfLevel == "" && areaCode == "") {
		jQuery("#" + id + " .sub_area_val select").html("<option value=''>- select one -</option>");
	} else {
	
		makeNQFRequest(
			id,
			"subarea",
			true,
			{ nqf_level: nqfLevel, field_code: areaCode, restrict_chars: restrictChars },
			function(data, textStatus, jqXHR) {
				if (data.code == 1) {
					// build the new sub area select box
					var elem = jQuery("#" + id + " .sub_area_val select");
					var newContents = "<option value=''>- select one -</option>";
					
					if (data.data && data.data.length) {
						for (var i = 0; i < data.data.length; i++) {
							newContents += "<option value='" + data.data[i].sub_field_code + "'>" + data.data[i].sub_field_name + "</option>";
						}
					}
					resetNQFTitle(titleId, titleFunc, data.data);
					resetNQFNumber(numberId, numberFunc, data.data);
					
					elem.html(newContents);
					
				} else {
					if (data.message) {
						alert(data.message);
					} else {
						alert(textStatus);
					}
				}
			}
		);
		
	}
}

/**
 * Update the NQF title/number autocomplete fields with values from the selected
 * NQF level and Area and Sub Area fields.
 * Called onchange by NQF Sub Area select box.
 * 
 * @param	String	id				the unique_name of the nqf_standards_control
 * @param	String	titleId			the input ID of the NQF title field
 * @param	Object	titleFunc		the standard title autocomplete instance
 * @param	String	numberId		the input ID of the NQF number field
 * @param	Object	numberFunc		the standard number autocomplete instance
 * @param	int		restrictChars	the number of characters to truncate display text to
 */
function resetNQFStandardFields(id, titleId, titleFunc, numberId, numberFunc, restrictChars) {
	// get the values for NQF level and area code and sub area code
	var nqfLevel = jQuery("#" + id + " .nqf_val select").val();
	var areaCode = jQuery("#" + id + " .area_val select").val();
	var subAreaCode = jQuery("#" + id + " .sub_area_val select").val();
	
	makeNQFRequest(
		id,
		"standards", 
		true,
		{ nqf_level: nqfLevel, field_code: areaCode, sub_field_code: subAreaCode, restrict_chars: restrictChars },
		function(data, textStatus, jqXHR) {
			if (data.code == 1) {
				
				resetNQFTitle(titleId, titleFunc, data.data);
				resetNQFNumber(numberId, numberFunc, data.data);
				
			} else {
				if (data.message) {
					alert(data.message);
				} else {
					alert(textStatus);
				}
			}
		}
	);
}

/**
 * Update the NQF title auto-complete datasource with new data.
 * 
 * @param	String	elemId		the unique_name of the nqf_standards_control
 * @param	Object	resetFunc	the autocomplete instance
 * @param	Array	newValues	the array of new data
 */
function resetNQFTitle(elemId, resetFunc, newValues) {
	var newArray = new Array();
	
	jQuery("#" + elemId).val("");
	
	if (newValues && newValues.length) {
		for (var i = 0; i < newValues.length; i++) {
			newArray[i] = [newValues[i].standard_title, newValues[i].standard_number];
		}
	}
	
	resetFunc.update(newArray);
}

/**
 * Update the NQF title auto-complete datasource with new data.
 * 
 * @param	String	elemId		the unique_name of the nqf_standards_control
 * @param	Object	resetFunc	the autocomplete instance
 * @param	Array	newValues	the array of new data
 */
function resetNQFNumber(elemId, resetFunc, newValues) {
	var newArray = new Array();
	
	jQuery("#" + elemId).val("");
	
	if (newValues && newValues.length) {
		for (var i = 0; i < newValues.length; i++) {
			newArray[i] = [newValues[i].standard_number, newValues[i].standard_title];
		}
	}
	
	resetFunc.update(newArray);
}

/**
 * Retrieve the record ID of the NQF standard with the given parameters.  Either the
 * standard title OR the standard number MUST be provided.
 * 
 * @param	String		id				the unique_name of the nqf_standards_control
 * @param	int			level			the NQF level
 * @param	int			areaCode		the area code
 * @param	int			subAreaCode		the sub area code
 * @param	String		title			the standard title
 * @param	int			number			the standard number
 * @return	int							the standard record id
 */
function getNQFRecId(id, level, areaCode, subAreaCode, title, number) {
	if (title == "" && number == "") {
		alert("Please provide either the Standard Title or the Standard Number");
		return;
	}
	
	var result;
	
	makeNQFRequest(
		id,
		"id",
		false,
		{ 
			nqf_level: level,  
			field_code: areaCode, 
			sub_field_code: subAreaCode, 
			standard_title: title, 
			standard_number: number 
		},
		function(data, textStatus, jqXHR) {
			if (data.code == 1) {
				
				result = data.data.rec_id;
				
			} else {
				if (data.message) {
					alert(data.message);
				} else {
					alert(textStatus);
				}
				result = -1;
			}
		}
	);
	
	return result;
}

/**
 * Retrieve the record ID and display text of the NQF standard with the given parameters.  Either the
 * standard title OR the standard number MUST be provided.
 * 
 * @param	String		id				the unique_name of the nqf_standards_control
 * @param	int			level			the NQF level
 * @param	int			areaCode		the area code
 * @param	int			subAreaCode		the sub area code
 * @param	String		title			the standard title
 * @param	int			number			the standard number
 * @return	Object						the standard record id and display text
 */
function getNQFRecIdAndDisplay(id, level, areaCode, subAreaCode, title, number) {
	if (title == "" && number == "") {
		alert("Please provide either the Standard Title or the Standard Number");
		return;
	}
	
	var result;
	
	makeNQFRequest(
		id,
		"id",
		false,
		{ 
			nqf_level: level,  
			field_code: areaCode, 
			sub_field_code: subAreaCode, 
			standard_title: title, 
			standard_number: number 
		},
		function(data, textStatus, jqXHR) {
			if (data.code == 1) {
				
				result = data.data;
				
			} else {
				if (data.message) {
					alert(data.message);
				} else {
					alert(textStatus);
				}
				result -1;
			}
		}
	);
	
	return result;
}

/**
 * Determines whether an NQF request is in progress or not.
 * 
 * @var	boolean
 */
var NQFRequestInProgress  = false;
/**
 * The time when the last NQF request was completed.
 * 
 * @var	Date
 */
var NQFRequestTimer = new Date();
/**
 * Perform an NQF query.
 * 
 * @param	String		id		the unique_name of the nqf_standards_control
 * @param	String		mode	the action to perform
 * @param	boolean		async	whether to perform the query async or not
 * @param	Object		data	the parameters to send
 * @param	Function	success	callback function on success
 */
function makeNQFRequest(id, mode, async, data, success) {
	if (NQFRequestInProgress) {
		alert("A request is in progress.  Please wait until it finishes.");
		return;
	} else if ((new Date()).getTime() - NQFRequestTimer.getTime() <= 500) {
		// hinder the spamming of the servers...
		alert("Slow down!  KN needs to breathe!");
		return;
	}
	showNQFLoading(id);
	NQFRequestInProgress = true;
	
	var url = "/index.php?page=ajax&cn=nqf_standards_control&mode=" + mode;
	jQuery.ajax({
		async: async,
		complete: function(jqXHR, textStatus) {
			NQFRequestTimer = new Date(); 
			NQFRequestInProgress = false; 
			hideNQFLoading(id);
		},
		data: data,
		dataType: "json",
		error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); },
		success: success,
		url: url
	});
}

// ====== nqf_standards_control functions end ====== //

// ====== metadata_search_control functions start ====== // 

/**
 * Show/Hide the appropriate year level range input fields for the given
 * year level type.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	String	newType		the new year level type's class name
 */
function changeMetadataSearchYearLevelType(uniqueName, newType) {
	var newTypeSelector = "#" + uniqueName + " ." + newType;
	jQuery("#" + uniqueName + " .year_level_wrapper").each(function() {
		var myself = jQuery(this);
		if (myself.is(":visible") && !myself.hasClass(newType)) {
			myself.slideUp("fast", function() {
				jQuery(newTypeSelector).slideDown("fast");
			});
			return;
		}
	});
}

/**
 * Show and adjust the year to level.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	String	target		the target class name
 * @param	int		value		the selected value
 */
function changeMetadataSearchYearLevelTo(uniqueName, target, value) {
	var targetSelector = "#" + uniqueName + " ." + target;
	var parentElem = jQuery(targetSelector);

	jQuery(targetSelector + " select option").each(function() {
		var myself = jQuery(this);
		if (myself.val() != "" && parseInt(myself.val()) < value) {
			myself.attr("disabled", "disabled");
			if (!myself.hasClass("disabled")) {
				myself.addClass("disabled");
			}
		} else {
			myself.attr("disabled", "").removeClass("disabled");
		}
	});

	jQuery(targetSelector + " select").val("");

	if (!parentElem.is(":visible")) {
		parentElem.slideDown("fast");
	}
}

/**
 * Show/Hide the appropriate learning area strand select box for the given
 * learning area value.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	int		laId		the selected learning area id
 */
function laChangeMetadataSearch(uniqueName, laId) {
	var elemClass = "learning_area_" + laId + "_strand";
	var strandElem = jQuery("#" + uniqueName + " ." + elemClass);

	jQuery("#" + uniqueName + " .substrand_title, #" + uniqueName + " .strand, #" + uniqueName + " .substrand").hide();

	if (strandElem.length) {
		jQuery("#" + uniqueName + " .strand_title").show();
		strandElem.show();
	} else {
		jQuery("#" + uniqueName + " .strand_title").hide();
	}
}
/**
 * Show/Hide the appropriate learning area substrand select box for the given
 * strand value.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	int		strandId	the selected strand id
 */
function strandChangeMetadataSearch(uniqueName, strandId) {
	var elemClass = "strand_" + strandId + "_substrand";
	var substrandElem = jQuery("#" + uniqueName + " ." + elemClass);

	jQuery("#" + uniqueName + " .substrand").hide();

	if (substrandElem.length) {
		jQuery("#" + uniqueName + " .substrand_title").show();
		substrandElem.show();
	} else {
		jQuery("#" + uniqueName + " .substrand_title").hide();
	}
}

/**
 * Show/Hide the appropriate Wāhanga ako ngā whenu select box for the given
 * Wāhanga ako value.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	int		waId		the selected Wāhanga ako id
 */
function waChangeMetadataSearch(uniqueName, waId) {
	var elemClass = "wa_" + waId + "_nw";
	var nwElem = jQuery("#" + uniqueName + " ." + elemClass);

	jQuery("#" + uniqueName + " .nw").hide();

	if (nwElem.length) {
		jQuery("#" + uniqueName + " .wa_na_title").show();
		nwElem.show();
	} else {
		jQuery("#" + uniqueName + " .wa_na_title").hide();
	}
}

// ====== metadata_search_control functions end ====== //

// ====== metadata_edit_control functions start ====== //

/**
 * Add a subject/topic to the list.
 * 
 * @param	String	uniqueName		the control's unique name
 * @param	String	id				the id of the autocomplete input field
 * @param	String	removeImageUrl	the URL of the remove button image
 */
function subjectTopicAddEntityMetadataEdit(uniqueName, id, removeImageUrl) {
	var word = jQuery("#" + id).val();
	word = jQuery.trim(word);
	var wordid = jQuery("#hidden_" + id).val();
	if (wordid == "") {
		// new word
		wordid = word;
	}

	if (word == "") {
		alert("Please enter the subject / topic.");
		return;
	}
	
	var duplicate = false;
	var words = jQuery("#" + uniqueName + " .subject_topic_list li");
	words.each(function(index, elem) {
		if (!duplicate && jQuery(elem).text().toLowerCase() == word.toLowerCase()) {
			duplicate = true;
			return;
		}
	});
	if (duplicate) {
		alert("\"" + word + "\" has already been entered.");
		return;
	}

	var targetName = "subject_topic_item";
	var targetListClass = "subject_topic_list";
	var uniqId = "" + Math.floor(Math.random() * 1000);

	// create list item
	var newItem = document.createElement("li");
	jQuery(newItem).addClass(targetName + "_wrapper_" + uniqId);

	// create the remove button
	var removeButton = document.createElement("img");
	jQuery(removeButton).addClass("clickable");
	removeButton.setAttribute("src", removeImageUrl);
	removeButton.setAttribute("alt", "Remove this from the list");
	removeButton.setAttribute("title", "Remove this from the list");
	YAHOO.util.Event.on(removeButton, "click", function() { removeEntityMetadataEdit(uniqueName, targetListClass, targetName + "_wrapper_" + uniqId, true); });
	newItem.appendChild(removeButton);

	// add the title
	newItem.appendChild(document.createTextNode(word));

	// create the hidden input
	var newItemInput = document.createElement("input");
	newItemInput.setAttribute("type", "hidden");
	newItemInput.setAttribute("name", targetName + "[" + wordid + "]");
	newItemInput.setAttribute("value", wordid);
	jQuery(newItemInput).addClass(targetName);
	newItem.appendChild(newItemInput);

	// add to the list
	jQuery("#" + uniqueName + " ." + targetListClass).append(newItem);
	
	// clear input fields
	jQuery("#" + id).val("");
	jQuery("#hidden_" + id).val("");
}

/**
 * Add a learning area item to the list.
 * 
 * @param	String	uniqueName		the control's unique name
 * @param	String	removeImageUrl	the URL of the removebutton image
 */
function laAddEntityMetadataEdit(uniqueName, removeImageUrl) {
	var laElem = jQuery("#" + uniqueName + " .learning_area_src");
	var laTitle = laElem.find("option:selected").text();
	var laValue = laElem.val();

	var sourceValue = laValue;
	var sourceTitle = laTitle;

	if (laValue == "") {
		alert("Please select an item from the list.");
		return;
	}

	var strandElem = jQuery("#" + uniqueName + " .learning_area_" + laValue + "_strand");
	var strandTitle;
	var strandValue;
	if (strandElem) {
		strandTitle = strandElem.find("option:selected").text();
		strandValue = strandElem.val();

		if (strandValue > 0) {

			sourceValue += "_" + strandValue;
			sourceTitle += " -> " + strandTitle;

			var subElem = jQuery("#" + uniqueName + " .strand_" + strandValue + "_substrand");
			var subTitle;
			var subValue;
			if (subElem) {
				subTitle = subElem.find("option:selected").text()
				subValue = subElem.val();

				if (subValue > 0) {
					sourceValue += "_" + subValue;
					sourceTitle += " -> " + subTitle;
				}
			}
		}
	}

	var targetName = "learning_area_item";
	var targetListClass = "learning_areas_list";

	if (!hasDuplicateMetadataEdit(uniqueName, targetName + "_wrapper_" + sourceValue)) {
		// create list item
		var newItem = document.createElement("li");
		jQuery(newItem).addClass(targetName + "_wrapper_" + sourceValue);

		// create the remove button
		var removeButton = document.createElement("img");
		jQuery(removeButton).addClass("clickable");
		removeButton.setAttribute("src", removeImageUrl);
		removeButton.setAttribute("alt", "Remove this from the list");
		removeButton.setAttribute("title", "Remove this from the list");
		YAHOO.util.Event.on(removeButton, "click", function() { removeEntityMetadataEdit(uniqueName, targetListClass, targetName + "_wrapper_" + sourceValue); });
		newItem.appendChild(removeButton);

		// add the title
		newItem.appendChild(document.createTextNode(sourceTitle));

		// create the hidden input
		var newItemInput = document.createElement("input");
		newItemInput.setAttribute("type", "hidden");
		newItemInput.setAttribute("name", targetName + "[" + sourceValue + "]");
		newItemInput.setAttribute("value", sourceValue);
		jQuery(newItemInput).addClass(targetName);
		newItem.appendChild(newItemInput);

		// add to the list
		jQuery("#" + uniqueName + " ." + targetListClass).append(newItem);

		var container = jQuery("#" + uniqueName + " ." + targetListClass).parent();
		if (!container.is(":visible")) {
			container.slideDown("fast");
		}
	} else {
		alert("This item has already been selected.");
	}
}

/**
 * Add a WA item to the list.
 * 
 * @param	String	uniqueName		the control's unique name
 * @param 	String	removeImageUrl	the URL of the remove button image
 */
function waAddEntityMetadataEdit(uniqueName, removeImageUrl) {
	var waElem = jQuery("#" + uniqueName + " .wahanga_ako_src");
	var waTitle = waElem.find("option:selected").text();
	var waValue = waElem.val();

	var sourceValue = waValue;
	var sourceTitle = waTitle;

	if (waValue == "") {
		alert("Please select an item from the list.");
		return;
	}

	var nwElem = jQuery("#" + uniqueName + " .wa_" + waValue + "_nw");
	var nwTitle;
	var nwValue;
	if (nwElem) {
		nwTitle = nwElem.find("option:selected").text();
		nwValue = nwElem.val();

		if (nwValue > 0) {

			sourceValue += "_" + nwValue;
			sourceTitle += " -> " + nwTitle;
		}
	}

	var targetName = "wa_item";
	var targetListClass = "wa_list";

	if (!hasDuplicateMetadataEdit(uniqueName, targetName + "_wrapper_" + sourceValue)) {
		// create list item
		var newItem = document.createElement("li");
		jQuery(newItem).addClass(targetName + "_wrapper_" + sourceValue);

		// create the remove button
		var removeButton = document.createElement("img");
		jQuery(removeButton).addClass("clickable");
		removeButton.setAttribute("src", removeImageUrl);
		removeButton.setAttribute("alt", "Remove this from the list");
		removeButton.setAttribute("title", "Remove this from the list");
		YAHOO.util.Event.on(removeButton, "click", function() { removeEntityMetadataEdit(uniqueName, targetListClass, targetName + "_wrapper_" + sourceValue); });
		newItem.appendChild(removeButton);

		// add the title
		newItem.appendChild(document.createTextNode(sourceTitle));

		// create the hidden input
		var newItemInput = document.createElement("input");
		newItemInput.setAttribute("type", "hidden");
		newItemInput.setAttribute("name", targetName + "[" + sourceValue + "]");
		newItemInput.setAttribute("value", sourceValue);
		jQuery(newItemInput).addClass(targetName);
		newItem.appendChild(newItemInput);

		// add to the list
		jQuery("#" + uniqueName + " ." + targetListClass).append(newItem);

		var container = jQuery("#" + uniqueName + " ." + targetListClass).parent();
		if (!container.is(":visible")) {
			container.slideDown("fast");
		}
	} else {
		alert("This item has already been selected.");
	}
}

/**
 * Add a NQF standard item to the list.
 * 
 * @param	String	uniqueName		the control's unique name
 * @param	String	targetListClass	the target list classname
 * @param	String	targetName		the target list item name
 * @param	Object	standardResult	the standard id and display
 * @param 	String	removeImageUrl	the URL of the remove button image
 */
function addNQFStandardEntityMetadataEdit(uniqueName, targetListClass, targetName, standardResult, removeImageUrl) {
	// get the source
	var sourceValue = standardResult.rec_id;
	var sourceTitle = standardResult.display_text;
	if (sourceValue == "") {
		alert("Please enter values in the Standard Title / Standard Number fields.");
		return;
	}
	if (!hasDuplicateMetadataEdit(uniqueName, targetName + "_wrapper_" + sourceValue)) {
		// create list item
		var newItem = document.createElement("li");
		jQuery(newItem).addClass(targetName + "_wrapper_" + sourceValue);

		// create the remove button
		var removeButton = document.createElement("img");
		jQuery(removeButton).addClass("clickable");
		removeButton.setAttribute("src", removeImageUrl);
		removeButton.setAttribute("alt", "Remove this from the list");
		removeButton.setAttribute("title", "Remove this from the list");
		YAHOO.util.Event.on(removeButton, "click", function() { removeEntityMetadataEdit(uniqueName, targetListClass, targetName + "_wrapper_" + sourceValue); });
		newItem.appendChild(removeButton);

		// add the title
		newItem.appendChild(document.createTextNode(sourceTitle));

		// create the hidden input
		var newItemInput = document.createElement("input");
		newItemInput.setAttribute("type", "hidden");
		newItemInput.setAttribute("name", targetName + "[" + sourceValue + "]");
		newItemInput.setAttribute("value", sourceValue);
		jQuery(newItemInput).addClass(targetName);
		newItem.appendChild(newItemInput);

		// add to the list
		jQuery("#" + uniqueName + " ." + targetListClass).append(newItem);

		var container = jQuery("#" + uniqueName + " ." + targetListClass).parent();
		if (!container.is(":visible")) {
			container.slideDown("fast");
		}
	} else {
		alert("This item has already been selected.");
	}
}

/**
 * Add an item to the list.
 * 
 * @param	String	uniqueName			the control's unique name
 * @param	String	sourceClass			the source list class
 * @param	String	targetListClass		the target list class
 * @param	String	targetName			the target item name
 * @param 	String	removeImageUrl		the URL of the remove button image
 */
function addEntityMetadataEdit(uniqueName, sourceClass, targetListClass, targetName, removeImageUrl) {
	// get the source
	var sourceList = jQuery("#" + uniqueName + " ." + sourceClass);
	var sourceValue = sourceList.val();
	var sourceTitle = sourceList.find("option:selected").text();
	if (sourceValue == "") {
		alert("Please select an item from the list.");
		return;
	}
	if (!hasDuplicateMetadataEdit(uniqueName, targetName + "_wrapper_" + sourceValue)) {
		// create list item
		var newItem = document.createElement("li");
		jQuery(newItem).addClass(targetName + "_wrapper_" + sourceValue);

		// create the remove button
		var removeButton = document.createElement("img");
		jQuery(removeButton).addClass("clickable");
		removeButton.setAttribute("src", removeImageUrl);
		removeButton.setAttribute("alt", "Remove this from the list");
		removeButton.setAttribute("title", "Remove this from the list");
		YAHOO.util.Event.on(removeButton, "click", function() { removeEntityMetadataEdit(uniqueName, targetListClass, targetName + "_wrapper_" + sourceValue); });
		newItem.appendChild(removeButton);

		// add the title
		newItem.appendChild(document.createTextNode(sourceTitle));

		// create the hidden input
		var newItemInput = document.createElement("input");
		newItemInput.setAttribute("type", "hidden");
		newItemInput.setAttribute("name", targetName + "[" + sourceValue + "]");
		newItemInput.setAttribute("value", sourceValue);
		jQuery(newItemInput).addClass(targetName);
		newItem.appendChild(newItemInput);

		// add to the list
		jQuery("#" + uniqueName + " ." + targetListClass).append(newItem);

		var container = jQuery("#" + uniqueName + " ." + targetListClass).parent();
		if (!container.is(":visible")) {
			container.slideDown("fast");
		}
	} else {
		alert("This item has already been selected.");
	}
}

/**
 * Remove a list item.
 * 
 * @param	String	uniqueName			the control's unique name
 * @param	String	targetListClass		the list class name
 * @param	String	targetItemClass		the list item class name
 * @param	boolean	dontHide			whether to hide the list if empty or not
 */
function removeEntityMetadataEdit(uniqueName, targetListClass, targetItemClass, dontHide) {
	jQuery("#" + uniqueName + " ." + targetItemClass).remove();

	if (!dontHide) {
		var elem = jQuery("#" + uniqueName + " ." + targetListClass);
		var container = elem.parent();
		if (elem.find("li").length <= 0 && container.is(":visible")) {
			container.slideUp("fast");
		}
	}
}

/**
 * Determines whether a given list item of given value already exists or not.
 *  
 * @param	String	uniqueName	the control's unique name
 * @param	String	name		the class of the input
 * @param	String	id			the value
 * @return	boolean				true if already defined, false otherwise
 */
function hasDuplicateMetadataEdit(uniqueName, listItemClass) {
	var ret = false;
	if (jQuery("#" + uniqueName + " ." + listItemClass).length) {
		ret = true;
	}
	return ret;
}

/**
 * Show/Hide appropriate learning area strands for given learning area.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	int		laId		the learning area id
 */
function laChangeMetadataEdit(uniqueName, laId) {
	var elemClass = "learning_area_" + laId + "_strand";
	var strandElem = jQuery("#" + uniqueName + " ." + elemClass);

	jQuery("#" + uniqueName + " .strand_src, #" + uniqueName + " .substrand_src, #" + uniqueName + " .strand_title, #" + uniqueName + " .substrand_title").hide();

	if (strandElem.length) {
		jQuery("#" + uniqueName + " .strand_title").css("display", "inline");
		strandElem.css("display", "inline");
	} else {
		jQuery("#" + uniqueName + " .strand_title").hide();
	}
}

/**
 * Show/Hide appropriate learning area substrands for given strand.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	int		strandId	the strand id
 */
function strandChangeMetadataEdit(uniqueName, strandId) {
	var elemClass = "strand_" + strandId + "_substrand";
	var substrandElem = jQuery("#" + uniqueName + " ." + elemClass);

	jQuery("#" + uniqueName + " .substrand_src").hide();

	if (substrandElem.length) {
		jQuery("#" + uniqueName + " .substrand_title").css("display", "inline");
		substrandElem.css("display", "inline");
	} else {
		jQuery("#" + uniqueName + " .substrand_title").hide();
	}
}

/**
 * Show/Hide appropriate Wāhanga ako ngā whenu for the given Wāhanga ako.
 * 
 * @param	Strong	uniqueName	the control's unique name
 * @param	int		waId		the wa id
 */
function waChangeMetadataEdit(uniqueName, waId) {
	var elemClass = "wa_" + waId + "_nw";
	var nwElem = jQuery("#" + uniqueName + " ." + elemClass);

	jQuery("#" + uniqueName + " .wa_nw_src, #" + uniqueName + " .wa_nw_title").hide();

	if (nwElem.length) {
		jQuery("#" + uniqueName + " .wa_nw_title").css("display", "inline");
		nwElem.css("display", "inline");
	} else {
		jQuery("#" + uniqueName + " .wa_nw_title").hide();
	}
}

/**
 * Change CC image according to the one selected.
 * 
 * @param	String	uniqueName	the control's unique name
 * @param	Element	selectElem	the <select> elemt
 */
function copyrightChangeMetadataEdit(uniqueName, selectElem) {
	var selectedElem = jQuery(selectElem).find("option:selected");
	var targetElem = jQuery("#" + uniqueName + " .copyright_src_img");
	var targetTitle = jQuery("#" + uniqueName + " .copyright_src_title");
	var targetDesc = jQuery("#" + uniqueName + " .copyright_src_desc");
	
	if (selectedElem.length) {
		if (selectedElem.hasClass("noimage")) {
			var html = "&copy;";
			if (selectedElem.val() == "") {
				html = "?";
			}
			targetElem.css({
				"background-image" : "",
				"background-color" : "#000"
			}).html(html);
		} else {
			var offsetX = selectedElem.attr("offsetx");
			var offsetY = selectedElem.attr("offsety");
			var bgImage = selectedElem.attr("bg");
			targetElem.css({
				"background-position" : offsetX + " " + offsetY,
				"background-color" : "transparent", 
				"background-image" : "url(" + bgImage + ")"
			}).html("");
		}
		targetTitle.html("<strong>Title:</strong> " + selectedElem.attr("title"));
		targetDesc.html("<strong>Description:</strong> " + selectedElem.attr("description"));
	}
}

// ====== metadata_edit_control functions end ====== //

// ====== web_review_search_control functions start ====== //

/**
 * Send the advanced search request.
 * 
 * @param	Object	tab		the reference to the web reviews tab
 * @param	String	params	the params to send
 */
function processAdvSearch(tab, params) {
	params += "&adv=Y";
	var dataSrc = tab.get("dataSrc");
	var index = dataSrc.indexOf("&search_type=");
	if (index > 0) {
		dataSrc = dataSrc.substring(0, index) + params;
	} else {
		dataSrc += params;
	}
	tab.set("dataSrc", dataSrc);
	tab.reload();
}

// ====== web_review_search_control functions end ====== //

