// ===================================================================
// File:    validation.js
// Author:  Don Herkimer <donald.herkimer@sas.com>
// Purpose: Validates input for the Customer Relationship Management
//          (CRM) application.  Included in various JSPs.
// See:     In PRISM -
//              \Dept\MIS\CRM\src\jsp
// ===================================================================

//Pops up an alert box if there is some alerttext to display.
function alertIfNecessary(alerttext)
{
  if (alerttext == undefined)
  {
    return;
  }
  if (alerttext != "") 
  {
    alert(alerttext);
  } 
}

//Returns true iff the value of the field is between (inclusive)
//min and max.  
//If supplied, the datatype is one of "I" (integer) or "F" (float).
//If supplied, the alerttext is popped up in an alert box as necessary.
function isValidNumericValue(field, min, max, alerttext, datatype)
{
  with (field)
  {
    checkvalue=parseFloat(value);
    if (isNan(checkvalue))
    {
      alertIfNecessary(alerttext);
      return false;
    }
    if (datatype)
    {
      smalldatatype=datatype.toLowerCase();
      if (smalldatatype.charAt(0)=="i")
      {
        checkvalue=parseInt(value);
      }
    }
    if ((checkvalue < min) || (checkvalue > max) || (value != checkvalue))
    {
      alertIfNecessary(alerttext);
      return false;
    }
  }
  return true;
}

//Returns true iff the value of the field is an integer, and has
//between (inclusive) min and max number of digits.
//If supplied, the datatype is one of "I" (integer) or "F" (float).
//If supplied, the alerttext is popped up in an alert box as necessary.
function isValidNumberOfDigits(field, min, max, alerttext, datatype)
{
  with (field)
  {
    checkvalue=parseFloat(value);
    if (isNan(checkvalue))
    {
      alertIfNecessary(alerttext);
      return false;
    }
    if (datatype)
    {
      smalldatatype=datatype.toLowerCase();
      if (smalldatatype.charAt(0)=="i") 
      {
        checkvalue=parseInt(value); 
        if (value.indexOf(".") != -1) 
        {
          checkvalue=checkvalue+1;
        }
      }
    }
    if ((value.length < min) || (value.length > max) || (value != checkvalue))
    {
      alertIfNecessary(alerttext);
      return false;
    }
  }
  return true;
}

//Returns true only if the value of the supplied field is not empty.
//If supplied, the alerttext is popped up in an alert box as necessary.
function isEmpty(field, alerttext)
{
  with (field)
  {
    if (value==null || value=="")
    {
      alertIfNecessary(alerttext);
      return true;
    }
  }
  return false;
}

/*
 * DJH: The following two functions are from the O'Reilly book
 *      "JavaScript: The Defnintive Guide".  See:
 *      http://examples.oreilly.com/jscript4/
 */
// A utility function that returns true if a string contains only 
// whitespace characters.
function isblank(s) {
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// This is the function that performs form verification. It is invoked
// from the onsubmit event handler. The handler should return whatever
// value this function returns.
function verify(f) {
    var msg;
    var empty_fields = "";
    var errors = "";

    // Loop through the elements of the form, looking for all 
    // text and textarea elements that have "required" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // verify that they are numbers and in the right range.
    // If the element has a "numeric" property defined, verify that
    // it is a number, but don't check its range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        if (((e.type == "text") || (e.type == "textarea")) && e.required) {
            // check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          ";
                if( e.desc != null )
                  empty_fields += e.desc;
                else
                  empty_fields += e.name;
                continue;
            }
        }
        // Now check for fields that are supposed to be numeric.
        if (e.numeric || (e.min != null) || (e.max != null)) { 
            if (((e.value == null) || (e.value == "") || isblank(e.value)) && !e.required)
            {
              //It's not filled in, but not required.  Skip it.
              continue;
            }
            var v = parseFloat(e.value);
            e.value = v;
            if  (isNaN(v) || 
                ((e.min != null) && (v < e.min)) || 
                ((e.max != null) && (v > e.max))) {
                
                errors += "- ";
                if( e.desc != null )
                  errors += e.desc;
                else
                  errors += e.name;

                if( e.max != null || e.min != null )
                  errors += " must have a number that is";
                else
                  errors += " must be";
                  
                if (e.min != null) 
                    errors += " at least " + e.min;
                if (e.max != null && e.min != null) 
                    errors += " and no more than " + e.max;
                else if (e.max != null)
                    errors += " no more than " + e.max;
                errors += ".\n\n";
            }
        }
        else if( e.alphanumeric )
        {
           if( !checkstring( e.value ) )
           {
              if( e.desc != null )
                 errors += e.desc;
              else
                 errors += e.name;

              errors += " must be alphanumeric only.\n\n";
           }
        }
    }

    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted. 
    // Otherwise return true.
    if (!empty_fields && !errors) return true;

    msg  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"

    if (empty_fields) {
        msg += "- The following required field(s) are empty:" 
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

function checkstring(text) {
         pat=/^[A-Za-z0-9]{6,10}$/;
         result=text.match(pat);
         return result;
}


