//--------------------------------------------------------------------------------
//
// Name: validate.js
//
// Javascript form validation functions used to check user input
//
// Version: 1.0
// Library: forms
// Requires: none
// Author: Brian McWilliams
//
//--------------------------------------------------------------------------------
//-----------------------------------------------------------
// 
// isFilled
//
//-----------------------------------------------------------
function isFilled(str)
{
   return (str.length);
}

//-----------------------------------------------------------
// 
// isNumber
//
// Number must contain only numbers!!
//
//-----------------------------------------------------------
function isNumber(str)
{
   for (i = 0; i < str.length; i++)
   {
      ch = str.substr(i, 1);

      if (ch < "0" || ch > "9")
         return(false);
   }

   return(true);
}

//-----------------------------------------------------------
// 
// isEmail
//
// Minimal address: a@b.cd
//
//-----------------------------------------------------------
function isEmail(str)
{
   pattern = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9-])+(\.[a-zA-Z0-9_-]+)+$/;

   return pattern.test(str);
}

//-----------------------------------------------------------
// 
// isURL
//
// Minimal url: http://www.ab
//
//-----------------------------------------------------------
function isURL(str)
{
   pattern = /^https?:\/\/([^.]{2,})(\.[^.]{2,})*$/;

   return pattern.test(str);
}

//-----------------------------------------------------------
// 
// isZip
//
// Minimal zipcode: 12345 OR 12345-6789
//
//-----------------------------------------------------------
function isZip(str)
{
   pattern = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

   return pattern.test(str);
}

//-----------------------------------------------------------
// 
// isPhone
//
// Minimal phone: 111 2222
//
//-----------------------------------------------------------
function isPhone(str)
{
   str = str.replace(/([\(\)\-\.# ])/g, ""); // Remove letters, (, ), and -

   pattern = /(^\d{10,15}$)|(^\d{10,15}[a-zA-Z]+\d+$)/;

   return pattern.test(str);
}

//-----------------------------------------------------------
// 
// isPrice
//
// Minimal Price: 1 OR 1.23
//
//-----------------------------------------------------------
function isPrice(str)
{
   pattern = /(^\d{1,}$)|(^\d{1,}\.\d{2}$)/;

   return pattern.test(str);
}

//-----------------------------------------------------------
// 
// isCardNumber
//
// Card Number must contain 16 digits seperated by spaces or
// dashes
//
//-----------------------------------------------------------
function isCardNumber(str)
{
   str = str.replace(/([\- ])/g, ""); // Remove dashes and spaces

   pattern = /(^\d{16}$)/;

   return pattern.test(str);
}

//-----------------------------------------------------------
// 
// isCardExpired
//
// Card expiration must be >= current date
//
//-----------------------------------------------------------
function isCardCurrent(cardMonth, cardYear)
{
   var d = new Date();

   //------------------------------------
   // Verify credit card expiration date
   //------------------------------------
   year = d.getFullYear();
   month = d.getMonth() + 1;

   //alert("date: " + month + " " + year + " card: " + cardMonth + " " + cardYear);
   if (cardYear < year || (cardYear == year && cardMonth < month))
      return(false);
      
   return(true);
}

//-----------------------------------------------------------------------------
// 
// validate_fields
//
// Validates the form named in passForm by comparing with the requirements
// specified in reqArr. passForm is just the name of the form such as
// documents.editForm and reqArr is an array such as:
//
// var reqArr = new Array 
// (
//     "req, title, Product Name",
//     "req, content, Short Description",
//     "req, price, Price, isDecimal",
//     "opt, sale_price, Sale Price, isDecimal"
// );
//
// The array gets broken into three parts: field name, text name (for messages),
// and a validation function. The same field can be passed to one or more 
// validation functions by including it on the list twice. This function builds
// a string with error messages for any field that fails the validation.
//
//-----------------------------------------------------------------------------
function validate_fields(passForm, reqArr)
{
   var msg = "";
   var field;           // The field on the form
   var field_name;      // The text name displayed in error messages
   var req;             // Whether the field must be filled or not
   var func;            // An optional validation function
   var val;             // The value of the field on the form
   var ret;             // Return value for optional validation function

   for (var i = 0; i < reqArr.length && reqArr[i] != "EOL"; i++)
   {
      field_arr = reqArr[i].split(", ");

      field = field_arr[1];
      field_name = field_arr[2];

      val = passForm.elements[field].value;

      req = (field_arr[0] == "req") ? true : false;
      func = (field_arr.length > 3) ? field_arr[3] : "";

      // Check if any required text fields are empty
      len = val.length;
      if (req == true && len == 0)
      {
         msg+= " - the " + field_name + " field is empty.\n";
      }

      // Run validation function only if field passes length test
      if (len > 0 && func != "")
      {
         ret = eval(func)(val);

         if (func == "isNumber" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter a numeric value.\n";

         if (func == "isDecimal" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter a numeric value with an optional decimal point.\n";

         if (func == "isPhone" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter the " + field_name.toLowerCase() + " including the area code.\n";
   
         if (func == "isEmail" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter your email address in the form: name@host.com.\n";
   
         if (func == "isZip" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter a zip code in the form: XXXXX or XXXXX-XXXX.\n";

         if (func == "isURL" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter a URL in the form: http://www.yoursite.com.\n";

         if (func == "isCardNumber" && !ret)
            msg+= " - the " + field_name + " is invalid. Please enter your 16 digit card number.\n";
      }
   }

   // Display error message
   return(msg);
}

//-----------------------------------------------------------------------------
// 
// validate_message
//
//-----------------------------------------------------------------------------
function validate_message(error_msg)
{
   var msg;
 
   // Display error message
   if (error_msg)
   {
      msg = "\nThe form cannot be submitted because:\n\n";
      msg+= error_msg;
      msg+="\nPlease correct the error(s) and resubmit.";

      alert(msg);
   }
}

//-----------------------------------------------------------------------------
// 
// validate
//
//-----------------------------------------------------------------------------
function validate(passForm, reqArr)
{
   var error_msg;
 
   //----------------------------------------------------
   // Check fields and display errors
   //----------------------------------------------------
   error_msg = validate_fields(passForm, reqArr);

   // Display error message
   if (error_msg)
   {
      validate_message(error_msg);
      return(false);
   }

   return(true);
}
