function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue;
} 
 
	function Translated_FT_FinalTest(SLNG) {
	var InputCollection = document.getElementsByTagName("INPUT")
  for (i = 0; i < InputCollection.length; i++) {
      if (InputCollection[i].getAttribute("mandatory") == "true" && trim(InputCollection[i].value) == "") 
      {		if(InputCollection[i].getAttribute("mandatorymessage")==null)
	        {
	        	if(SLNG.toUpperCase()=='SPANISH')
	        	{error(InputCollection[i], "De campo no puede estar en blanco");}
	        	else
	        	{error(InputCollection[i], "Field may not be blank");}
	        	InputCollection[i].value = '';
	        	InputCollection[i].select();
	        	return false;
					}
					else
					{error(InputCollection[i], InputCollection[i].getAttribute("mandatorymessage")); InputCollection[i].value = ''; InputCollection[i].select(); return false;
					}
      }
  }
  return true;
}
	function ValidateEmail(email,SLNG) {
		
	bFlag=true;
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|\s/; // invalid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/; // valid
	var str = email.value;
	if(str == ""){return bFlag;}
	var separater=";";
	
	for (i = 0; i < email.value.length; i++) 
			{
				seq = email.value.charAt(i);
				if(separater.indexOf(seq)>-1 ) 
				{		if(SLNG.toUpperCase()=='SPANISH')
	        	{alert('Varias direcciones de correo electrónico deben separarse con una coma.');}
	        	else
	        	{alert('Multiple email addresses must be separated by a comma.');}
	        	email.focus();
					  email.select();
					  bFlag=false;
					  return bFlag;
				}
	
			}
	var emailaddrs = str.split(",");
	
	for (var i=0; i < emailaddrs.length; i++) {

	  if (!reg1.test(trim(emailaddrs[i])) && reg2.test(trim(emailaddrs[i]))) {}
		else {
			if(SLNG.toUpperCase()=='SPANISH')
			{alert("\"" + emailaddrs[i] + "\" es una dirección válida de correo electrónico.");}
			else
		  {alert("\"" + emailaddrs[i] + "\" is an invalid e-mail address.");}
		  email.focus();
		  email.select();
		  bFlag=false;
		  return bFlag;
		}
	}
	
	return bFlag;
}

		  function Translated_validatePassword(obj,SLNG)
			{	var lower_even = "abcdefghijklmnopqrstuvwxyz";
				var upper = lower_even.toUpperCase();
				var numbers = "0123456789";
				var isAlpha=false;
				var isNumeric=false;
				var isUpper=false;
				var isSpecial=false;
				var validLength=true;
				var ValidStartChar=true;
				var AlertMsg ="** Password must be at least 8 characters and contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character, such as $ ! # % & ~ . , : ; / [ ] ( ) **";
				var i;
				if (obj.value!='')
				{	for (i = 0; i < obj.value.length; i++) 
					{	seq = obj.value.charAt(i);
						if (lower_even.indexOf(seq) > -1) isAlpha=true;
						if (numbers.indexOf(seq) > -1) isNumeric =true;
						if (upper.indexOf(seq) > -1) isUpper =true;
					}
					if (obj.value.length < 8) validLength=false;
					if (isAlpha != true || isUpper !=true || isNumeric != true || validLength!= true)
					{	if(SLNG.toUpperCase()=='SPANISH')
						{	AlertMsg="** La contraseña debe tener al menos 8 caracteres y que contenga al menos una letra mayúscula, una letra minúscula, un número y un carácter especial, tales como # $% & ~,:;!. / [] () **";}
						else
						{AlertMsg="** Password must be at least 8 characters and contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character, such as $ ! # % & ~ . , : ; / [ ] ( ) **";}
						if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
						{alert(AlertMsg);}
						else
						{alert(AlertMsg);}
						
						obj.select();
						return false;
					}
			}
			return true;
			}	
		  
		  
	function Translated_validatePasswordHUD(obj,SLNG)
			{	var lower_even = "abcdefghijklmnopqrstuvwxyz";
				var upper = lower_even.toUpperCase();
				var numbers = "0123456789";
				var isAlpha=false;
				var isNonAlpha=false;
				var isNumeric=false;
				var isUpper=false;
				var isSpecial=false;
				var validLength=true;
				var ValidStartChar=true;
				var isBlank=true;
				var i;
				
				var sValidationMsg
				var sValidationSpaceMsg
				if(SLNG.toUpperCase()=='SPANISH')
				{
					sValidationMsg='** La contraseña debe tener al menos 8 caracteres y que contenga al menos una letra mayúscula, una letra minúscula, un número y un carácter especial, tales como # $% & ~,:;!. / [] ()  **'
				}
				else
				{
					sValidationMsg='** Password must be at least 8 characters and contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character, such as $ ! # % & ~ . , : ; / [ ] ( ) **'
				}
			
			
			 if(SLNG.toUpperCase()=='SPANISH')
				{
					sValidationSpaceMsg='La contraseña no debe contener un espacio en blanco.'															
				}
				else
				{
					sValidationSpaceMsg='Password should not contain spaces.'
				}
			
			
			if (obj.value!='')
			{
					for (i = 0; i < obj.value.length; i++) 
					{
						
						seq = obj.value.charAt(i);
						if (	seq == ' ') isBlank = false;
						if (lower_even.indexOf(seq) > -1) isAlpha=true;
								
						if (numbers.indexOf(seq) > -1) isNumeric =true;
							
						if (upper.indexOf(seq) > -1) isUpper =true;												
						
	if (seq== '~' || seq== '`' || seq== ' ' || seq== '-' || seq== '_' || seq== ':' || seq== ';' || seq== '/' || seq== '{' || seq== '}' || seq== '[' || seq== ']' || seq== '|' || seq== '+' || seq== '=' || seq== '*' || seq== '&' || seq== '%' || seq== '$' || seq== '@' || seq== '#' || seq== ',' || seq== '.' || seq== '>' || seq== '<' || seq== '(' || seq== ')' || seq== '!' || seq== '^' || seq== '\\')
	{
		isNonAlpha = true;
	}
	}
	
				if(isBlank != true)
					{
						if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
						{							
						alert(sValidationSpaceMsg);
					}
					else
					{
						alert(sValidationSpaceMsg);
						}
						obj.select();
						return false;				
					}
								
					if (obj.value.length < 8) validLength=false;
												
					if (isAlpha != true || isUpper !=true || isNumeric != true || validLength != true || isNonAlpha != true )
					{
						if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
						{
							alert(sValidationMsg);
						}
						else
						{
							alert(sValidationMsg);
						}
						
						obj.select();
						return false;
					}
			}
					
					return true;
			}	  
		  
function validatePasswordHUD(obj)
			{			
				var lower_even = "abcdefghijklmnopqrstuvwxyz";
				var upper = lower_even.toUpperCase();
				var numbers = "0123456789";
				var isAlpha=false;
				var isNonAlpha=false;
				var isNumeric=false;
				var isUpper=false;
				var isSpecial=false;
				var validLength=true;
				var ValidStartChar=true;
				var i;
			
			if (obj.value!='')
			{
					for (i = 0; i < obj.value.length; i++) 
					{
						
						seq = obj.value.charAt(i);
																
						if (lower_even.indexOf(seq) > -1) isAlpha=true;
								
						if (numbers.indexOf(seq) > -1) isNumeric =true;
							
						if (upper.indexOf(seq) > -1) isUpper =true;												
						
	if (seq== '~' || seq== '`' || seq== ' ' || seq== '-' || seq== '_' || seq== ':' || seq== ';' || seq== '/' || seq== '{' || seq== '}' || seq== '[' || seq== ']' || seq== '|' || seq== '+' || seq== '=' || seq== '*' || seq== '&' || seq== '%' || seq== '$' || seq== '@' || seq== '#' || seq== ',' || seq== '.' || seq== '>' || seq== '<' || seq== '(' || seq== ')' || seq== '!' || seq== '^' || seq== '\\')
	{
		isNonAlpha = true;
	}


					}
								
					if (obj.value.length < 8) validLength=false;
												
					if (isAlpha != true || isUpper !=true || isNumeric != true || validLength != true || isNonAlpha != true)
					{
						if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
						{
							alert('** Password must be at least 8 characters and contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character, such as $ ! # % & ~ . , : ; / [ ] ( ) **');
						}
						else
						{
							alert('** Password must be at least 8 characters and contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character, such as $ ! # % & ~ . , : ; / [ ] ( ) **');
						}
						
						obj.select();
						return false;
					}
			}
					
					return true;
			}	
			
			
			
			function validateUsername(obj) 
			{
				if (obj.value == "")
				 {
					alert('You must enter a User Name.');
						obj.select();
					return false;
				 } 
				else if ((obj.value.length < 5) || (obj.value.length > 50)) 
				{
					alert('User Name should contain minimum 5 or maximum 50 characters.');
					obj.select();
					return false;
				} 
				 else 
				 {
					return true;
				}
			}
			
			
//HUD CaptchaImage function
			function HUDCaptchaImage()
			{
				var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

				var length=5;

				
					if (! length) {

						length = Math.floor(Math.random() * chars.length);
					}
				var str = '';

					for (var i = 0; i < length; i++) {

						str += chars[Math.floor(Math.random() * chars.length)];
					}

					strCaptcha = str;
					if (document.getElementById("theImg") != null)
					{
					document.getElementById("theImg").src="PortalHUDGenerateCaptchaImage.aspx?str=" +strCaptcha;
					}
			}

//HUD CaptchaImage validation function

 		function fnCheckRandom(txtCaptcha)
			{			
				if(txtCaptcha.value==strCaptcha)
				{
					return true;
					//return false;
				}
				else
				{
					 if(txtCaptcha.value.length==0)
                            {
                                alert("Captcha Field may not be blank");
                                txtCaptcha.focus();
                            }
                      else
	                       {
                                 // alert("The characters you entered didn't match the word verification. Please try again.");
                                  alert("The characters you entered didn't match the Security Check. Please try again.");
	                       }

                        return false;
				}				
		   	}
		   	
		  function fnCheckRandom(txtCaptcha,SLNG)
			{			
				if(txtCaptcha.value==strCaptcha)
				{
					return true;
					//return false;
				}
				else
				{
					 if(txtCaptcha.value.length==0)
          {
          		if(SLNG.toUpperCase()=='SPANISH')
          		{alert("Captcha de campo no puede estar en blanco");}
          		else
              {alert("Captcha Field may not be blank");}
              txtCaptcha.focus();
          }
   			 else
	       {
	       					if(SLNG.toUpperCase()=='SPANISH')
	          		 	{alert("Los caracteres que ha introducido no coinciden con los de comprobación de seguridad. Por favor, inténtelo de nuevo.");}
	          		 	else
	                {alert("The characters you entered didn't match the Security Check. Please try again.");}
	                txtCaptcha.focus();
	       }

          return false;
				}				
		   	}
		   	

//Alpha Validation
function AlphaValidation(AlphaField)
{
var Alphabet;			
//Alphabet = "^[a-zA-Z]+$";	
Alphabet =/^[A-Za-z\'\,\-\.\ ]+$/;
//A-Z or a-z Alphabets only allowed
var name = AlphaField.value;
var FieldLable = GetControlName(AlphaField);

if (name.search(Alphabet) == -1)
//	Or				
//if (!name.match(Alphabet))
{
alert ("A-Z or a-z Alphabets only allowed" + FieldLable );
AlphaField.focus();
return false;

}
else
{
return true;	
}
}

//AlphaNumeric Validation

function AlphaNumericValidation(AlphaNumericField)
  {
    var FieldLable = GetControlName(AlphaNumericField)
		
    // regular expression to match only alphanumeric characters and spaces
    var re = /^[\w\'\,\-\.\ ]+$/;
    
    // validation fails if the input doesn't match our regular expression
    if(!re.test(AlphaNumericField.value)) {
      alert("Only alphanumeric values allowed" + FieldLable);
      AlphaNumericField.focus();
      return false;
    }
    // validation was successful
    return true;
  }
  
  
 //Radio button checked value
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// Zipcode Validation
function doZipCodeCheck(thisfield) {
	if (thisfield.value != "") {
		var FieldLable = GetControlName(thisfield);
		if ((isNaN((thisfield.value).replace("-","")) == true) || (((thisfield.value).replace("-","")).length < 5) ||  (((thisfield.value).replace("-","")).length > 9) ) {
			alert("Please enter a valid Zip Code" + FieldLable);
			thisfield.focus();
			return false;
		}
		return true;
	}
}

// phoneNo Validation		
  function doPhoneNumberCheck(PhoneNumber) 
  {
      if (PhoneNumber.value.length > 0) 
      {
       return ValidatePhone(PhoneNumber);
      }
      return true;
  }
    
    
// Submit/enter button validation
function clickButton(e, buttonid)
    {					
	var evt = e ? e : window.event;			
	var bt = document.getElementById(buttonid);

 	  if (bt)
	     { 
	          if (evt.keyCode == 13)
		{ 
		   bt.click(); 
		   return false; 
		} 
	      }
}

//GetRadioButtonValue

function GetRadioButtonValue(id)
        {
            var radio = document.getElementsByName(id);
            for (var j = 0; j < radio.length; j++)
            {
                if (radio[j].checked)
                   return radio[j].value ;
            }
        }
        
//Check the radio button is selected or not

	function ValidateCheckBox(opts, message) {
		var sFlag = 0;	
		for (var i = 0; i < opts.length; i++) {
			if (opts.item(i).checked) {			
			  sFlag = 1;		
			}	
		}

		if (sFlag != 1) {
			alert(message);
			return false;
		}
		else{
		  return true;
		}
	}


function ValidateEIN(num) {
  dashes = 0;
  ein = num.value.toUpperCase();
  if (Empty(ein)) return "";
	if (((ein.charAt(0) < "a") || (ein.charAt(0) > "z")) && ((ein.charAt(0) < "A") || (ein.charAt(0) > "Z")) && ((ein.charAt(0) < "0") || (ein.charAt(0) > "9"))) {
    return error(num, "Please enter a valid EIN");
	};
  for (var i = 0; (i < ein.length); i++) {
    if (i != 0) {
  		if (((ein.charAt(i) < "0") || (ein.charAt(i) > "9")) && (ein.charAt(i) != "-")) return error(num, "Please enter a valid EIN.");
  	};
    if (ein.charAt(i) == "-") {
      dashes = dashes + 1;
		};
	}; 
  if (dashes > 1) return error(num,"Please enter a valid EIN.",false);
  if (dashes == 1) {
	  if ((ein.charAt(0) < "0") || (ein.charAt(0) > "9")) {
      return error(num, "Please enter a valid EIN");
	};
  
  };
	if (ein.length != (9 + dashes)) return error(num, "Please enter a valid EIN.", false);
		
  if (ein.length == 9) {
    ein = ein.substring(0, 2) + "-" + ein.substring(2, 9);
  };  

  if (ein.substring(2, 3) != '-') 
  	return error(num, "Please enter a valid EIN.");
  num.value = ein;
  return ein;
}


function get_radio_value(opts)
{		for (var i = 0; i < opts.length; i++) 
  	{	if (opts.item(i).checked) 
  		{    var rad_val = opts[i].value;     }
   }
   return rad_val;
}

function replaceAll(txt, replace, with_this) {  return txt.replace(new RegExp(replace, 'g'),with_this);}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + dblValue + '.' + strCents);
}


function restrictDecimalPlace(strValue,idecimal)
{
	//strValue = strValue.toString().replace(/\$|\,/g,'');
	//dblValue = parseFloat(strValue);
	var pos=strValue.indexOf(".");
	var len=strValue.length;
	if (pos>-1)
	{
		var newValue=strValue.substring(0,pos+3)
		if(len>=pos+3)
		{	return newValue;	}
	}
	return strValue;
}

function ValidateAddress(Field)
  {
    var FieldLable = GetControlName(Field);
    // regular expression to match only alphanumeric characters and spaces
    var re = /^[\w\'\,\&\-\.\/\#\ ]+$/;
    
    // validation fails if the input doesn't match our regular expression
    if(!re.test(Field.value)) {
      alert("Only alphanumeric values allowed" + FieldLable);
      Field.focus();
      return false;
    }
    // validation was successful
    return true;
  }
  
function GetControlName(Field) {
		var FieldLable = trimString(Field.getAttribute('alt'));//Get control name to display in alert message
		if (FieldLable != '') {
			FieldLable = " in " + FieldLable;
		}
		return FieldLable + ".";
}


String.prototype.ReplaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    }
   
function replaceAll(txt, replace, with_this) { return txt.replace(new RegExp(replace, 'g'), with_this); }

function trimString(txt) { 
	if (txt==null) 
		return '';
	return txt.replace(/^\s*/, "").replace(/\s*$/, "");
}

//Alpha Validation
function IsAlpha(Field, FieldName, SLNG) {
	Field.value = trimString(Field.value);
    if (Field.value == "") return true;

    var Alphabet;
    Alphabet = /[^a-z_\-\s\.\,]/ig;

    if (Alphabet.test(Field.value)) {
        if (SLNG.toUpperCase() == 'SPANISH') {
            alert("Sólo alfabetos y caracteres especiales como comas (,) y puntos (.) se permiten en " + FieldName + ".");
        }
        else {
            alert("Only alphabets, and special characters like commas (,), and periods (.) are allowed in " + FieldName + ".");
        }
        Field.focus();
        Field.select();
        return false;
    }
    else {
        return true;
    }
}

//AlphaNumeric Validation
function IsAlphaNumeric(Field, FieldName, SLNG) {
    Field.value = trimString(Field.value);
    if (Field.value == "") return true;
    var re = /[^a-z_0-9\-\s\.\,\#]/ig;

    if (re.test(Field.value)) {
        if (SLNG.toUpperCase() == 'SPANISH') {
            alert("Alfabetos, números y caracteres especiales como comas (,), puntos (.), Y signos de número (#) se permiten en " + FieldName + ".");
        }
        else {
        		alert("Only alphabets, numbers, and special characters like commas (,), periods (.), and pound signs (#) are allowed in " + FieldName + ".");
        }
        Field.focus();
        Field.select();
        return false;
    }
    return true;
}


// Numeric Validation
function IsNumeric(Field, FieldName, SLNG) {
    Field.value = trimString(Field.value);
    if (Field.value == "") return true;
    var re = /[^0-9]/;

    if (re.test(Field.value)) {
        if (SLNG.toUpperCase() == 'SPANISH') {
            alert("Sólo números se les permite in " + FieldName + ".");
        }
        else {
            alert("Only numbers are allowed in " + FieldName + ".");
        }
        Field.focus();
        Field.select();
        return false;
    }
    return true;
}

// Numeric with Dash Validation
function IsNumericWithDash(Field, FieldName, SLNG) {
    Field.value = trimString(Field.value);
    if (Field.value == "") return true;
    var re = /[^0-9-]/g;

    if (re.test(Field.value)) {
        if (SLNG.toUpperCase() == 'SPANISH') {
            alert("Sólo números y guiones (-) se permiten en " + FieldName + ".");
        }
        else {
            alert("Only numbers, and hyphens (-) are allowed in " + FieldName + ".");
        }
        Field.focus();
        Field.select();
        return false;
    }
    return true;
}

