﻿// ********************************
//GENERIC DECLARATIONS
// ********************************
    var colorHighlight="#C8B9D3";
	var colorNormal="#ffffff";
	var DefaultInvalidCharacters="\\//|\<\>-";  	//This content is case sensitive - used if not specified in the function call
	var InvalidCharacters="";
	var OverallValidation;						    //Global check to see if there are invalid characters found
	var ErrorMessageTouser;                         //Throughout the checks, fill this with the message that should be
	                                                // should be displayed to the user
// ********************************
// prototype.Trim Function
// ********************************
    /*
        The following adds a Trim() function to the String type.
        When called, it will remove any leading and trailling blank space.
        
        Example usage : 
            var abc = obj.value;
            abc.Trim();
    */
	String.prototype.Trim = function() { return this.replace(/^\s+|\s+$/g, '');};

// ********************************
// ValidateForm Function
// ********************************
	function ValidateForm(lstIgnoredFields, lstInvalidCharacters, lstForcedFields, lstMandatoryFields)
	{
        /*
            The ValidateForm function is a generic function that checks each elements on a form
            Forced and Ignored fields are only used with TEXTAREA and TEXTBOX elements for now
            It takes 4 arguments as follows : 
                lstIgnoredFields -> Used only of lstForcedFields is not used - this means that we look at ALL textbox and/or textarea
                lstInvalidCharacters -> list of characters to be ignored...properly escaped
                lstForcedFields -> Used to force validation of given list of fields
                lstMandatoryFields -> Check for which fields should not be empty	
                
                You should put the field ID between pipe signs to ensure we can find them easily.  I.E. "field1|field2"
                This way, "field1" will not be found if you pass "field11"
        */

		OverallValidation = true;	//Reset

		//Default to empty parameters if they are not passed
		if(typeof lstIgnoredFields == "undefined")
			lstIgnoredFields = "";
		if(typeof lstInvalidCharacters == "undefined")
			lstInvalidCharacters = DefaultInvalidCharacters;
		if(typeof lstForcedFields == "undefined")
			lstForcedFields = "";
		if(typeof lstMandatoryFields == "undefined")
			lstMandatoryFields = "";


		//Make sure we put the list of fields to be ignored to Lower Case
		lstIgnoredFields = lstIgnoredFields.toLowerCase();
		lstIgnoredFields = lstIgnoredFields.Trim();

		//Check for passed forced fields
		lstForcedFields = lstForcedFields.toLowerCase();
		lstForcedFields = lstForcedFields.Trim();
		
		//Make sure we put the list of mandatory fields to Lower Case
		lstMandatoryFields = lstMandatoryFields.toLowerCase();
		lstMandatoryFields = lstMandatoryFields.Trim();
		
		//Check for passed characters to be ignored
		if(lstInvalidCharacters != "")
		{
			InvalidCharacters = lstInvalidCharacters.Trim();
		}
		else
		{
			InvalidCharacters = DefaultInvalidCharacters;
		}

		//Check each text field to see if there are invalid characters.  If there are, highlight the field by changing the background color
		for (i=0;i<document.forms[0].elements.length;i++)
		{
			var objField = document.forms[0].elements[i];
			var errFlag = false;
			var CheckedField = false;
			if (objField.type=="text" || objField.type=="textarea"  )
			{
				//Did we get ForcedFields?
				if(lstForcedFields != "")
				{
					//We do have forced fields
					if(lstForcedFields.indexOf(objField.id.toLowerCase()) != -1)
					{
						CheckCharacterSet(objField);
						CheckedField = true;
					}
				}
				else
				{
				    //No forced fields.  Handle ignored fields
				    if(lstIgnoredFields != "")
				    {
					    if(lstIgnoredFields.indexOf(objField.id.toLowerCase()) != -1)
					    {
					        alert(objField.id);
						    CheckCharacterSet(objField);
						    CheckedField = true;
					    }
					}
				}
			 }
						
		    if(lstMandatoryFields != "")
		    {
		        if(lstMandatoryFields.indexOf(objField.id.toLowerCase()) != -1)
		        {
		            if ((objField.value == "") || (objField.value == "---- Select ----"))
		            {
		                objField.style.background = colorHighlight;
		                OverallValidation = false;
		                CheckedField = true;
		            }
		        }
		    }
            if(CheckedField==false)
            if(objField.type!="button" && objField.type!="submit")
            {
                objField.style.background= colorNormal;
            }
		}
		return(OverallValidation)

	}
// **************************************************************** ValidateForm Function


// ********************************
// CheckCharacterSet function
// ********************************
	function CheckCharacterSet(objField)
	{
        /*
            This function, given an object handle, will loop through 
            each character of text to checks for each invalid character.
            If an invalid character is found, it will return false.
            
            Possible improvement : use REGEX to check for each character
        */
		
		var errFlag=false;

		if(objField.value != "")
		{
			for(j=0; j<InvalidCharacters.length; j++)
			{
				var objChar = InvalidCharacters.charAt(j);
				if(objField.value.indexOf(objChar) > -1)
				{
					errFlag=true;
					break;
				}
			}
		}
		if(errFlag==true)
		{
			objField.style.background = colorHighlight;
			OverallValidation = false;
		}
		else
		{
			objField.style.background= colorNormal;
		}

    }
// **************************************************************** CheckCharacterSet function
        
// ********************************		
// ValidatePhone function
// ********************************
    function ValidatePhone(obj, paramHighlight, paramAlertUserOnError)
    {
	    /*
	        This function has 3 parameters as follows : 
	            obj -> the object to be checked
	            paramHighlight -> Indicates if the function should highlight the field if an error is found
	                                The highlight color is specified at the begining of this script : colorHighlight
	            paramAlertUserOnError -> Should we alert immediately the user?
	    
		    The following Regular Expression format is as follow :
		    Start at the begining of the line									^
		    Followed by zero or one open parehthesis  							\(?
		    followed by three digits, remembered as first group					(\d{3})
		    followed by zero or one close parenthesis  							\)?
		    followed by a single dash ,point, or space							[-. ]{1}
		    followed by three digits, remembered as second group  				(\d{3})
		    followed by a single dash ,point, or space							[-. ]{1}
		    followed by four digits, remembered as third group  				(\d{4})

		    The Options are as follow :
		    global seqrch for all occurences of the patern						g
		    ingore case															i
		    multiline search													m                
	    */

        //If paramHighlight is not passed, force to FALSE - else assume it is TRUE
	    if(typeof paramHighlight == "undefined")
			paramHighlight = false;
		else
		    paramHighlight = true;
		//If paramAlertUserOnError is not passed, force to TRUE - else assume FALSE
	    if(typeof paramAlertUserOnError == "undefined")
			paramAlertUserOnError = true;
		else
		    paramAlertUserOnError = false;
			
	    var sPhone = obj.value.Trim();
	    if (sPhone != '')
	    {			
	        var MyRegExp = new RegExp("^\\(?(\\d{3})\\)?[-. ]?(\\d{3})[-. ]{1}(\\d{4})", "i");
	        if (sPhone.match(MyRegExp))
	        {
		        var FormattedPhoneNumber;
		        var RegexArr = MyRegExp.exec(sPhone);
		        FormattedPhoneNumber = "(" + RegExp.$1 + ") " + RegExp.$2 + "-" + RegExp.$3;
		        obj.value = FormattedPhoneNumber;
		        obj.style.background = colorNormal;
		        return true
	        }
	        else
	        {
		        if (paramHighlight == true)
		            obj.style.background = colorHighlight;
		        
			    if (paramAlertUserOnError == true){
			        if (getLang() == "fr")
			            alert("Format invalide!\nVeuillez utiliser le format suivant : xxx-xxx-xxxx");
			        else
			            alert("Wrong format!\nPlease use the following format: xxx-xxx-xxxx");
			    }
		            //alert('<%=GetGlobalResourceObject("labels", "AlertPhoneFormat").Replace("'", "\'" )%>');
		        return false
	        }
        }
    }
// **************************************************************** ValidatePhone function
        
// ********************************		
// ValidateEmail function
// ********************************
	function ValidateEmail(obj, paramHighlight, paramAlertUserOnError)
	{
		/*
	        This function has 3 parameters as follows : 
	            obj -> the object to be checked
	            paramHighlight -> Indicates if the function should highlight the field if an error is found
	                                The highlight color is specified at the begining of this script : colorHighlight
	            paramAlertUserOnError -> Should we alert immediately the user?		
		
			The following Regular Expression format is as follow :
			Start at the begining of the line									^
			Followed one or more letters, numbers, dots, dashes, or underscore	[a-z0-9._-]*
			Followed by an @ sign												@
			Followed one or more letters, numbers, dashes, or underscore		[a-z0-9_-]*
			Start repetition between 1 and 5 times                              (?:
			Followed by a dot													\.
			Followed two or more letters 										[a-z]{2,4}
			End of repetition between 1 and 5 times                             ){1,5}
			End of line string                                                  $


			The Options are as follow :
			global seqrch for all occurences of the patern						g
			ingore case															i
			multiline search													m

		*/

	    //If paramHighlight is not passed, force to FALSE - else assume it is TRUE
	    if(typeof paramHighlight == "undefined")
			paramHighlight = false;
		else
		    paramHighlight = true;
		//If paramAlertUserOnError is not passed, force to TRUE - else assume FALSE
	    if(typeof paramAlertUserOnError == "undefined")
			paramAlertUserOnError = true;
		else
		    paramAlertUserOnError = false;

		var sEmail = obj.value.Trim();
		if (sEmail != '')
		{
		    var MyRegExp = new RegExp("^[a-z0-9._-]*@[a-z0-9_-]*(?:\.[a-z]{2,4}){1,5}$", "i");
            
		    if (sEmail.match(MyRegExp))
		    {
		        obj.style.background = colorNormal;
			    return true
		    }
		    else
		    {
			    
			    if (paramHighlight == true)
			        obj.style.background = colorHighlight;
			    if (paramAlertUserOnError == true){
			        if (getLang() == "fr")
			            alert("Adresse de courriel invalide");
			        else
			            alert("Invalid email address");
			    }
			        //alert('<%=GetGlobalResourceObject("labels", "AlertEmailFormat").Replace("'", "\'" ) %>');
			    return false
		    }
		}
	}
// **************************************************************** ValidateEmail function

// ********************************		
// RemoveScriptTags function
// ********************************
	function RemoveScriptTags(objTextbox) 
	{
	    /*
	        This function removes tag characters to prevent injection
	        Tag characters are < and >
	    */
	    objTextbox.value = objTextbox.value.replace(/<[^<|>]+?>/gi, '');
	}
// **************************************************************** RemoveScriptTags function
