/**
 *
 * FILE NAME:    	common.js
 *
 * AUTHOR:       	Akpor Adrian Edo-Ukeh
 *
 * TYPE:         	{TYPE}
 *
 * DESCRIPTION:  	{DESCRIPTION}
 *
 * VERSION:      	1.0
 *
 * CREATED:      	01-03-2004
 *
 * LAST MODIFIED:	3-12-2004
 *
 * NOTE:         	{NOTES}
 *
*/





/**
 * This is used to switch debugging on and off
*/
var DEBUG_STATUS = 0;





/**
 * debug():
 * 
 * DESCRIPTION: Debugging function
 * 
 * PARAMETERS:
 *
 * RETURNS: 
*/ 
function debug(x){
	if(DEBUG_STATUS) alert(x);
	return;

}// end of debug















/**
 * getStyleObj():
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *  1. elem: the id of the element of the Document to be retrieved
 *  2. parent: the parent if exists!!!!!
 *
 * RETURNS: the string that points to the style property of an element depending on which browser is in use
*/ 
function getStyleObj(elem,parent){
	return getDocObj(elem,parent).style;

}// end of getStyleObj

















/**
 * getDocObj():
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *   1. elem: the id of the element of the Document to be retrieved
 *   2. parent: the parent if exist!!!!!
 * 
 * RETURNS: the string pointing to the correct document object
*/ 
function getDocObj(elem,parent){

	var docObj  = null;

	if(document.layers){
		if(parent){
			docObj = "document." + parent + ".document." + elem;
		}
		else{
			docObj = "document." + elem;
		}
	}
	else if(document.getElementById){
		docObj = "document.getElementById('" + elem + "')";
	}
	else if(document.all){
		docObj = "document.all." + elem;
	}	
	
	return eval(docObj);

}// end of getDocObj














///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////                             VALIDATION FUNCTIONS 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////











/**
 * validateForm(): Validates a form
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *   1. theForm: a reference to a document form object to be validated
 *   2. theFormElements: a reference to an array containing the name of the form elements to be validated
 *
 * RETURNS: true if the form is valid false otherwise
*/
function validateForm(theForm,theFormElements,psswdConfirmFlag,passWords){
	
	var argType = typeof  theFormElements;
	
	//First find the type of the second arguments
	if( argType == "boolean"){		
		theFormElements = theForm.elements;
	}
	
	for(var i = 0; i < theFormElements.length; i++){	
					
		var formElem = (argType == "boolean") ? theFormElements[i] : eval("document." + theForm.name + "." + theFormElements[i]);
		
		var elemType = formElem.type;
		
		if(elemType == "text" || elemType == "textarea" || elemType == "password"){
		
			if(isEmpty(trim(formElem.value))){
			
				var formElemName = formElem.name;
				formElemName     = formElemName.replace("_"," ");
				
				// Inform the user to enter a value for this form element and then return false;
				alert("Please enter a value for [ " + formElemName + " ]");
				
				formElem.focus();
				
				return false;
			}
		}
		else{
			
			if( elemType.match(/^SELECT/i) ){
			
				//Get the selected list
				var selectedList = getSelectedList(formElem);
				
				var returnFalse = true;
				
				//Now go throught the selected list 
				for(var k = 0; k < selectedList.length; k++){
				
					//Get the selectOption that is indexed by the value in selectedList[k]
					var selectOption  = formElem.options[ selectedList[k] ];
					
					//if the value of current option is set, it is then break out of the loop
					// and then set the returnFalse value to false
					if(selectOption.value){
						returnFalse = false;
						break;
					}
				}
				
				//Check the value of returnFalse
				if( returnFalse ){
					alert("You must selected a valid option from [ " + formElem.name + " ]");
					return false;
				}
			}
			else{
				//debug("Not a select element");
			}
		}
	}
	
	
	//Now see if a flag was sent to confirm the password
	if(psswdConfirmFlag){
		
		//Get references to the input elements
		var psswdElem        = eval("document." + theForm.name + "." + trim(passWords[0]));
		var psswdConfirmElem = eval("document." + theForm.name + "." + trim(passWords[1]));
		
		if(psswd.value != psswdConfirm.value){
		
			alert("The password you re-entered is not the same as you original password\nPlease re-enter your password again");
			
			//clear the value
			psswdElem.value        = "";
			psswdConfirmElem.value = "";
			
			//Bring password into focus
			psswdElem.focus();
			
			return false;
		}
		
	}	
	
	// Return true if everything is ok
	return true;
	
}//end of validateForm

















/**
 * isEmpty(): Checks if a string is empty or not
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *  1. str: The sting to be checked
 *
 * RETURNS: true if string is empty, false otherwise
*/ 
function isEmpty(str){

	if(str == null || str=="")
		return true;
	else
		return false;

}// end of isEmpty












/**
 * trim(): Trims a String passed to it
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *  1. str: A reference to a String object to be trimmed
 *
 * RETURNS: the trimmed version of the string str
*/ 
function trim(str){

	if(str != null){
		str = str.replace(/^\s+/,"");
		str = str.replace(/\s+$/,"");    
	}
  
	return str; 

}// end of trim







/**
 * toggle(): Trims a String passed to it
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *  1. id: The id of an html element to be shown or hidden
 *  2. elem: A reference to a button.
 *  3. showMsg: The string that is displayed on the button when the user wishes to show a region of the page
 *  4. hideMsg: The string that is displayed on the button when the user wishes to hide a region of the page
 *
 * RETURNS: the trimmed version of the string str
*/ 
function toggle(id,elem,showMsg,hideMsg){
	
	var elemStyle = getStyleObj(id);
	
	//This boolean indicates whether or not the id should be added to the value of the refreshForm element refreshIDs
	// IRRELEVANT BUT JUST LEAVE IT AS IT IS.
	var showOrHide;

	if(elemStyle.display == "block"){
    		
		elemStyle.display = "none";
		
		if(elem && elem.type == 'button' && showMsg) elem.value = showMsg;
		
		//Set showOrHide to false
		showOrHide = false;
		
	}
	else{
		elemStyle.display = "block";
		
		if(elem && elem.type == 'button' && hideMsg) elem.value = hideMsg;
		
		//Set showOrHide to true
		showOrHide = true;
	}

	
}//end of toggle










/**
 * openNewWindow(): Trims a String passed to it
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *  1. url: The url of the page to be opened in a new windo
 *
 * RETURNS: false
*/ 
function openNewWindow(url){
	var newWin = window.open(url,"newWindow","toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=780,height=380,resizable=yes");
	newWin.focus();
	return false;		
				
				
}//end of openNewWindow










/**
 * SetSelectedByName():
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *
 * RETURNS: 
*/ 
function SetSelectedByName(selectElem,name){
	
	var elem;
	for(var i = 0; i < selectElem.options.length; i++){
		elem = selectElem.options[i];
		
		if(elem.value == name){
			elem.selected = true;
			break;
		}
	}
	
	return;

}// end of SetSelectedByName









/**
 * fillRemoveList():
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *
 * RETURNS: nothing
*/ 
function fillRemoveList(sourceElem,targetElem){
	
	//  Get the list of selected indexes 
	var selectList = getSelectedList(sourceElem);
	
	
	// Create an array which will containing the selected index length as the key and the a value of true to 
	// indicate that the index should be ignored
	var deleteFlags = new Array(selectList.length);
	
	for(var i = 0; i < selectList.length; i++){
		deleteFlags[selectList[i]] = true;
	}
	
	
	// Create an array to hold a list of all the remaining elements
	var newsourceElem = new Array(sourceElem.length - selectList.length);
	var targetElems   = new Array(selectList.length);
	
	for(var i = 0,j = 0,k = 0; i < sourceElem.length; i++){
		
		if(!deleteFlags[i])
			newsourceElem[j++] = sourceElem[i];		
		else
			targetElems[k++]  = sourceElem[i];
				
	}

	
	fillSelectElem(targetElem,targetElems,eval(targetElem.length + selectList.length),targetElem.length);
	
	// Now re-initials the sourceElem
	fillSelectElem(sourceElem,newsourceElem,newsourceElem.length,0);
	
	return;

}// end of fillRemoveList












/**
 * getSelectedList(): Helper method to fillRemoveList. Gets a list of selected indexes from a Form Select elem
 * 
 * DESCRIPTION: Gets a list of selected indexes from a Form Select elem
 * 
 * PARAMETERS:
 *  1.selectElem: a reference to a form select object
 *
 * RETURNS: an array containing the list of selected indexes
*/ 
function getSelectedList(selectElem){

	var selectedOptions = new Array();
	var j = 0;
	
	for(var i = 0; i < selectElem.options.length; i++){
	
		var selectOption = selectElem.options[i];
		
		if(selectOption.selected)
			selectedOptions[j++] = i;
		
	}
	
	return selectedOptions;

}// end of getSelectedList











/**
 * fillSelectElem():  Helper method to fillRemoveList. 
 * 
 * DESCRIPTION: Fills a form select element of a given length (specified by one of its arguments)
 *             from a given startPos with array containing form select options object references
 * 
 * PARAMETERS:
 *  1.selectElem: a reference to the form select object element to be field
 *  2.selectElemSource: a reference to the an array containing form select options object reference from which the Select element stored in 
 *		  the variable selectElem will be filled
 *  3.selectElemLength: the length of the select element should be
 *  4.startPos: the starting position from which the select element should be filled from 
 *
 * RETURNS: nothing
*/ 
function fillSelectElem(selectElem,selectElemSource,selectElemLength,startPos){
	
	selectElem.options.length = selectElemLength;
	
	for(var i = 0, j = startPos; i < selectElemSource.length; ++i,++j){
		selectElem.options[j].text  = selectElemSource[i].text;
		selectElem.options[j].value = selectElemSource[i].value;
	}
	
	return;

}// end of fillSelectElem














/**
 * fillHidden():
 * 
 * DESCRIPTION:
 *            Note the values and text appended to the theHiddenIds and theHiddenNames are separated by a ';'
 * 
 * PARAMETERS:
 *   1. selectElem: a reference to a form select object from which the values and text of the options to be removed will be obtained
 *   2. theHiddenIds: a reference to a form hidden field object to which the values of the selected options will be appended to 
 *   3. theHiddenNames: a reference to a form hidden field object to which the text of the selected options will be appended to 
 *   4. confirmLengths (optional: This is a boolean value that forces the function to first make sure that the number of options for the
 *                      Select element object stored in the first argument selectElem is equal to the value of the last argument
 *   5. lengthForComparison (optional): This is only ever supplied if confirmLengths has been passed as an argument. This is the value to 
 *                                       which the number of options of the Select element object reference in selectElem must be equal to.
 *   6. errorMsg (optional): This is only supplied when the 4th and 5th arguments exists. It contains the error message sent out to the user 
 *                           if the number of options of the Select element object reference in selectElem  is not equal to the value in 
 *                           lengthForComparison
 * RETURNS: nothing
*/ 
function fillHidden(selectElem,hiddenIDs,hiddenNames,confirmLengths,lengthForComparison,errorMsg){

	// Get the number of options for the Select element in the variable selectElem
	var numberOfOptions = selectElem.options.length;
	
	if(confirmLengths){
		debug("Must confirm lengths no of options=" + numberOfOptions + " lengthForComparison=" + lengthForComparison);
		
		if( numberOfOptions != lengthForComparison){
			alert(errorMsg.toUpperCase());
			return false;
		}
	}
	else{
		debug("No need to confirm lengths");
	}

	
	debug("In fillHidden selectElem=" + selectElem + " name=" + selectElem.name  + " no of options=" + numberOfOptions+ 
	"\n hidden fields=" + hiddenIDs + " name=" + hiddenIDs.name + " value=" + hiddenIDs.value + 
	"\nhidden names=" + hiddenNames+ " name=" + hiddenNames.name + " value=" + hiddenNames.value);
	
	
	
	for(var i = 0;  i < numberOfOptions; i++){
	
		var glue = (i < (numberOfOptions-1)) ? ":" : "";
		
		hiddenIDs.value   += selectElem.options[i].value + glue;
		hiddenNames.value += selectElem.options[i].text + glue;
	}
	
	debug("Leaving fillHidden" + 
	"\n hidden fields=" + hiddenIDs + " name=" + hiddenIDs.name + " value=" + hiddenIDs.value + 
	"\nhidden names=" + hiddenNames+ " name=" + hiddenNames.name + " value=" + hiddenNames.value);
	
	return true;

}// end of fillHidden























/**
 * setToSelected():
 * 
 * DESCRIPTION: The second argument determines which index should be selected, if it is null then its value is set to true
 *              The type of the second argument is then obtained if it has a boolean of true then all the elements are selected
 *              if it is a number then this is converted to a one element array containing just that number.
 * 
 * PARAMETERS:
 *  1. selectElem: A reference to a Select element whose option(s) should be selected
 *  2. indexesToSelect (optional): This can be a number, an array or a boolean value of true. 
 *
 * RETURNS: 
*/ 
function setToSelected(selectElem,indexesToSelect){
	
	if(indexesToSelect == null) indexesToSelect = true;
	
	var argType = typeof indexesToSelect;
	
	// Get the type of the second argument
	if( argType == 'number' ) indexesToSelect = [indexesToSelect];
		
	else if( argType == 'boolean' ){
	
		var arraySize = selectElem.options.length;
		
		indexesToSelect = Array(arraySize);
		
		for(var i = 0; i < arraySize; i++){
			indexesToSelect[i] = i;
		}
	}
	var numberOfIndexesToSelect = indexesToSelect.length;
	
	
	for(var j = 0; j <  numberOfIndexesToSelect; j++){
		selectElem.options[indexesToSelect[j]].selected = true;	
	}
	
	return;

}// end of setToSelected












/**
 * clearSelectElements(): Resets different Select elements
 * 
 * DESCRIPTION:
 * 
 * PARAMETERS:
 *  1. fromSelectElem: A reference to a Select element which has the original list of options
 *  2. toSelectElem: A reference to a Select element to which one of more options from the Select element in the variable fromSelectElem
 *                   were placed
 *
 * RETURNS: nothing
*/ 
function clearSelectElements(fromSelectElem,toSelectElem,otherElems){


	debug(" In clearSelectElements from=" + fromSelectElem.name + " number of options=" + fromSelectElem.options.length +  
	"\n to=" + toSelectElem.name + " number of options=" + toSelectElem.options.length);
	
	
	//First select all the elements in the toSelectElem
	setToSelected(toSelectElem);
	
	
	//Now clear everything
	fillRemoveList(toSelectElem,fromSelectElem);
	
	//Now clear any elements if any
	if(otherElems != null && typeof otherElems == 'object'){
	
		for(var i = 0; i < otherElems.length; i++){
			var elem = otherElems[i];
			//Reset the value
			otherElems[i].value = "";
		}
	}
	
	debug("Leaving clearSelectElements");
	
	return;

}// end of clearSelectElements












/**
 * setRadioBox():
 * 
 * DESCRIPTION: Checks to see if there are any radio boxes set
 * 
 * PARAMETERS:
 *
 * RETURNS: 
*/ 
function setRadioBox(theForm,radioName,radioValue){

	if(radioValue != null && radioValue.length > 0){
	
		//Get the list of radioBox
		var radioElems = eval("document." + theForm.name + "." +radioName);
		
		var argType = typeof radioElems;
		
		
		var numberOfElems = radioElems.length;
		
		if( numberOfElems ){
			
			for(var i = 0; i < numberOfElems; i++){
				
				var elem = radioElems[i];
				
				// See if the value of the elem is the same as that in radioValue,
				// If there are then set its checked attribute to true and then break out of the loopd
				if(elem.value == radioValue){
					elem.checked = true;
					break;
				}
				
			}
		}
		
	}
	
	return;

}// end of setRadioBox
















//alert("Finished loading common.js");



