/*
  $Id: validate.js,v 1.1.1.1.2.1.2.1 2006/02/07 23:26:03 admin Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

function IsEmpty(fieldobj) {

  // Checks if field value is empty or contains only space
  var emptyexp = /^\s*$/

  if(fieldobj.value.search(emptyexp) != -1) {
      // the string contains just spaces or is empty
    //alert("<?php echo JS_MSG_ISEMPTY ?>");
    return true;
  } else {
      // not empty
      return false;
  }
}

function IsValidLength(fieldobj,min_size) {

  // Checks if field value meets the minimum field requirements

  var lengthexp = new RegExp("^.{" + min_size + ",}$");
  var resultmatch = fieldobj.value.match(lengthexp);

  if (resultmatch==null) {
      // the string does not contain enough characters
    //alert("<?php echo JS_MSG_ISVALIDLENGTH_PRE ?>" + min_size + "<?php echo JS_MSG_ISVALIDLENGTH_POST ?>");
    return false;
  } else {
      // string is long enough
      return true;
  }
}

function IsAlphaNum(fieldobj) {

  // Checks for non-alphanumeric characters. returns false if any non-alphanumeric chars found and true if all alphanumeric.

  var notalphaexp = /\W/g

  if (fieldobj.value.search(notalphaexp) != -1) {
    //alert("<?php echo JS_MSG_ISALPHANUM ?>");
    return false;
  } else {
    return true;
  }
}

function IsValidDate(dateStr, format) {
/*
  The function takes an input string and an optional format string.
  The format string is only 3 characters long and determines the relative positions of the month, day, and year.
  If the format string is omitted, then it will be "MDY" (month first, then day, then year).
  There are three different types of dividers that can be used in the date string.
  These are the slash (/), the period (.) and the dash (-).
  Years can be either 2 digits (00-49 are assumed to be 21st century and 50-99 are assumed to be 20th century) or 4 digits.

  The way the regular expression part of the function works is by using the "remember" capabilities of regular expressions.
  This assures that the same divider is used in both positions. (In other words, you couldn't do MM/DD-YYYY).
  The "\1" in the regular expression says "use the same thing you used in parentheses before (which is the check for a slash, period, or dash) and apply the check here".

  If the string passes the regular expression (there are 2 checks since the year can be either 2 or 4 digits), then additional JavaScript is performed to check the validity of the date.
  Instead of doing all the checks for the day of the month being out of range and checking for leap years, a simple approach is taken.
  A new date object is created in JavaScript. If the numbers are out of range (like February 31), JavaScript will still create an object, it will just be adjusted to be a valid date.
  So create the date and then check to see if it was adjusted by JavaScript.
  If it was adjusted, then the original date is not a valid date.
*/

   //check or set format
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1) ) { format = "MDY"; }
   // format set. creat exp based on where year is
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") {
     var mm = parts[0];
   } else if (format.substring(1, 2) == "M") {
     var mm = parts[1];
   } else {
     var mm = parts[2];
   }

   if (format.substring(0, 1) == "D") {
     var dd = parts[0];
   } else if (format.substring(1, 2) == "D") {
     var dd = parts[1];
   } else {
     var dd = parts[2];
   }

   if (format.substring(0, 1) == "Y") {
     var yy = parts[0];
   } else if (format.substring(1, 2) == "Y") {
     var yy = parts[1];
   } else {
     var yy = parts[2];
   }

   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }

   //passed validation
   return true;
}


function GetPositiveIntVal(argval) {

  // Returns positive integer value of argument if possible otherwise returns an empty string

  //first trim any space characters
  var retval = TrimString(argval);

  // check if a valid number
  if (isNaN(retval)) {
    // not a number. return empty string
    return '';
  } else {
    //is a valid number. return integer part
    if (retval >= 1) {
      return parseInt(retval);
    } else {
      //not positive number (greater than 0)
      return '';
    }
  }

}

function IsNumeric(fieldobj) {

  // Checks for non-numeric characters. returns false if any non-numeric chars found and true if all numeric.

  var notalphaexp = /\D/g

  if (fieldobj.value.search(notalphaexp) != -1) {
    //alert("<?php echo JS_MSG_ISNUMERIC ?>");
    return false;
  } else {
    return true;
  }
}


function StripSpaces(fieldobj) {

  // Strips all whitespace characters from field value

  var stripexp = /\s/g

  fieldobj.value = fieldobj.value.replace(stripexp,"");
}

function StripNonAlphaNumChars(fieldobj) {

  // Strips all whitespace characters from field value

  var stripexp = /\W/g

  fieldobj.value = fieldobj.value.replace(stripexp,"");
}


function TrimSpace(fieldobj) {

  // Trims all whitespace characters from field beginning and end of field value

  var leftexp = /^\s+/
  var rightexp = /\s+$/

  //Trim left side
  fieldobj.value = fieldobj.value.replace(leftexp,"");

  //Trim right side
  fieldobj.value = fieldobj.value.replace(rightexp,"");

}

function TrimString(string_value) {

  // Trims all whitespace characters from the string argument and returns the new string

  var leftexp = /^\s+/
  var rightexp = /\s+$/

  var new_string = string_value;

  //Trim left side
  new_string = new_string.replace(leftexp,"");

  //Trim right side
  new_string = new_string.replace(rightexp,"");

  return new_string;

}

function IsValidZip(fieldobj,country) {

  // Checks for valid postal code

  var postexp = "";

  switch (country) {
    case 38: //CAN
      //AIN 3L6
      postexp = /^([a-zA-Z]{1})(\d{1})([a-zA-Z]{1})(\d{1})([a-zA-Z]{1})(\d{1})$/
      break
    case 223: //US
      //90210 OR 90210-6754
      postexp = /^\d{5}(\-?\d{4})?$/
      break
    default:
      //unknown - must have non-whitespace chars
      postexp = /\S+/
  }

  var tempval = null;

  StripSpaces(fieldobj);

  // try matching with pattern
  if (fieldobj.value.match(postexp)==null) {
    // Does not match pattern.

    //alert("Validation Error: " + MapName(fieldobj) + " field does not match standard Canadian or US Postal Code (Zip) format.");
    return false;
  } else {
    // matches Canadian pattern
    return true;
  }

}

function IsValidPhone(fieldobj,country) {

  // Checks for valid phone number base on canada/us/international

  var phoneexp = "";

  switch (country) {
    case 38: //CAN
      //(709)-364-8765
      phoneexp = /^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/
      break
    case 223: //US
      //(709)-364-8765
      phoneexp = /^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/
      break
    default: //international
      //unknown - must have non-whitespace chars
      //phoneexp = /\S+/
      phoneexp = /^[ ]*[ \+0-9()\-]{8,}[ ]*$/
  }

  var tempval = null;

  StripSpaces(fieldobj);

  // try matching with pattern
  var tempval=fieldobj.value.match(phoneexp);

  if (tempval==null) {
    // Does not match pattern.

    //alert("Validation Error: " + MapName(fieldobj) + " field does not match standard Canadian or US Postal Code (Zip) format.");
    return false;
  } else {
    // matches pattern - reformat properly
    switch (country) {
      case 38: //CAN
        //(709)-364-8765
        FormatPhone(fieldobj,country)
        break
      case 223: //US
        //(709)-364-8765
        FormatPhone(fieldobj,country)
        break
      default: //international
        //unknown - must have non-whitespace chars

      }

    return true;
  }
}

function FormatPhone(fieldobj,country) {

  // Formats phone number based on canada/us/international

  var phonenum = fieldobj.value;
  var stripexp = /[\D]/g
  var stripped = '';

  switch (country) {
    case 38: //CAN
      //(709)-364-8765
      stripped = phonenum.replace(stripexp, '');
      if(stripped.length >= 10 ) {
        stripped = "(" + stripped.substring(0,3) + ") " + stripped.substring(3,6) + "-" + stripped.substring(6,10);
      }
      break
    case 223: //US
      //(709)-364-8765
      stripped = phonenum.replace(stripexp, '');
      if(stripped.length >= 10 ) {
        stripped = "(" + stripped.substring(0,3) + ") " + stripped.substring(3,6) + "-" + stripped.substring(6,10);
      }
      break
    default: //international
      return false;
  }

  fieldobj.value = stripped;
  return true;
}

function IsValidEmail(fieldobj) {

  // Pattern to check entered e-mail address for user@domain format.
  var emailPat=/^(.+)@(.+)$/
  // Unwanted special characters. These include ( ) < > @ , ; : \ " . [ ]
  var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
  // String representing which chars aren't allowed.
  var validChars="\[^\\s" + specialChars + "\]";
  // Pattern applies if the "user" is a quoted string
  var quotedUser="(\"[^\"]*\")";
  // Pattern applies for domains that are IP addresses. (E.g. joe@[123.124.233.4]) NOTE: The square brackets are required.
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
  // String representing an atom (a series of non-special characters.)
  var atom=validChars + '+';
  // String representing one word in the typical username. For example, in john.doe@somewhere.com
  var word="(" + atom + "|" + quotedUser + ")";
  // Pattern describing the structure of the user
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
  // Pattern describing the structure of a normal domain name, as opposed to ipDomainPat, shown above.
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

  // Start Validation

  // Begin with the coarse pattern to simply break up user@domain intodifferent pieces that are easy to analyze.

  var matchArray=fieldobj.value.match(emailPat);

  if (matchArray==null) {
    // Too many/few @'s or something; basically, this address doesn't even fit the general mold of a valid e-mail address.
    //alert("<?php echo JS_MSG_ISVALIDEMAIL_GEN ?>");
    return false;
  }

  var user=matchArray[1];
  var domain=matchArray[2];

  // See if "user" is valid
  if (user.match(userPat)==null) {
      // user is not valid
      //alert("<?php echo JS_MSG_ISVALIDEMAIL_USER ?>");
      return false;
  }

  /* 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) {
            //alert("<?php echo JS_MSG_ISVALIDEMAIL_IP ?>");
        return false;
        }
      }
      return true;
  }

  // Domain is symbolic name
  var domainArray=domain.match(domainPat);

  if (domainArray==null) {
    //alert("<?php echo JS_MSG_ISVALIDEMAIL_DOMAIN ?>");
      return false;
  }

  /* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

  /* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
  var atomPat=new RegExp(atom,"g");
  var domArr=domain.match(atomPat);
  var len=domArr.length;

  if (domArr[domArr.length-1].length<2 ||
      domArr[domArr.length-1].length>3) {
       // the address must end in a two letter or three letter word.
       //alert("<?php echo JS_MSG_ISVALIDEMAIL_END ?>");
       return false;
  }

  // Make sure there's a host name preceding the domain.
  if (len<2) {
       //var errStr="<?php echo JS_MSG_ISVALIDEMAIL_HOST ?>"
       //alert(errStr);
    return false;
  }

  // If we've gotten this far, everything's valid!
  return true;
}
