/*
 * Developed for the CRIF-HCI project by Thomson Consulting International.
 * TCI, 31st Floor, Centre Point, 103 New Oxford Street, London. WC1A 1PG.
 *
 * SOURCE FILE
 *	global.js
 *
 * DESCRIPTION
 *	Contains a set of generic functions which are available to all frames.
 *
 * FUNCTIONS
 *	assert ( condition, message )
 *	getFrameByName ( name )
 *	setFrameLocation ( name, url )
 *	getOptionIndex ( ref , val )
 *	replace ( original, searchfor, replacewith )
 */

/*
 * This is a standard assertion mechanism implemented for JavaScript.
 *
 * @param condition the condition to test
 * @param message the descriptive message to display if the assertion fails
 */
function assert ( condition, message ) {
	// If the condition is not true, pop up a dialog
	if (!condition) {
		alert("FAILED ASSERTION\n\n" + message);
	}
}

/*
 * Returns a reference to a frame given the frame name.
 *
 * @param name the frame name
 * @return the frame reference; or null if no frame was found
 */
function getFrameByName ( name ) {
	// Loop through all of the frames.
	for (var i = 0; i < top.frames.length; i++) {
		// If this is the frame we want, return a reference to it.
		if (top.frames[i].name == name) {
			return top.frames[i];
		}
	}

	// If the frame was not found, return null.
	return null;
}

/*
 * Sets the location for a frame given the frame name and the new url.
 *
 * @param name the frame name
 * @param url the URL
 */
function setFrameLocation ( name, url ) {
	var frame = getFrameByName(name);
	assert(frame != null, "No such frame \'" + name + "\'");
	frame.location = url;
}

/*
 * Returns the index of the first option in a SELECT element which
 * has a given value.
 *
 * @param ref a reference to the SELECT element
 * @param val the value
 * @return the index of the option; or -1 if no such option is found
 */
function getOptionIndex ( ref , val ) {
	for (var i = 0; i < ref.length; i++) {
		if (ref.options[i].value == val) {
			return i;
		}
	}
	return -1;
}

/*
 * A string search and replace function.
 *
 * @param original the original string
 * @param searchfor the string to search for
 * @param replacewith the string to replace it with
 */
function replace ( original, searchfor, replacewith ) {
	var str = new String(original);
	var slength = searchfor.length;
	var rlength = replacewith.length;
	var index = str.indexOf(searchfor);
	while (index != -1) {
		var before = str.substring(0, index);
		var after = str.substring(index + slength);
		str = before + replacewith + after;
		index = str.indexOf(searchfor, index + rlength);
	}

	return str.toString();
}

		
