// global for checking user entered characters
var okayChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,:;!?$%()_-+=/\\@#&'*\r\n";
//var maxChars = 1000;

function formatCurrency(num) {
  num = num.replace(/^\s+|\s+$/g,''); // trim leading and trailing spaces
  if (num == '') return ('');
  num = num.toString().replace(/\$|\,/g,'');
  //if (isNaN(num)) num = "0";
  if (isNaN(num)) return (num.toString());
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if (cents<10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
  //return (((sign)?'':'-') + '$' + num + '.' + cents);
  return (((sign)?'':'-') + '$' + num);
}

function isCurrency(str) {
  // matches $17.23 or $14,281,545.45 or ...
  var re = /\$\d{1,3}(,\d{3})*/;
  return re.test(str);
}

// remove characters not in okay string (Used on form submission.)
function adjustEntryEnd(e) {
  // strip last character if not in okay string
  var strLen = e.value.length;
  var ch = e.value.charAt((strLen) - 1);

  if (okayChars.indexOf(ch) == -1) e.value = e.value.substring(0, (strLen) - 1);
}

// remove characters not in okay string (Used while user entering data usually on keyup.)
function adjustEntry(e) {
  // strip characters not in okay string
  var strLen = e.value.length;
  var i, t, ch, re;

  t = "";
  re = /\s/;
  for (i=0; i < strLen; i++) {  
    ch = e.value.charAt(i);
    if ( (okayChars.indexOf(ch) != -1) || re.test(ch.toString()) ) t += ch.toString();
  }
  e.value = t;
}

function isEmpty(str) {
  return (str == null) || (str.length == 0);
}

// returns true if the string is a valid email
function isEmail(str) {
  if(isEmpty(str)) return false;
  var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
  return re.test(str);
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
  var re = /[^a-zA-Z]/g;
  if (re.test(str)) return false;
  return true;
}

// returns true if the string only contains characters 0-9
function isNumeric(str) {
  var re = /[\D]/g;
  if (re.test(str)) return false;
  return true;
}

// returns true if the string only contains characters A-Z a-z 0-9
function isAlphaNumeric(str) {
  var re = /[^a-zA-Z0-9]/g;
  if (re.test(str)) return false;
  return true;
}

// returns true if the string only contains characters A-Z a-z space . ' -
function isName(str) {
  var re = /[^a-zA-Z./ /'/-]/g;
  if (re.test(str)) return false;
  return true;
}

// returns true if the string only contains characters A-Z a-z 0-9 space . , : # % ' -
function hasAddressChars(str) {
  var re = /[^a-zA-Z0-9/ /./,/:#/%/'/-]/g;
  if (re.test(str)) return false;
  return true;
}

// returns true if the string's length equals "len"
function isLength(str, len) {
  return str.length == len;
}

// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max) {
  return (str.length >= min) && (str.length <= max);
}

// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str) {
  var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/;
  return re.test(str);
}

function isPhoneNumberPlus1(str) {
  var re = /^(1[\s\.-]?)?\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/;
  return re.test(str);
}

// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
function isDate(str) {
  var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/;
  if (!re.test(str)) return false;
  var result = str.match(re);
  var y = parseInt(result[3]);
  var m = parseInt(result[1]);
  var d = parseInt(result[2]);
  if (m < 1 || m > 12 || y < 1900 || y > 2100) return false;
  if (m == 2) {
    var days = ((y % 4) == 0) ? 29 : 28;
  } else if (m == 4 || m == 6 || m == 9 || m == 11) {
    var days = 30;
  } else {
    var days = 31;
  }
  return (d >= 1 && d <= days);
}

// returns true if the string is a valid month formatted as...
// mm yyyy, mm/yyyy, mm.yyyy, mm-yyyy
function isMonth(str) {
  var re = /^(\d{1,2})[\s\.\/-](\d{4})$/;
  if (!re.test(str)) return false;
  var result = str.match(re);
  var y = parseInt(result[2]);
  var m = parseInt(result[1]);
  return (m < 1 || m > 12 || y < 1900 || y > 2100) ? false : true;
}

// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2) {
  return str1 == str2;
}

// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str) { // NOT USED IN FORM VALIDATION
  var re = /[\S]/g;
  if (re.test(str)) return false;
  return true;
}

// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(str, replacement) {// NOT USED IN FORM VALIDATION
  if (replacement == null) replacement = '';
  var result = str;
  var re = /\s/g;
  if(str.search(re) != -1) {
    result = str.replace(re, replacement);
  }
  return result;
}

// validate the form
function validateForm(f, preCheck, newClass, alerttype) {
  var errors = '';
  var errorsa = '';
  if (preCheck != null) {
    errors += preCheck + '<br>';
    errorsa += preCheck + '\n';
  }

  var i,e,t,n,v;
  for(i=0; i < f.elements.length; i++) {
    e = f.elements[i];
    e.value = e.value.replace(/^\s+|\s+$/g,''); // trim leading and trailing spaces

    if (e.optional && e.value.length==0) continue;
    t = e.type;
    n = e.id;
    v = e.value;
    if (t == 'text' || t == 'password' || t == 'textarea') {

      if (isEmpty(v)) {
        errors += n+errormsg[1]+ '<br>';
        errorsa += n+errormsg[1]+'\n';
        e.className=newClass;
        continue;
      }
      else {
        e.className='checkit';
      }
      if (v == e.defaultValue) {
        errors += n+errormsg[2]+ '<br>';
        errorsa += n+errormsg[2]+'\n';
        e.className=newClass;
        continue;
      }
      else {
        e.className='checkit';
      }
      if (e.isAlpha) {
        if (!isAlpha(v)) {
          errors += n+errormsg[3]+ '<br>';
          errorsa += n+errormsg[3]+'\n';
          //overlib('eaaaa');
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isNumeric) {
        if (!isNumeric(v)) {
          errors += n+errormsg[4]+ '<br>';
          errorsa += n+errormsg[4]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isAlphaNumeric) {
        if (!isAlphaNumeric(v)) {
          errors += n+errormsg[5]+ '<br>';
          errorsa += n+errormsg[5]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isName) {
        if (!isName(v)) {
          errors += n+errormsg[102]+ '<br>';
          errorsa += n+errormsg[102]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isEmail) {
        if (!isEmail(v)) {
          errors += v+errormsg[6]+ '<br>';
          errorsa += n+errormsg[6]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isAddress) {
        if (!hasAddressChars(v)) {
          errors += n+errormsg[103]+ '<br>';
          errorsa += n+errormsg[103]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isTextArea != null) {
        adjustEntry(e); // strip unwanted chars
        var maxChars = 1000; // maximum text area character length; should match corresponding php defs variable
        if (!isLengthBetween(e.value,0,maxChars)) {
          e.value = e.value.substring(0, maxChars); // truncate if exceeds char limit
          errors += n+' truncated to ' + maxChars + ' characters. Please check.' + '<br>';
          errorsa += n+' truncated to ' + maxChars + ' characters. Please check.' + '\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isLength != null) {
        var len = e.isLength;
        if (!isLength(v,len)) {
          errors += n+errormsg[7]+ len + '<br>';
          errorsa += n+errormsg[7]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isLengthBetween != null) {
        var min = e.isLengthBetween[0];
        var max = e.isLengthBetween[1];
        if (!isLengthBetween(v,min,max)) {
          errors += n+errormsg[8] + min + '-' + max + '<br>';
          errorsa += n+errormsg[8] + min + '-' + max + '\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isPhoneNumber) {
        if (!isPhoneNumberPlus1(v)) {
          errors += v+errormsg[9]+ '<br>';
          errorsa += n+errormsg[9]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isCurrency) {
        if (!isCurrency(v)) {
          errors += v+errormsg[105]+ '<br>';
          errorsa += n+errormsg[105]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isDate) {
        if (!isDate(v)) {
          errors += v+errormsg[10]+ '<br>';
          errorsa += n+errormsg[10]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isMonth) {
        if (!isMonth(v)) {
          errors += v+errormsg[104]+ '<br>';
          errorsa += n+errormsg[104]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
      if (e.isMatch != null) {
        if (!isMatch(v, e.isMatch)) {
          errors += n+errormsg[11]+ '<br>';
          errorsa += n+errormsg[11]+'\n';
          e.className=newClass;
          continue;
        }
        else {
          e.className='checkit';
        }
      }
    }
    if (t.indexOf('select') != -1) {
      if (isEmpty(e.options[e.selectedIndex].value)) {
        errors += n+errormsg[12]+ '<br>';
        errorsa += n+errormsg[12]+'\n';
        e.className=newClass;
        continue;
      }
      else {
        e.className='checkit';
      }
    }
    if (t == 'file') {
      if (isEmpty(v)) {
        errors += n+errormsg[13]+'<br>';
        errorsa += n+errormsg[13]+'\n';
        e.className=newClass;
        continue;
      }
      else {
        e.className='checkit';
      }
    }
  }
  div = document.getElementById('errordiv');
  if (errors != '') {
	  if (alerttype == '2' || alerttype == '3') {
      alert(errorsa);
    }
	  if (alerttype == '1' || alerttype == '3') {
      return dispErr(errors, div);
    }
  }
  div.style.display="none";
  return errors == '';
}

dispErr = function(error, divo) {
  divo.style.display="block";
  divo.innerHTML = error;
  return false;
}


/*
The following elements are not validated...

button   type="button"
checkbox type="checkbox"
hidden   type="hidden"
radio    type="radio"
reset    type="reset"
submit   type="submit"

All elements are assumed required and will only be validated for an
empty value or defaultValue unless specified by the following properties.

isEmail = true;          // valid email address
isAlpha = true;          // A-Z a-z characters only
isNumeric = true;        // 0-9 characters only
isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
isName = true;           // A-Z a-z space - ' characters only
isAddress = true;        // A-Z a-z 0-9 space . , : # % ' - characters only
isLength = number;       // must be exact length
isLengthBetween = array; // [lowNumber, highNumber] must be between lowNumber and highNumber
isPhoneNumber = true;    // valid phone number. See "isPhoneNumber()" comments for the formatting rules
isDate = true;           // valid date. See "isDate()" comments for the formatting rules
isMonth = true;          // valid month. See "isMonth()" comments for the formatting rules
isCurrency = true;       // valid dollar amount. See "isCurrency()" comments for the formatting rules
isMatch = string;        // must match string
optional = true;         // element will not be validated

alerttype = 0            // no error msg
alerttype = 1            // error msg in div
alerttype = 2            // error msg in alert
alerttype = 3            // error msg in div and alert
*/

//============================

// error msg depends on the language
var errormsg = new Array();
errormsg[0] = 'Select at least one checkbox.';
errormsg[1] = ' cannot be empty.';
errormsg[2] = ' cannot use the default value.';
errormsg[3] = ' can only contain characters A-Z a-z.';
errormsg[4] = ' can only contain characters 0-9.';
errormsg[5] = ' can only contain characters A-Z a-z 0-9.';
errormsg[6] = ' is not a valid email.';
errormsg[7] = ' character number must be less than ';
errormsg[8] = ' character number must be between ';
errormsg[9] = ' is not a valid U.S. phone number.';
errormsg[10] = ' is not a valid date.';
errormsg[11] = ' does not match.';
errormsg[12] = ' needs an option selected.';
errormsg[13] = ' needs a file to upload.';
errormsg[99] = 'All form information will be erased.';
errormsg[100] = 'Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

errormsg[101] = 'Email addresses must match.';
errormsg[102] = ' can only contain characters A-Z a-z space . \' -';
errormsg[103] = ' can only contain characters A-Z a-z 0-9 space . , : # % \' -';
errormsg[104] = ' is not a valid month.';
errormsg[105] = ' is not a valid dollar amount.';
