// Based on code by:
// Matt Kruse <matt@mattkruse.com>
// http://www.mattkruse.com/
function _isInteger(val)
  {
    var digits="1234567890";
    for (var i=0; i < val.length; i++)
      {
        if (digits.indexOf(val.charAt(i))==-1) { return false; }
      }

    return true;
  }



// Based on code by:
// Matt Kruse <matt@mattkruse.com>
// http://www.mattkruse.com/
function _getInt(str,i,minlength,maxlength)
  {
    for (var x=maxlength; x>=minlength; x--)
      {
        var token=str.substring(i,i+x);
	  if (token.length < minlength) { return null; }
          if (_isInteger(token)) { return token; }
      }

    return null;
  }


	
// Based on code by:
// Matt Kruse <matt@mattkruse.com>
// http://www.mattkruse.com/
function isDate(val)
  {
    val=val.replace(/\s*$/, "");    // Trim trailing spaces
    format="MM/dd/y";
    var i_val=0;
    var i_format=0;
    var c="";
    var token="";
    var x,y;
    var now=new Date();
    var year=now.getYear();
    var month=now.getMonth()+1;
    var date=1;
	
    while (i_format < format.length)
      {
        // Get next token from format string
	c=format.charAt(i_format);
	token="";
	while ((format.charAt(i_format)==c) && (i_format < format.length))
          {
            token += format.charAt(i_format++);
          }
	// Extract contents of value based on format token
        if (token=="y")
          {
            x=4;
            y=4;
            year=_getInt(val,i_val,x,y);
            if (year==null) { return 0; }
            if (year<2000) { return 0; }
            i_val += year.length;
          }
        else if (token=="MM")
          {
            month=_getInt(val,i_val,token.length,2);
            if(month==null||(month<1)||(month>12)){return 0;}
            i_val+=month.length;
          }
        else if (token=="dd"||token=="d")
          {
            date=_getInt(val,i_val,token.length,2);
            if(date==null||(date<1)||(date>31)){return 0;}
            i_val+=date.length;
          }
        else
          {
            if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
            else {i_val+=token.length;}
          }
        }

      // If there are any trailing characters left in the value, it doesn't match
      if (i_val != val.length) { return 0; }

      // Is date valid for month?
      if (month==2)
        {
          // Check for leap year
          if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) )
            { // leap year
              if (date > 29){ return 0; }
            }
          else 
            {
              if (date > 28) { return 0; }
            }
        }
      if ((month==4)||(month==6)||(month==9)||(month==11))
        {
          if (date > 30) { return 0; }
        }

    return 1;
  }