//  Extend a new method to the String Class isNull 
String.prototype.isNull=string_isNull;

String.prototype.strip=string_strip;

String.prototype.isNum=string_isNum;
String.prototype.isWholeNum=string_isWholeNum;
String.prototype.validateDateEntry=string_validateDateEntry;



// Method Name: alertAndFocus                                                                       
// Description:  It alerts the given msg, focus the form element, and returns false
//               NOTE:  The caller should/may want to return the returned value of false
// Prototype of: String                                                                      
// Syntax:  return alertAndFocus(aform.password, "Your password and password confirmation must match.");                                                                          
// Returns: false = to stop execution after the alert
function alertAndFocus(obj, msg)
{
	alert(msg);
	obj.focus();
	obj.select();  //selects all the text in the object.
	return false;
}


function string_isNull()
{ 
// Method Name: isNull                                                                       
// Description:  returns whether or not the string is null.  If only tabs and spaces         
//               are present, the string is still considered null.                           
// Prototype of: String                                                                      
// Syntax: isNull()                                                                          
// Returns: true = string is null,     false = string is not null                                                       
  var str = this;
  var i, ch, isnull = true, maxlen;
  if (typeof str == 'number') return(false) 
  if (str != null  && str != 'undefined')
  {  for (i = 0; i < str.length; ++i)
	 {   ch = str.charAt(i);
	     if (ch != ' ' && ch != '\t')
	     {  isnull = false;
	        break;
	     }
	 }
  }
  return (isnull);
}


/*
function string_isValidDate(separator, country)
{
  if (separator == null)
    separator = '/';
  if (country != null) 
    return this.validateDateEntry(separator, "NONE", country);
  else
    return this.validateDateEntry(separator, "NONE");
}
*/

function checkDate(fld, fieldName) {
	var dateMsg = fld.value.validateDateEntry();
	if ( dateMsg != "" ) {
		return alertAndFocus(fld, fieldName + ": " + dateMsg);
	}
	return true;
}

function noNull(fld, fieldName) { 
// Name: noNull                                                                            
// Description:  Calls isNull and gives alert msg is the given fields is NULL.             
// Syntax: noNullisNull(<documents.form.fieldname>, name of fields to be put in alert.)    
// Returns: true = field is NOT NULL,          false = fields is NULL                                                         
	if ( fld.value.isNull() ) {
		return alertAndFocus(fld, "The '" + fieldName + "' field cannot be empty.");
	}
	return true;
}


// method strip:
// description: Returns a copy of the string with the spaces and tabs removed.
//                      Can also strip other characters if provided with the 'character'  parameter. 
//  prototype of: String
//  syntax: strip(option, character)
//  inputs: option - Optional parameter. 
//                     "B" = remove both leading and trailing.  Default. 
//                     "L" = remove only from the left of the string
//                     "R" = remove only to the right of the string
//                     "A" = remove all of the specified characters from the string
//          character - character to strip from the string.  Optional, but you must 
//                      specify the option parameter in order to use this one.  
//                      By default will use spaces and tabs.
// returns:  A string containing the original string, without any spaces or tabs, 
//           or without any of the characters provided witht the 'character' 
//           parameter.
// custom functions called: isNull()
function string_strip(option, character) {
  var oldStr = this
  var newStr='',tempStr='',i,j;

  if ( option != null) { option = option.toUpperCase() }
  else { option = "B" }
  if ( oldStr == null ) 
  {
    newStr = null;
  }
  else 
  {
    newStr.value = "";
    if ( character != null )
       badchars = character;
    else  
       badchars=" \t";
    if ( (option == "B") || (option == "L") || (option == "A") )     
    {
      for(i=0; i < oldStr.length; i++) 
      {
        curchar = oldStr.charAt(i);
        if( badchars.indexOf(curchar) == -1 ) 
        {
          newStr = oldStr.substring(i,oldStr.length);
          break;
         }
      }
    }  else {newStr = oldStr}
    if ( (option == "B") || (option == "R") || (option == "A"))
    {
      for(i=newStr.length-1;i>=0; i-- ) 
      {
        curchar = newStr.charAt(i);
        if( badchars.indexOf(curchar) == -1 ) 
        {
          newStr = newStr.substring(0,i+1);
          break;
        }
      }
    }
    if ( option == "A") 
    {
      tempStr = newStr;
      newStr = '';
      for (j=0; j < tempStr.length; j++) 
      {
        curchar = tempStr.charAt(j);
        if (badchars.indexOf(curchar) == -1)
          newStr +=  curchar;
      }
    }  
  }
  return (newStr);
}

// method isNum:  
// description:  returns whether or not the string is strictly numeric 
//               this includes all digits (0..9) and the decimal point (.)
//               Will allow blanks and still be considered numeric by default,
//               but this can be disabled with the allowBlanks parameter.
//
// prototype of: String
//
// syntax: isNum(allowBlanks, addChars)
//
// inputs:    allowBlanks - Optional.  Defaults to 'Y'
//                             'Y' - Yes, allow blanks and still consider numeric
//                             'N' - No, don't allow blanks and still consider numeric.  
//            addChars - Optional.  String of additional characters to allow and 
//                       still be considered striclty numeric.  The allowBlanks 
//                       parameter must be specified to use this option.  
//
// returns: true = string is strictly numeric
//          false = string is not strictly numeric
function string_isNum(allowBlanks, addChars)
{  
  var param1 = allowBlanks, param2;
  if (allowBlanks == null)
    param1 = 'Y';
  if (addChars == null)
    param2 = '.'
  else
    param2 = addChars.toString()+'.';
  return this.isWholeNum(param1, param2);
}

// method isWholeNum:  
// description:  returns whether or not the string is a whole number.
//               This includes all digits (0..9).  Will allow blanks and still 
//               be considered numeric by default, but this can be disabled with 
//               the allowBlanks parameter.
//
// prototype of: String
//
// syntax: isWholeNum(allowBlanks, addChars)
//
// inputs:    allowBlanks - Optional.  Defaults to 'Y'
//                             'Y' - Yes, allow blanks and still consider numeric
//                             'N' - No, don't allow blanks and still consider numeric.  
//            addChars - Optional.  String of additional characters to allow and 
//                       still be considered a whole number.  The allowBlanks 
//                       parameter must be specified to use this option.  
//
// returns: true = string is a whole number
//          false = string is not a whole number 
function string_isWholeNum(allowBlanks, addChars)
{
   var numStr = this; 
   var digits = "0123456789", retval = true, i, ch;
   if (typeof addChars != 'undefined') digits += addChars;
   if (typeof(numStr) == 'number') return true;
   if (allowBlanks == null || allowBlanks == 'y' || allowBlanks == 'Y') 
      allowBlanks = 'Y';
   else 
      allowBlanks = 'N'
   if (allowBlanks == 'N')
      if ( this.strip().isNull()) 
	   		return false;	  
	 

   numStr = String(numStr);
   numStr = numStr.strip();

   for (i=0; i < numStr.length; i++)
   {   
       ch = numStr.charAt(i);
       if ( digits.indexOf(ch) == -1 )
       {  
          retval = false;
          break;
       }
   }
   return (retval)
}



//----------------------------------------------------------------------------------------------------
// method validateDateEntry:
// Definition:  Validates a given string to make sure it is a
//           date in the format mm-dd-yyyy.  The '-' character can be 
//           substituted for another, by passing it in as a parameter.  
// Syntax:  validateDateEntry(separator, fieldTitle)

// Inputs:  separator - the character you want to use as a separator.  
//                      Optional.  Defaults to '/'
//          fieldTitle -   the title of the message you want displayed to 
//                         the user.  More specific details will be displayed 
//                         to the user to give the specific reason why a date
//                         is invalid.  Optional.  Default is "Please enter a valid 
//                         date in the format mm<sep>dd<sep>yyyy, where
//                         <sep> is the specified separator.  If you specify this
//                         field, you must also specify a separator.  
//                         NOTE: If you do not wish to have an alert given to the 
//                         user, enter "NONE" (all in caps) for this field.
// Returns:  true if string is a date in format mm<sep>dd<sep>yyyy,
//             where <sep> is the specified separator.
//           false otherwise
//----------------------------------------------------------------------------------------------------
function string_validateDateEntry(validDate, fieldTitle, separator) {
  var validDate = this;
 
  var returnMsg = "";
  
  var isDateValid = true;                           // Assume date is valid
  validDate = validDate.strip();                	// Trim leading/trailing blanks from date field value
  
  if (validDate == '') return '';
  
  var mm = "";                                      // Month   
  var dd = "";                                      // Day
  var yyyy = "";                                    // Year
  var sep1 = 0;                                     // Pointer to position of 1st digit separator in date string ("/" or "-")
  var sep2 = 0;                                     // Pointer to position of 2nd digit separator in date string ("/" or "-")
  if (separator == null) {separator = '/'}
  if (fieldTitle == null) {fieldTitle = 'Please enter a valid date in the format mm'+separator+'dd'+separator+'yyyy'}
  country = null; //hack
  if (country == null) {country = 'US'}

  sep1 = validDate.indexOf(separator);                    // Find position of 1st slash
  sep2 = validDate.indexOf(separator, sep1+1);          //  find position of 2nd slash
 
  if ( ( sep1 >= 0 ) && (sep2 >= 0 ) ) {            // If both separators found
    mm = validDate.substring(0, sep1)    
    dd = validDate.substring(sep1+1, sep2)
    yyyy = validDate.substring(sep2+1, validDate.length)
  }
  else {
    isDateValid = false;
    //alert(fieldTitle);
	returnMsg = fieldTitle;
	return returnMsg;
  }

  var details = "";     // Initial details msg to be returned to user on error 
  var leastYear = 1900;                             // Year must be >= this
  var greatestYear = 2100;                          // Year must be <= this
  var tempDate = new Date();

  if ( validDate.length > 0 ) {                     
	if ( (yyyy.isNum() == false) || (mm.isNum() == false) || (dd.isNum() == false))
      isDateValid = false
    else if (yyyy.length < 4) {
	  isDateValid = false;
	  details = "Year must be a 4-digit year";
	}
	else if ( (yyyy < leastYear) || (yyyy > greatestYear) ) {      
      isDateValid = false;
      details = "Year must be between " + leastYear + " and " + greatestYear;
    }
    else if ( (mm < 1 ) || (mm > 12 ) ) {                          
      isDateValid = false;
      details = "Invalid month entered";
    }
    else if ( (dd < 1 )  ) {                                      
      isDateValid = false;
      details = "Invalid day entered";
    }
    else if ( dd > 28 ) {          
      var daysInMonth = 31;                                        // Assume 31 days in month
      if ( mm == 4 || mm == 6 || mm == 9 || mm == 11 )             // If a 30-day month
        daysInMonth = 30                                           //   change days-in-month to 30
      else if ( mm == 2 )                                          // If month is February
        daysInMonth = ( (yyyy/4) == parseInt(yyyy/4) ? 29 : 28 );  // If leap year, days = 29, else days = 28
      if ( dd > daysInMonth ) {                                    // If too many days specified...
        isDateValid = false;             
        details = "There are only " + daysInMonth + " days in the specified month";
      } 
    }
  }
  if ((isDateValid == false) && (fieldTitle != "NONE")) {
    returnMsg = fieldTitle + "\n" + details
	//alert(fieldTitle + "\n" + details);
  }
  return returnMsg;
}


