/***************************************************************************************************
* Date: 01/12/06
* Author: Eric Brillet (Codalworks)
* Description: General library file that holds the most common javascript functions used by other libs.
* 
*/


WINDOWDELIM = 	
"\r\n------------------------------------------------------------" + 
"------------------------------------------------------------\r\n";


/***************************************************************************************************
 * Redirects browser page to another URL.
 */
function redirectTo(newURL) {
	top.location.href = newURL;
}


/***********************************************************************************************
*
*/
function trimString(rString) {
	return rString.replace(/^\s+|\s+$/g, '');
}


/***************************************************************************************************
* 
*/
function convertCsvToArr(rCsv) {

	if (rCsv == null) {
		alert("Javascript Error: convertCsvToArr(): Null parameter passed in for input csv string: \"" + rCsv + "\".");
		return;
	}
	
	if ((trimString(rCsv) == "") || (trimString(rCsv)  == ",")) {
		return new Array();
	}

	var myChar = '';
	var myElementName = "";
	var myElementFound = false;
	var myArr = new Array();
	for (var i=0; i<rCsv.length; i++) {
		myChar = rCsv.charAt(i);
		if (myChar == "," ) {
			if (myElementName != "") {
				// Element parsed successfully, add him to array, then reset the name string for further parsing.
				myElementFound = true;
				myArr.push(myElementName);
				myElementName = "";
			}
		}
		else {
			// Continue to add character to name string.
			if (myChar != ' ') {
				myElementName += myChar;
			}
		}
	}
	
	// Add the last element, if any.
	if ((myElementName != "") && (myElementName != ",")) {
		myElementFound = true;
		myArr.push(myElementName);
	}
	
	if (!myElementFound) {
		alert("Javascript Error: convertCsvToArr(): no element found in CSV: \"" + rCsv + "\".");
		return;
	}

	return myArr;
}


/***************************************************************************************************
* Toggles the "check" on the given list of checkboxes.
* Used when selecting/deselecing entire list of memberID checkboxes.
*/
function toggleCheck(rCheckStatus, rCheckBoxList) {
	for (i = 0; i < rCheckBoxList.length; i++)
		rCheckBoxList[i].checked = rCheckStatus;
}


/***************************************************************************************************
* Given a string, returns the number of words in that string.
* Used for counting the number of words in a name to determine if it is a Chinese name.
*/
function countNumWords(rWord) {

	var wordCount = 0;
	var thisIndex = 0;
	var thisChar;
	
	// Locate the first word.
	for (var i=0; i<rWord.length; i++) {
		thisChar = rWord.charAt(i);
		if (thisChar != " " ) {
			wordCount = 1;
			thisIndex = i;
			break;
		}
	}
	
	// Locate the next words.
	var spaceFound = false;
	for (var i = thisIndex+1; i < rWord.length; i ++) {
		thisChar = rWord.charAt(i);
		if (thisChar != " " ) {
			if (spaceFound) {
				wordCount++;
				spaceFound = false;
			}
		}
		else
			spaceFound = true;
	}
	return wordCount;
}


/***************************************************************************************************
* Fills in the Badge Name field only if it is empty.
*/
function fillBadgeName(rForm) {
	
	thisFirstName = "";
	thisLastName = "";
	if (rForm.BadgeName.value == "") {
		if (rForm.FirstName.value != "")
			thisFirstName = rForm.FirstName.value;
		if (rForm.LastName.value != "")
			thisLastName = rForm.LastName.value;
		
		thisBadgeName = "";
		if (thisFirstName == "")
			thisBadgeName = thisLastName;
		else {
			if (thisLastName == "")
				thisBadgeName = thisFirstName;
			else {
				numWords = countNumWords(thisFirstName) + countNumWords(thisLastName);
				if (numWords > 2)
					thisBadgeName = thisLastName + " " + thisFirstName;
				else
					thisBadgeName = thisFirstName + " " + thisLastName;
			}
		}
		rForm.BadgeName.value = thisBadgeName;
	}
}


/***************************************************************************************************
 * Function to copy the Country from the radio buttons to the text field.
 * Used when we ask user to select a country for the event, then we fill
 * in the Country field inside the address fields.
 *
 * NOTE: Assumes the country text field is labelled as "Country".
 * Also assumes the form is labelled as "RegForm".
 */
function copyCountry(rRadioButton) {
	
	document.RegForm.Country.value = rRadioButton.value;
}


/***************************************************************************************************
 * Changes the row color for the given selected Checkbox.
 */
function switchRowColor(rSelectedCheckBox) {
	
	//alert("Hello");
	// Retrieve the table elements.
	myTableCell = rSelectedCheckBox.parentNode;
    myTableRow = myTableCell.parentNode;
	
	// Determine the Class Names for the CSS.
	myOrigClassName = myTableRow.className;
	var myClassNameHilited;
	var myClassNameNonHilited;
	

	// Determine the name of the hilited and non hilited CSS (since we may have more than one color for hilited).
	myClassNameLength = myOrigClassName.length;
	if (myClassNameLength > 7) {
		myClassNameTextObj = document.createTextNode(myOrigClassName);
		if (myClassNameTextObj.substringData(myClassNameLength-7, myClassNameLength) == "Hilited") {
			myClassNameHilited = myOrigClassName;
			myClassNameNonHilited = myClassNameTextObj.substringData(0, myClassNameLength-7);
		}
		else {
			myClassNameHilited = myOrigClassName + "Hilited";
			myClassNameNonHilited = myOrigClassName;
		}
	}
	else {
		myClassNameHilited = myOrigClassName + "Hilited";
		myClassNameNonHilited = myOrigClassName;
	}

	// Do the switch of the Cell CSS.
	if(rSelectedCheckBox.checked) {
		//myTableCell.className = myClassNameHilited;
		myTableRow.className = myClassNameHilited;
	}
	else {
		//myTableCell.className = myClassNameNonHilited;
		myTableRow.className = myClassNameNonHilited;
	}
} 


/***************************************************************************************************
 * Changes the row color for the given selected Checkbox.
 */
/*function switchRowColor(rSelectedCheckBox) {
	
	//alert("Hello");
	// Retrieve the table elements.
	myTableCell = rSelectedCheckBox.parentNode;
    myTableRow = myTableCell.parentNode;
	
	// Determine the Class Names for the CSS.
	myOrigClassName = myTableCell.className;
	var myClassNameHilited;
	var myClassNameNonHilited;

	// Determine the name of the hilited and non hilited CSS (since we may have more than one color for hilited).
	myClassNameHilited = myOrigClassName + "Hilited";
	myClassNameNonHilited = myOrigClassName;


	// Do the switch of the Cell CSS.
	if(rSelectedCheckBox.checked) {
		alert('Hello');
		myTableCell.className = myClassNameHilited;
		myTableRow.className = myClassNameHilited;
	}
	else {
		myTableCell.className = myClassNameNonHilited;
		myTableRow.className = myClassNameNonHilited;
	}
}*/


/***************************************************************************************************
 * Puts the cursor into one of the default text fields, for efficiency.
 */
function setFocus() {
	
	if (document.LoginForm != null) {
		if (document.LoginForm.Username != null) {
			document.LoginForm.Username.focus();
		}
	}
	else if (document.RegForm != null) {
		if (document.RegForm.FirstName != null) {
			document.RegForm.FirstName.focus();
		}
	}
	else if (document.SearchMemberForm != null) {
		if (document.SearchMemberForm.SearchFieldValue != null) {
			document.SearchMemberForm.SearchFieldValue.focus();
		}
	}
	else if (document.SearchEventForm != null) {
		if (document.SearchEventForm.EventName != null) {
			document.SearchEventForm.EventName.focus();
		}
	}
	else if (document.EventForm != null) {
		if (document.EventForm.EventName != null) {
			document.EventForm.EventName.focus();
		}
	}
}


/******************************************************************************
*
**/
function convertToLowerCase(rTextAreaObj) {
	
	var myLowerCaseString = rTextAreaObj.value.toLowerCase();
	rTextAreaObj.value = myLowerCaseString;
}


/***************************************************************************************************
* Toggles the given checkboxes
*/
function toggleCheckBoxes(rToggleCheckBox, rCheckBoxesName) {
	
	var myCheckStatus = rToggleCheckBox.checked;
	var myCheckBoxList = document.getElementsByName(rCheckBoxesName);
	for (i = 0; i < myCheckBoxList.length; i++)
		myCheckBoxList[i].checked = myCheckStatus;
}


/******************************************************************************
* Used in e1 Admin's Email Settings form to choose a subject string based on 
* available subjects displayed in a set of radio buttons.
**/
function processSubjectChoice(rSubjectChoiceObj) {
	
	document.EmailSettingsForm.Subject.value = rSubjectChoiceObj.value;
}


/******************************************************************************
*
**/
function clickLink(rURL) {
	
	alert(rURL);
	location.href = rURL;
}

/***************************************************************************************************
* function popUpWindow()
*/
function popUpWindow(rURLString)
{
	myWindowWidth = 700;
	myWindowHeight = 700;
	
	if (!window.focus)
		return true;
		   
	window.open(
		rURLString, 
		"Event", 
		"width="+ myWindowWidth +", height="+ myWindowHeight +", scrollbars=1, location=0, status=0, menubar=0, directories=0, resizable=1");
	
	return false;
}


/***************************************************************************************************
* function popUpWindow()
* IMPORTANT NOTE: WindowName cannot contain any space or dash, only characters.
*/
function popUpWindow(rURLString)
{
	myWindowWidth = 700;
	myWindowHeight = 700;
			   
	myNewWindow = window.open(
		rURLString, 
		'PopUp', 
		"width="+ myWindowWidth +", height="+ myWindowHeight +", scrollbars=1, location=0, status=0, menubar=0, directories=0, resizable=1");

	if (window.focus) {
		myNewWindow.focus();
	}

	return false;
}


/***************************************************************************************************
* function popUpScrollWindow()
* IMPORTANT NOTE: WindowName cannot contain any space or dash, only characters.
*/
function popUpScrollWindow(rURLString, rWindowName, rWidth, rHeight) 
{
	// First check that WindowNames does NOT contain any space.
	
	// Next open up the new window.
	myNewWindow = window.open(rURLString, rWindowName, 'height='+rHeight+',width='+rWidth+'');
	
	//the parameters rWindowName, etc cannot contain spaces, dashes (-) or other symbols/numbers
	
	if (window.focus) {
		myNewWindow.focus();
	}
	
	return false;
}


/***************************************************************************************************
* function checkFieldExists()
* Checks that the given field exists by doing a getElementById() on the given fieldname.
*/
function checkFieldExists(rFieldName) {
	
	myFieldObj = document.getElementById(rFieldName);
	if (myFieldObj == null) {
		alert("Null field referenced:" + WINDOWDELIM + rFieldName);
	}
	return myFieldObj;
}


/***************************************************************************************************
* function fillSourceData()
* Used by: Import Manager
* Fills in the text field "SourceData" in import window in e1 admin.
*/
function fillSourceData() 
{
	myNamelistObj = checkFieldExists("Namelist");
	if ((myNamelistObj != null) && (myNamelistObj.value.length > 0)) {
		// Extract SourceData name from Namelist input field.
		myNewSourceDataName = parseFilenameToSourceData(myNamelistObj.value);
		if (myNewSourceDataName == null) {
			mySourceDataObj.value = "";
		}
		else {
			mySourceDataObj = checkFieldExists("SourceData");
			if (mySourceDataObj != null) {
				mySourceDataObj.value = myNewSourceDataName;
			}
		}
	}
}


/***************************************************************************************************
* function parseFilenameToSourceData()
* Used by: Import Manager
* Checks that the given filename is a valid '.csv' filename, in order to be used by Import Manager.
*/
function parseFilenameToSourceData(rFilename) {
	
	if (rFilename == null) {
		alert("Invalid null filename.");
		return null;
	}
	
	if (rFilename.length < 5) {
		alert("Invalid filename, too short, must be 5 chars minimum: \r\n" + rFilename);
		return null;
	}

	if (rFilename.substring(rFilename.length-4, rFilename.length).toLowerCase() != '.csv') {
		alert("Invalid filename, must end with .csv: \r\n" + rFilename);
		return null;
	}

	return rFilename.substring(0, rFilename.length-4);
}


/***************************************************************************************************
* Checks if the given value is present in the given array of values.
* Useful when checking through values say in a Menu.
* Used in a function that checks each menu item against a CSV of values representing overbooked items.
*/
function isPresent(rValue, rValuesArr) {

	if (rValuesArr == null) 
		displayError('isPresent()', 'Null ValuesArr passed in, unable to check if given value is present.');

	for (var i=0; i<rValuesArr.length; i++) {
		if (rValuesArr[i] == rValue)
			return true;
	}
	return false;
}


/***************************************************************************************************
* Returns the value of the given parameter inside the URL.
* If value is not found, then returns null.
*/
function getParameter(rParameterName, rDefaultValue) {
	
	var queryString = window.location.search.substring(1).toLowerCase();
	var parameters = new Array();
	parameters = queryString.split('&');
	for(var i = 0; i < parameters.length; i++) {
		if (parameters[i].indexOf(rParameterName.toLowerCase())>=0) {
			var parameterValue = new Array();
			parameterValue = parameters[i].split('=');
			return parameterValue[1];
		}
	}
	return rDefaultValue;
}


/***************************************************************************************************
* Returns current date in dd/mm/yy format.
*/
function getDateDDMMYY() {
	
	var date = new Date();
	var d  = date.getDate();
	var day = (d < 10) ? '0' + d : d;
	var m = date.getMonth() + 1;
	var month = (m < 10) ? '0' + m : m;
	var yy = date.getYear();
	var year = (yy < 1000) ? yy + 1900 : yy;

	return day + "/" + month + "/" + year;
}




/**********************************************************************************
* Function to process the compulsory questions for this survey.
* This is necessary because IE clears the form elements after submission so we do 
* not want to submit until all questions have been asnwered.
*
* NOTE: Needs this library to work: res_code/lib_3rdparty/jquery/jquery-1.3.2.min.js
*/
function processSurvey(rElementIdArr, rElementDisplayArr) {
	
	var myErrMsg = '';
	// Loop for each element that is compulsory.
	for (var i=0; i<rElementIdArr.length; i++) {
		var myElementId = rElementIdArr[i];
		if (isValueEmptyUndefined(myElementId))  {
			myErrMsg += rElementDisplayArr[i] + "\r\n";
		}
	}
	
	// Display error, if any.
	if (myErrMsg != '') {
		myErrMsg = myErrMsg.substring(0, myErrMsg.length-2);
		alert("Sorry, please make sure you have answered the following: \r\n\r\n" + myErrMsg);	
		return false;
	}
	
	// No errors, return true to submit form.
	return true;
}


/**********************************************************************************
* Returns false if the given element ID returns an empty or undefined value.
* The given ElementID is assumed to be compulsory.
* Used by above function processSurvey()
*
* NOTE: Needs this library to work: res_code/lib_3rdparty/jquery/jquery-1.3.2.min.js
*/
function isValueEmptyUndefined(rElementId) {
	
	var myType = $('#'+rElementId).attr('type');
	if ((myType == 'text') || 
		(myType == 'textarea') || 
		(myType == 'hidden') || 
		(myType == 'select') || 
		(myType == 'select-one') || 
		(myType == 'file')) {
	
		var myVal = $('#'+rElementId).attr("value");
		return (myVal == '');
	}
	else {
		// Test for array of elements (ie checkboxes or radiobuttons).
		var myVal = $('[name=' + rElementId+ ']:checked').val();
		return !myVal;
	}
}


