// JavaScript library for form field validation

// max chars count in request textarea.
//var maxCount = 300;     // set in config.xml.config file

//Trim's always a good function to have!
String.prototype.trim = function() {
 // skip leading and trailing whitespace
 // and return everything in between
  return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");

}

function alertError(field, message)
{
	alert(message);
	field.focus();
}

function requiredTextBox(field, fieldName)
{
	alertError(field, fieldName + " is required.");
}

function invalidFormatTextBox(field, fieldName, format)
{
	alertError(field, fieldName + " must be in " + format + " format.");
}

function mutuallyExclusiveTextBox(field, fieldName1, fieldName2)
{
	alertError(field, "You may not enter a " + fieldName1 + " and a " + fieldName2 + " at the same time.");
}

function requiredDropDownList(field, fieldName, multiple)
{
	if(multiple)
	{
		alertError(field, "You must select at least one " + fieldName + ".");
	}
	else
	{
		alertError(field, "You must select a " + fieldName + ".");
	}
}

function requiredCheckBox(field, fieldName, multiple)
{
	alertError(field, "You must select a " + fieldName + ".");
}


// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
   if (string.search) {
      if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
   }
   return true;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
   if (string.search) {
      if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
   }
   return true;
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
   if (string.search) {
      if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
   }
   return true;
}

//IllegalCharacter
//Used in email validation
function hasIllegalCharacters(string, illegalchars)
{	
	for(var i = 0; i < illegalchars.length; i++)
	{
		if(string.indexOf(illegalchars[i]) != -1) 
		{
			return true;
		}
	}
	return false;
}

//Function used to check invalid parenthesis
//Used in checking invalid parenthesis
//Parameter passed is string to be checked and fieldname for alert message
function containsInvalidParenthesis(thisObj, fieldName)
{	
	var illegalchars = new Array("(" , ")");
	
	thisObj.value = thisObj.value.trim();
	
	if (thisObj.value != "" ){
	
		for(var i = 0; i < illegalchars.length; i++)
		{
			if(thisObj.value.indexOf(illegalchars[i]) != -1) 
			{
				alert("'" + fieldName + "' contains invalid characters '(' and/or ')'.");
				thisObj.focus();
				return false;
			}	
		}
	}
	
	return true;
}

//isLongerThan
//Used in email validation
function isLongerThan(val, biggerThan)
{
	if(val.trim() == "")
		return false;
	if(val.length <= biggerThan)
		return false;
	return true;
}

//this turns a string separated by spaces into an array
//Used in email validation
function stringToArray(string)
{
	var charArray = new Array();
	var index = string.indexOf(" ");
	var arrayIndex = 0;
	while(index != -1)
	{
		charArray[arrayIndex] = string.charAt(index - 1);
		arrayIndex++;
		index = string.indexOf(" ", index + 1);
	}
	return charArray;
}

// check email
function isEmail (s)
{   
	// must have '@' and '.'
	var pattern = /^([a-zA-Z0-9\-\_\.\&\~]{1,})@([a-zA-Z0-9\-\_\.\&\~]+\.[a-zA-Z]{2,})$/
    var res = s.search(pattern);
    return (res == 0);
    //return isValidEmail(s);
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function isInteger (s)
{   
    var i;
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }

    return true;
}

// check zipcode
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 10
var ZIPCodeDelimeter = "-"

function isZIPCode (s)
{  
	for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (isDigit(c)) {} else { return false; }
    }

   return (s.length == digitsInZIPCode1)
}

function isZIPCodeExt (s)
{  
	for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (isDigit(c) || c == ZIPCodeDelimeter) {} else { return false; }
    }

   return ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2) )
}

// count char in textarea. 
function countCharacters(field)
{
	fieldObj = document.getElementById(field);
	if(fieldObj.value.trim().length > maxCount)
	{
		alert("The maximum allowed characters is " + maxCount + ".  You have " + fieldObj.value.trim().length + " characters.");
		//fieldObj.value = String(fieldObj.value).substring(0,maxCount);
		return false;
	}
	return true;
}

function trimLeadingZero(sText)
{
	return sText.replace(/^0+/, '');	
}

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   }
   return this
}

// check date
var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;
 
function isYear (s)
{   
    //return ((s.length == 2) || (s.length == 4));
    if(s.charAt(0) == '1') {
       if(s.charAt(1) != '9') return false;
    } else {
       if(s.charAt(0) == '0') return false;
    }
    return ((s.length == 4));
}

function isMonth (s)
{   
    return isIntegerInRange (s, 1, 12);
}

function isIntegerInRange (s, a, b)
{   
    if (!isInteger(s, false)) return false;
    var num = s; //parseInt (s); don't use parseInt. '09' wlll be 0.
    return ((num >= a) && (num <= b));
}

function isDay (s)
{  
    return isIntegerInRange (s, 1, 31);
}

function daysInFebruary (year)
{
    return ( ((year % 4 == 0) && (!(year % 100 == 0) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function isDate (year, month, day)
{
    if (!(isYear(year, false) && isMonth(month, false) && isDay(day, false) )) return false;

    var intYear = year; 
    var intMonth = month;
    var intDay = day; 

    if (intDay > daysInMonth[intMonth]) return false;    
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function checkUSDate(dt)
{
	var sArray = dt.split("/");
    
    if ( (sArray.length < 3) || (sArray.length > 3))
        return false;        
    
    month = trimLeadingZero(sArray[0]);
    day = trimLeadingZero(sArray[1]);
    year = sArray[2];

	return isDate(year, month, day);
}

// US phone number
var digits = "0123456789";
var phoneNumberDelimiters = "()- ";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var digitsInUSPhoneNumber = 10;

function isUSPhoneNumber (s)
{  
    if(!isInteger(s)) return false;
    else { 
		if( s.length == digitsInUSPhoneNumber) return true;
		else {
			// us format only
			//if( s.length == (digitsInUSPhoneNumber + 1) && s.charAt(0) == "1" ) return true;
			//else 
			return false;
		}
    }
}

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}

function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function reformat (s) {   
    var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

function reformatUSPhone (USPhone)
{  
	if(USPhone.length == digitsInUSPhoneNumber) return (reformat (USPhone, "(", 3, ") ", 3, "-", 4));
	else {
		return USPhone;
	}
	
}

function checkUSPhone (theField)
{  
	var USPhone = theField.value.trim();
	if(USPhone == "") return true;
    var normalizedPhone = stripCharsInBag(USPhone, phoneNumberDelimiters)
    if (!isUSPhoneNumber(normalizedPhone, false))
          return false;
    else
    {
		if(normalizedPhone.length == digitsInUSPhoneNumber) {
			theField.value = reformatUSPhone(normalizedPhone);
		} else {
			//theField.value =  USPhone;
			//us format only
			return false;
		}
          return true;
    }
   
}

