var reWhitespace = /^\s+$/
var reLetter = /^[a-zA-Z]$/
var reDayLetter = /^[A-Z]$/
var reAlphabetic = /^[a-zA-Z]+$/
var reAlphanumeric = /^[a-zA-Z0-9]+$/
var reDigit = /^\d/
var reInteger = /^\d+$/
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var timeDelimiter = ":";
// whitespace characters as defined by this sample code
var whitespace = " \t\n\r";

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()-. ";

// characters which are allowed in US phone numbers
var validUSPhoneChars = digits + phoneNumberDelimiters;

// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";

// U.S. phone numbers have 10 digits.
// They are formatted as 123 456 7890 or (123) 456-7890.
var digitsInUSPhoneNumber = 10;


// m is an abbreviation for "missing"

var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."

// s is an abbreviation for "string"
var sPhone = "Phone Number"

// i is an abbreviation for "invalid"

var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now.";
var iWorldPhone = "This field must be a valid international phone number. Please reenter it now.";
var iDayOfWeek = "This field must be a day of the week (like Monday, Tuesday). Please reenter it now.";
var iTimeOfDay = "This field must be a time of day (like 2:35 or 12:55). Please reenter it now.";
var iDuration = "This field must be a number for the duration of call (like 120 or 2). Please reenter it now.";
var iCust = "This field may not be left blank. Please enter your Customer ID number";
// p is an abbreviation for "prompt"
var pEntryPrompt = "Please enter a "
var pUSPhone = "10 digit U.S. phone number (like 415 555 1212)."
var pWorldPhone = "international phone number."
var pTime = "time for the call (like 8:15) and then Select A.M. or P.M."
var pDay = "day of the week (like Monday).";
var pDuration = "value for the duration of the call (2 hours is the same as 120 Minutes).";
var defaultEmptyOK = false
function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}
// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   // Is s empty?
    return (isEmpty(s) || reWhitespace.test(s));
}

function stripCharsInRE (s, bag)

{       return s.replace(bag, "")
}

// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

// Removes all characters which do NOT appear in string bag 
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}

function isLetter (c)
{   return reLetter.test(c)
}

function isDigit (c)
{   return reDigit.test(c)
}

// Returns true if character c is a letter or digit.

function isLetterOrDigit (c)
{   return reLetterOrDigit.test(c)
}
function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    return reInteger.test(s)
}

function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}

function isInternationalPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isInternationalPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}

function prompt (s)
{   window.status = s
}

function promptEmpty ()
{   window.status = ""
}


// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}


function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}

function warnInvalid (theField, s)
{   eval(theField).focus()
    eval(theField).select()
    alert(s)
    return false
}

function checkString (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return warnEmpty (theField, s);
    else return true;
}

// takes USPhone, a string of 10 digits
// and reformats as (123) 456-789

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "", 3, "-", 3, "-", 4))
}

function checkUSPhone (theField, emptyOK)
{   
    if (checkUSPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(eval(theField).value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(eval(theField).value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false)) 
          return warnInvalid (theField, iUSPhone);
       else 
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          return true;
       }
    }
}
   var Day = new Array(7);
   Day[0] = "Sunday";
   Day[1] = "Monday";
   Day[2] = "Tuesday";
   Day[3] = "Wednesday";
   Day[4] = "Thursday";
   Day[5] = "Friday";
   Day[6] = "Saturday";

function isDayofWeek (theField, emptyOK) {
   
   test_day = theField.value
   if (test_day == "") {
      return warnInvalid (theField, iDayOfWeek);
   }
   if (isDigit(test_day)) {
       return warnInvalid (theField, iDayOfWeek);
   }
   replaceChars(test_day);
   
   lengthday = Day.length;
   var short_day="";
   var sTestDay = "";
   var tDay = "";

   for (var st=0; st < 2; st++ ) {
      sTestDay += temp.charAt(st);
   }
   
   for (var sd=0; sd < lengthday; sd++) {
      tDay = Day[sd];
    for (var k=0; k < 2; k++) {
       short_day += tDay.charAt(k);
    }
    //alert ("Testing "+ short_day + " against "+ sTestDay);
    if (short_day == sTestDay) {
         //alert ("Matched "+ short_day + " to " + sTestDay);    
         theField.value = tDay;
         break
       }
       else {
          short_day = "";
         }
   }
   if (short_day == "") {
      return warnInvalid (theField, iDayOfWeek);
   }
}
function replaceChars(test_day) {
   test_day= test_day.toLowerCase();
   out = test_day.charAt(0); // replace this
   add = out.toUpperCase(); // with this
   temp = "" + test_day; // temporary holder

   while (temp.indexOf(out)>-1) {
   pos= temp.indexOf(out);
   temp = "" + (temp.substring(0, pos) + add + 
   temp.substring((pos + out.length), temp.length));
   }
   return temp;
}

function checkDuration  (theField) {
   var tDuration = theField.value;
   if (tDuration == isLetter(tDuration) || tDuration == "") {
      return warnInvalid(theField, iDuration);
      theField.value="";
   }
}

function checkID (theField) {
   var tID = theField.value;
   //alert (tID);
   if (tID == 0 || tID =="") {
      return warnInvalid(theField, iCust);
      theField.value="";

   }
}
function checkTime (theField) {
   var normalizedTime = stripCharsInBag(theField.value, timeDelimiter)
   if (normalizedTime.length == 3) {
      //alert ("Entered a 3 digit time " + normalizedTime);
      var tTime;
      tTime = normalizedTime.charAt(0);
      var tHour = tTime;
      tTime = normalizedTime.charAt(1);
      tTime += normalizedTime.charAt(2);
      var tMin = tTime;
      if (tHour <= 0 || tHour > 9 || tMin >=59 || tMin < 0 ) {
         return warnInvalid (theField, iTimeOfDay);
      }
      else {
         tTime = tHour + timeDelimiter + tMin;
         theField.value = tTime;
      }
   }
   else if (normalizedTime.length == 4) {
      //alert ("Entered a 4 digit time " + normalizedTime);
      var tTime;
      tTime = normalizedTime.charAt(0);
      tTime += normalizedTime.charAt(1);
      var tHour=tTime;
      tTime = normalizedTime.charAt(2);
      tTime += normalizedTime.charAt(3);
      var tMin = tTime;
      //alert ("This is the hour " + tHour + " this is the minute " + tMin);
      if (tHour >= 13 || tHour <= 9 || tMin >=59 || tMin < 0) {
        return warnInvalid (theField, iTimeOfDay);
      } 
      else {
         tTime = tHour + timeDelimiter + tMin;
         theField.value = tTime;
         }
      }
   else {
        return warnInvalid (theField, iTimeOfDay);
   }
}
function checkInternationalPhone (theField, emptyOK)
{   if (checkInternationalPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  if (!isInternationalPhoneNumber(theField.value, false)) 
          return warnInvalid (theField, iWorldPhone);
       else return true;
    }
}

function getRadioButtonValue (radio)
{   
    radio = eval(radio);
    for (var i = 0; i < radio.length; i++){   
        if (radio[i].checked) { 
            break;
        }
        
    }
    if (i== radio.length) {
        return "null";
    }
    else {
        return radio[i].value;    
    }
    //alert(i);
    //return radio[i].value;
}

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 emailCheck (emailStr) {

            /* The following variable tells the rest of the function whether or not
            to verify that the address ends in a two-letter country or well-known
            TLD.  1 means check it, 0 means don't. */
            
            var checkTLD=1;
            
            /* The following is the list of known TLDs that an e-mail address must end with. */
            
            var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
            
            /* The following pattern is used to check if the entered e-mail address
            fits the user@domain format.  It also is used to separate the username
            from the domain. */
            
            var emailPat=/^(.+)@(.+)$/;
            
            /* The following string represents the pattern for matching all special
            characters.  We don't want to allow special characters in the address. 
            These characters include ( ) < > @ , ; : \ " . [ ] */
            
            var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
            
            /* The following string represents the range of characters allowed in a 
            username or domainname.  It really states which chars aren't allowed.*/
            
            var validChars="\[^\\s" + specialChars + "\]";
            
            /* The following pattern applies if the "user" is a quoted string (in
            which case, there are no rules about which characters are allowed
            and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
            is a legal e-mail address. */
            
            var quotedUser="(\"[^\"]*\")";
            
            /* The following pattern applies for domains that are IP addresses,
            rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
            e-mail address. NOTE: The square brackets are required. */
            
            var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
            
            /* The following string represents an atom (basically a series of non-special characters.) */
            
            var atom=validChars + '+';
            
            /* The following string represents one word in the typical username.
            For example, in john.doe@somewhere.com, john and doe are words.
            Basically, a word is either an atom or quoted string. */
            
            var word="(" + atom + "|" + quotedUser + ")";
            
            // The following pattern describes the structure of the user
            
            var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
            
            /* The following pattern describes the structure of a normal symbolic
            domain, as opposed to ipDomainPat, shown above. */
            
            var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
            
            /* Finally, let's start trying to figure out if the supplied address is valid. */
            
            /* Begin with the coarse pattern to simply break up user@domain into
            different pieces that are easy to analyze. */
            
            var matchArray=emailStr.match(emailPat);
            
            var emailError ='Your EMail seems incorrect:\n';

            if (matchArray==null) {
            
            /* Too many/few @'s or something; basically, this address doesn't
            even fit the general mould of a valid e-mail address. */
            
            emailError += "(check @ and .'s)\n" ;
            return emailError;
            }
            var user=matchArray[1];
            var domain=matchArray[2];
            
            // Start by checking that only basic ASCII characters are in the strings (0-127).
            
            for (i=0; i<user.length; i++) {
            if (user.charCodeAt(i)>127) {
            emailError += "the username contains invalid characters.\n";
            return emailError;
               }
            }
            for (i=0; i<domain.length; i++) {
            if (domain.charCodeAt(i)>127) {
            emailError += "the domain name contains invalid characters.\n";
            return emailError;
               }
            }
            
            // See if "user" is valid 
            
            if (user.match(userPat)==null) {
            
            // user is not valid
            
            emailError += "the username doesn't seem to be valid.\n";
            return emailError;
            }
            
            /* if the e-mail address is at an IP address (as opposed to a symbolic
            host name) make sure the IP address is valid. */
            
            var IPArray=domain.match(ipDomainPat);
            if (IPArray!=null) {
            
            // this is an IP address
            
            for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
            emailError += "destination IP address is invalid!\n";
            return emailError;
               }
            }
            return true;
            }
            
            // Domain is symbolic name.  Check if it's valid.
             
            var atomPat=new RegExp("^" + atom + "$");
            var domArr=domain.split(".");
            var len=domArr.length;
            for (i=0;i<len;i++) {
            if (domArr[i].search(atomPat)==-1) {
            emailError += "the domain name does not seem to be valid.\n";
            return emailError;
               }
            }
            
            /* domain name seems valid, but now make sure that it ends in a
            known top-level domain (like com, edu, gov) or a two-letter word,
            representing country (uk, nl), and that there's a hostname preceding 
            the domain or country. */
            
            if (checkTLD && domArr[domArr.length-1].length!=2 && 
            domArr[domArr.length-1].search(knownDomsPat)==-1) {
                emailError += "the address must end in a well-known domain or two letter " + "country.\n";
                return emailError;
            }
            
            // Make sure there's a host name preceding the domain.
            
            if (len<2) {
                emailError += "this address is missing a hostname!\n";
                return emailError;
            }
            
            // If we've gotten this far, everything's valid!
            return true;
            }
