/**********************************************
DESCRIPTION:	Disables the rest and submit form if submit has
				been pressed to prevent double submit				
PARAMETERS:		theForm - the form name		
RETURNS:		true
**********************************************/
function disableButton(theForm) {
	theForm.submit.disabled = true;
	theForm.reset.disabled = true;		
	return true;
}
/**********************************************
DESCRIPTION: 	Enables the rest and submit form if submit has
				been pressed to prevent double submit
PARAMETERS:		theForm - the form name		
RETURNS:		true
**********************************************/
function enableButton(theForm) {
	theForm.submit.disabled = false;	
	theForm.reset.disabled = false;	
	return true;
}
/************************************************
DESCRIPTION: 	Removes leading and trailing spaces.
PARAMETERS: 	strvValue - Source string from which spaces will
  				be removed;
RETURNS: 		Source string with whitespaces removed.
*************************************************/
function trimAll( strValue ) {
	var objRegExp = /^(\s*)$/;
	//check for all spaces
	if(objRegExp.test(strValue)) {
		strValue = strValue.replace(objRegExp, '');
		if( strValue.length == 0) return strValue;
	}
	//check for leading & trailing spaces
	objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
	 
	 //remove leading and trailing whitespace characters
	if(objRegExp.test(strValue)) strValue = strValue.replace(objRegExp, '$2');
	return strValue;
}
/************************************************
DESCRIPTION:	Used to open a window with street names	
PARAMETERS:		id - id of the field to return the street name to
				app - name of the application / template files for roadlist.pl
 				lang - en or fr
RETURNS:		true
*************************************************/
function roadpick(id, app, lang)
{
		if (lang != "en" && lang !="fr") lang="en";
	
        newWin=window.open('/cgi-bin/streetname/roadlist.pl?id='+ id + '&lang='+lang + '&name='+app,'newguy',
                                        'resizable=1,scrollbars=1,width=500,height=400');
        if (window.focus) {newWin.focus()};
}
/************************************************
DESCRIPTION: 	Validates that a string is not all
  				blank (whitespace) characters.
PARAMETERS:		strValue - String to be tested for validity
RETURNS:		True if valid, otherwise false.
*************************************************/
function validateNotEmpty( strValue ) 
{
	var strTemp = strValue;
	strTemp = trimAll(strValue);	
	if(strTemp.length > 0) return true;
	return false;
}

/*******FUNCTION IS LEGACY AND DEPRICATED - USE validatePhoneNumber() INSTEAD******

DESCRIPTION:	Validates phone numbers including business extension  
PARAMETERS:		areaCode - area code
				prefix - 3 digit exchange
				extension - 
				business_ext - business extension (optional)
				lang - en or fr
				message - error message to be returned
//				required - is the field required or test only if data is inputed  
RETURNS:		Nothing if successful or returns an error message
  
*************************************************/
function validatePhone(areaCode,prefix,extension, business_ext, lang, errorEmpty, errorInvalid, local)
{
	var error="";
	var flag = "true";
	var phoneNum = areaCode + "-" + prefix + "-" + extension;
	var vaildPhoneObj = /\d\d\d-\d\d\d-\d\d\d\d/;
	// Phone extension numbers only
	var vaildBusExtObj = /^\d*$/;	
	// Numbers reserved for TV shows etc ...
	var fakeNumberObj = /\d\d\d-555-01\d\d/;
	// Directory Assistance Number
	var dirAssistObj = /\d\d\d-555-1212/;	
	var ottawaAreaCode = /^613/;
	local = local.toLowerCase();  // in case of lowercase
	// If any of the phone fields are empty - return error message
	if ((!areaCode) && (!prefix) && (!extension))
	{
		error=errorEmpty + "\n";
		flag = "false";
	}	
	if (flag == "true")
	{
	
		if(vaildPhoneObj.exec(phoneNum) == null || (areaCode =="555") || (fakeNumberObj.exec(phoneNum)) || (dirAssistObj.exec(phoneNum)))
		{
				error += errorInvalid + "\n";
		}	
		else
		{
			if (local == "y")
			{
				if (! ottawaAreaCode.test(areaCode))
				{
					if (lang == "fr")
					{
						error += "Votre indicatif régional doit se trouver dans la région d’Ottawa.\n";
					}
					else
					{
						error += "Area Code must be from the Ottawa Area.\n";
					}	
				}	
			}		
		}
		if (business_ext)
		{		
			if(vaildBusExtObj.exec(business_ext) == null)
			{
				if (lang == "fr")
				{
					error += "Veuillez entrer un numéro de poste valide. \n";
				}
				else
				{		
					error += "Please enter a valid phone extension.\n";
				}						
			}	
		}		
	}	
	return error;
}
/************************************************
DESCRIPTION:	Validates that a string a Canadian
  				postal code in 6 character format. Z5Z 5Z5 or Z5Z5Z5 or Z5Z-5Z5
  				It can also check if the postal code is an Ottawa Postal
  				Code or Not
PARAMETERS:		strValue - String to be tested for validity
				lang - en or fr
				local - flag to set for only Ottawa Postal Codes
						(loosely defined as any postal code starting with K
RETURNS:		Nothing if successful or returns an error message
*************************************************/
function validatePostalCode(strValue, lang, local) {
	var error="";
	var objRegExp  =  /^\D{1}\d{1}\D{1}[\s-]?\d{1}\D{1}\d{1}$/ ;
	var santaClausPC = /H0H\s?0H0/;
	// Not valid Postal Code Letters
	var invalidLetter = /[DFIOQU]/;
	var ottawaStation = /^[K]/;
	strValue = trimAll(strValue);
	local = local.toLowerCase();  // in case of lowercase
	strValue = strValue.toUpperCase();  // chance case to upppercase
	//check for valid Canadian Postal Code	
	if (!validateNotEmpty(strValue)) {
		if (lang == "fr") error += "Veuillez entrer votre code postal.\n";
		else error += "Please enter your postal code.\n";
		return error;
	}
	if (!objRegExp.test(strValue) || santaClausPC.test(strValue) || invalidLetter.test(strValue)) {  
		if (lang == "fr") error += "Veuillez entrer un code postal valide.\n";
		else error += "Please enter a valid postal code.\n";
		return error;
	}
	if (local == "y" && !ottawaStation.test(strValue)) {
		if (lang == "fr") error += "Votre indicatif régional doit se trouver dans la région d’Ottawa.\n";
		else error += "Postal code must be from the Ottawa Area.\n";
	}	
	return error;
}
/************************************************
DESCRIPTION:	Checks the format of the email address  
PARAMETERS:		strng - email address
				lang - en or fr
 //				required - is the field required or test only if data is inputed  
RETURNS:		Nothing if successful or returns an error message
*************************************************/
function checkEmail (strng, lang)
{
	var error="";
	var flag = "true";
	strng = trimAll(strng);
	var emailFilter=/^(\w|\-|\_|\.)+\@((\w|\-|\_)+\.)+[a-zA-Z]{2,}$/;	
	var validChars = /[a-zAZ0-9!#%*\/\?\|\^{}`~&\'\+\-\=]/;	
	if (!validateNotEmpty(strng)) {
		if (lang == "fr") return "Veuillez entrer votre adresse électronique.\n";
		else return "Please enter your email address.\n";		
	}		
		
	if (!(emailFilter.test(strng))) { 
		if (lang == "fr") return "Veuillez entrer une adresse électronique valide.\n";
		else return "Please enter a valid email address.\n";
	}
	
	if (!strng.match(validChars)) {
		//test email for illegal characters
		if (lang == "fr") return "Cette adresse électronique comporte des caractères invalides.\n";
		else return "The email address contains illegal characters.\n";		
	}	
	return error;    
}
/************************************************
DESCRIPTION:	Checks to see if the input is all numbers, alpha, or both - depeding on the switch used  
PARAMETERS: 	strng - input value
  				errorMessageInvalid - Message stating that the input failed test (ie not all numbers)
				errorMessageSize - Message stating that the minimum size has not been reached
				checkType - n (numbers only)
						  - a (alpha only)
						  - b (both)
RETURNS:		Nothing if successful or returns an error message  
*************************************************/
function checkForNumAlpha (strng, errorEmpty, errorInvalid, errorSize, size, checkType) {
	var error="";
	var validChars;
	var validNum=/^\d*$/;
	var validAlpha=/^[a-zA-Z]*$/;
	var validAlphaNum=/^\w*$/;
	strng = trimAll(strng);
	checkType = checkType.toLowerCase(); 
	/* sets the corrected regular expression */
	
	if (checkType == "n") validChars = validNum;
	else if (checkType == 'a') validChars = validAlpha;
	else validChars = validAlphaNum;
	
	if (strng.length == 0 )	return errorEmpty + "\n";
	if (! validChars.exec(strng)) return errorInvalid + "\n";		
	if (strng.length < size) return  errorSize + "\n";		
	
	return error;
	
}
/************************************************
DESCRIPTION:	Checks the drop down selection box
PARAMETERS:		strng - - input value
				message - Error Message
RETURNS:		Nothing if successful or returns an error message
*************************************************/
function checkDropDown(strng,errorMessage) {
	var error="";
	if (strng == '' || strng == '_blank')  return errorMessage + "\n";
	return error;
}
/************************************************
DESCRIPTION:	Checks the data in a input box 
PARAMETERS:		strng - - input value
				message - Error Message
				size - if this is used, there is a min size for the input box
				lang - en or fr
RETURNS:		Nothing if successful or returns an error message
*************************************************/
function checkInputBox (strng, errorEmpty, errorIlegal, errorSize, size, lang) {
	var error = "";
	strng = trimAll(strng);
	var legalChars = /^[0-9a-zA-Z\s\-\'.]+$/; // valid characters for input box
	if (!validateNotEmpty(strng)) return errorEmpty + "\n";
	
	if (!legalChars.test(strng)) return errorIlegal + "\n";		

	if (strng.length < size) return errorSize + "\n";
	
	return error;		
}
/************************************************
DESCRIPTION:	Checks to see if a radio button is selected
PARAMETERS:		checkvalue - value of radio button
				message - Error message
RETURNS:		Nothing if successful or returns an error message
*************************************************/
function checkAllRadio(theForm,radioName, errorMessage, lang) {
	list = theForm.elements[radioName];
	/* The length property is not a number so this cannot be a
	   collection and must be normalised so that the following
	   loop statement can handle it correctly. Normalisation is
	   done by making  a reference to the control currently
	   referred to by the - radioCollection - local variable
	   into the first (and only) element of a new Array object
	   and then assigning a reference to that array to the - 
	   radioCollection - local variable:
	*/	
	if(typeof list.length != "number") list = [logon_id];
	
	for (i=0; i<list.length; i++) {
		if (list[i].checked) {
			var checkvalue = list[i].value;
			break;
		} 
	}
	if (!(checkvalue)) return errorMessage + "\n";
	else return "";
}		
/************************************************
DESCRIPTION: 	Checks to see if a text area is empty
PARAMETERS:		strng - - input value
				message - Error message
				lang - en or fr
RETURNS:		Nothing if successful or returns an error message
*************************************************/
function checkTextArea(strng, errorMessage,lang) 
{
	if (strng.length == 0) return errorMessage + "\n";
	return "";	  
}
/************************************************
DESCRIPTION: 	Checks to see if the email address of from and to are the same
PARAMETERS:		to - - to field
				from - from field
				lang - en or fr
RETURNS:		Nothing if successful or returns an error message
  
*************************************************/
function sameToFrom(to,from, lang) {

	if (lang != "en" && lang !="fr") lang="en";	
	var error = "";
	to = trimAll(to);
	from = trimAll(from);
	if (to != from) return error;
	
	if (lang == "fr") return "FRENCH NEEDED\n"		
	else return "Requestor's email address cannot be the same as the Recipient email address.\n"; 

	return error;
}						
/************************************************
DESCRIPTION:	Auto tabs to the next field once the first field is full
				Taken from: http://www.acmesoffware.com/acme/default.asp  
				Modified it to accept firefox	
PARAMETERS:		eCtrl
				len - length of the field
				e
RETURNS:		true
*************************************************/
/*
Keycodes Values:
0	
8 	backspace
9 	tab
16 	shift
17 	ctrl
18 	alt
37	left arrow
38	up arrow
39	right arrow
40	down arrow
46 	delete
*/
function autoTab(eCtrl,len, e)
{
	var agent  = navigator.userAgent.toLowerCase();
	var isNN = (agent.indexOf("netscape")!=-1);
	var isIE = (agent.indexOf("msie") != -1);
	var isOpera = (agent.indexOf("opera")!=-1);
	var isFF = (agent.indexOf("firefox") != -1);
	var keyCode;
	var filter;
	if (isNN)
	{
	 keyCode = e.which;
	 filter = [0,8,9];
	}
	else
	{
	 keyCode = e.keyCode;
	 filter = [0,8,9,16,17,18,37,38,39,40,46];
	}
	if(eCtrl.value.length >= len && !containsElement(filter,keyCode))
	{
	 eCtrl.value = eCtrl.value.slice(0, len);
	 eCtrl.form[(getIndex(eCtrl)+1) % eCtrl.form.length].focus();
	}

	function containsElement(arr, ele)
	{

	 var found = false, index = 0;

	 while(!found && index < arr.length)

		if(arr[index] == ele)
		   found = true;
		else
		   index++;

	 return found;
	}

	function getIndex(eCtrl)
	{

	 var index = -1, i = 0, found = false;
	 while (i < eCtrl.form.length && index == -1)
{
		if (eCtrl.form[i] == eCtrl) index = i;
		else i++;
//		 alert(eCtrl.form[i].value);

}
	 return index;
	}
	return true;
}


/************************************************
DESCRIPTION:	Designed to change focus to an input element
PARAMETERS:		element_id - the id of the element which will receive focus
RETURNS:		false - to avoid link act
*************************************************/
function focusElement(element_id) {
	document.getElementById(element_id).focus();
	return false;
}

/************************************************
DESCRIPTION:	Validates phone numbers including business extension. Accepts spaces, no spaces, -, and . as number seperators
PARAMETERS:		phoneNum - the phone number to validate
				business_ext - business extension (optional). Just pass '' if you do not have an extension to validate
				lang - en or fr
				local - boolean (pass true or false, no quotes)
RETURNS:		String - representing the error message generated. Blank string on success
BY: 			Brad West
DATE: 			March 6, 2009  
*************************************************/
function validatePhoneNumber(phoneNum, business_ext, lang, local) {
	var error="";
	var validPhoneObj = /^\d\d\d[ -.]?\d\d\d[ -.]?\d\d\d\d$/;  		// phone number regex
	var validBusExtObj = /^\d*$/;									// Phone extension numbers only
	var fakeNumberObj = /^\d\d\d[-.\s]?555[-.\s]?\d\d\d\d$/;		// Numbers reserved for TV shows etc ...
	var fakeAreaCodeObj = /^555/;									// fake area code
	var ottawaAreaCodeObj = /^613/;									// ottawa area code
	
	/* sets default language */
	if (lang != "en" && lang !="fr") lang="en";
	/* tests the phone number */
	if (fakeNumberObj.test(phoneNum) || !validPhoneObj.test(phoneNum) || fakeAreaCodeObj.test(phoneNum)) {
		if (lang == "en") error+= "Please enter a valid phone number.\n";
		else error+= "Veuillez entrer un numéro de téléphone valide.\n"
	}
	/* now, phone number at least is assumed valid, check for local */
	if (local && !ottawaAreaCodeObj.test(phoneNum) && error=="") {
		if (lang=="en") error+= "Area Code must be from the Ottawa Area.\n";
		else error+= "Votre indicatif régional doit se trouver dans la région d’Ottawa.\n";		
	}
	/* and finally, check the extension */
	if (!validBusExtObj.test(business_ext)) {
		if (lang=="en") error+= "Please enter a valid phone extension.\n"
		else error+= "Veuillez entrer un numéro de poste valide.\n";	
	}
	return error;
}	

