/*
MODULE NAME:  validate.js
PURPOSE: javascript input field validation functions for CSF
AUTHOR: Grant Szabo (grant@quagmire.com)
CREATED: 1/03
LAST MODIFIED: 5/28/03
*/

// Function to validate all Date fields
function fcnVerifyDate(thisDayObj) {
            if (thisDayObj.value == "") {
                        return 1;
            }
            
            var dtePattern;
            var thisDateTest;
            var msg;
            var thisMonth;
            var thisDay;
            var thisYear;
            var strTodayMonth;
            var strTodayDay;
            var strTodayYear;
            var strTodayStr;
            var strValStr;
            
            // Checks for dates of "031302" format
            if (thisDayObj.value.length == 6) {
                        dtePattern = /\d\d\d\d\d\d/;
                        thisDateTest = dtePattern.test(thisDayObj.value);
                        msg = "All date fields must be entered in a MMDDYY or MM/DD/YYYY format.  \n";
                        if (thisDateTest == false) {
                                    thisDayObj.focus();
                                    thisDayObj.value = "";
                                    return 1;
                        }
                        thisMonth = thisDayObj.value.substring(0,2);
                        thisDay = thisDayObj.value.substring(2,4);
                        thisYear = thisDayObj.value.substring(4,6);                      
            }
            // Checks for dates of "03132003" format
            else if (thisDayObj.value.length == 8) {
                        dtePattern = /\d\d\d\d\d\d\d\d/;
                        thisDateTest = dtePattern.test(thisDayObj.value);
                        msg = "All date fields must be entered in a MMDDYY or MM/DD/YYYY format.  \n";
                        if (thisDateTest == false) {
                                    thisDayObj.focus();
                                    thisDayObj.value = "";
                                    return 1;
                        }           
                        thisMonth = thisDayObj.value.substring(0,2);
                        thisDay = thisDayObj.value.substring(2,4);
                        thisYear = thisDayObj.value.substring(4,8);
            }
            // Checks for dates of "09/13/2002" format
            else if (thisDayObj.value.length == 10) {
                        dtePattern = /\d\d\/\d\d\/\d\d\d\d/;
                        thisDateTest = dtePattern.test(thisDayObj.value);
                        msg = "All date fields must be entered in a MMDDYY or MM/DD/YYYY format.  \n";
                        if (thisDateTest == false) {
                                    thisDayObj.focus();
                                    thisDayObj.value = "";
                                    return 1;
                        }           
                        thisMonth = thisDayObj.value.substring(0,2);
                        thisDay = thisDayObj.value.substring(3,5);
                        thisYear = thisDayObj.value.substring(6,10);
            }
            else {
                        alert("All date fields must be entered within a MMDDYY or MM/DD/YYYY format.  ");
                        thisDayObj.focus();
                        thisDayObj.value = "";
                        return 1;
            }
            
            // Month Tests
            if ((thisMonth > 12) || (thisMonth < 1)) {
                        thisDayObj.focus();
                        thisDayObj.value = "";
                        alert(msg);
                        return 1;
            }
                        
            if ((thisMonth == '02') && (thisDay > 28)) {
                        thisDayObj.focus();
                        thisDayObj.value = "";
                        alert("The month of February cannot have more than 28 days.  ");
                        return 1;
            }
            if (((thisMonth == '04') || (thisMonth == '06') || (thisMonth == '09') || (thisMonth == '11')) && (thisDay > 30)) {
                        thisDayObj.focus();
                        thisDayObj.value = "";
                        alert("The month within this date cannot have more than 30 days.  ");
                        return 1;
            }
            if (((thisMonth == '01') || (thisMonth == '03') || (thisMonth == '05') || (thisMonth == '07') || (thisMonth == '08') || (thisMonth == '10') || (thisMonth == '12')) && (thisDay > 31)) {
                        thisDayObj.focus();
                        thisDayObj.value = "";
                        alert("The month within this date cannot have more than 31 days.  ");
                        return 1;
            }
            // Day Test
            if ((thisDay < 01) || (thisDay > 31)) {
                        thisDayObj.focus();
                        thisDayObj.value = "";
                        alert("Days cannot be less than 1 or more than 31.  ");
                        return 1;
            }
            
            // Year Test
            // If length is 6, then convert to 10 and set value
            if (thisDayObj.value.length == 6) {
                        if ((thisYear < '00') || (thisYear > '09')) {
                                    thisDayObj.focus();
                                    thisDayObj.value = "";
                                    alert(msg);
                                    return 1;
                        }
                        //thisDayObj.value = thisMonth + "/" + thisDay + "/20" + thisYear;
            }           
            else if (thisDayObj.value.length == 10) {
                        if ((thisYear < 1900) || (thisYear > 2010)) {
                                    thisDayObj.focus();
                                    thisDayObj.value = "";
                                    alert(msg);
                                    return;
                        }
            }
            
            //
            // Dates cannot be in the past
            //
            /*
            if (thisDayObj.value.length == 6) {
                        strTodayMonth = strTodaysDate.substring(0,2);
                        strTodayDay = strTodaysDate.substring(3,5);
                        strTodayYear = strTodaysDate.substring(8,10);
            }
            else {
                        strTodayMonth = strTodaysDate.substring(0,2);
                        strTodayDay = strTodaysDate.substring(3,5);
                        strTodayYear = strTodaysDate.substring(6,10);
            }
                                    
            strTodayStr = strTodayYear + strTodayMonth + strTodayDay;
            strValStr = thisYear + thisMonth + thisDay;
            
            if (strValStr < strTodayStr) { 
                        alert("You cannot enter dates in the past.  ");
                        thisDayObj.value = ""; 
                        return 1;
            }
            else {
                        if (thisYear.length == 2) { 
                                    thisYear = "20" + thisYear;
                        }
                        thisDayObj.value = thisMonth + "/" + thisDay + "/" + thisYear;
            }
            */
            return 0;
}

function fcnVerifyPhone(phonenum) {
	rxpNum = /[^\d]/g;

	return (phonenum.replace(rxpNum,''));
}

function fcnVerifyPassword(pwd1, pwd2) {
    if (pwd1 != pwd2) {
              msg  = '_____________________________________________________________\n\n';
              msg += 'The passwords you typed in did not match.  Please re-type both\n';
              msg += 'passwords and try again.\n';
              msg += '_____________________________________________________________\n\n';
       alert(msg);
       return false;
    }
}

// FUNCTION TO CHECK VALID EMAIL ADDRESSES
function fcnIsEmail ( obj ) {
			var emailStr = obj.value;
            var isOK = true;
            /* The following variable tells the rest of the function whether or not
            to verify that the address ends in a two-letter country or well-known
            TLD.  1 means check it, 0 means don't. */
            
            var checkTLD=1;
            
            /* The following is the list of known TLDs that an e-mail address must end with. */
            
            var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
            
            /* The following pattern is used to check if the entered e-mail address
            fits the user@domain format.  It also is used to separate the username
            from the domain. */
            
            var emailPat=/^(.+)@(.+)$/;
            
            /* The following string represents the pattern for matching all special
            characters.  We don't want to allow special characters in the address. 
            These characters include ( ) < > @ , ; : \ " . [ ] */
            
            var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
            
            /* The following string represents the range of characters allowed in a 
            username or domainname.  It really states which chars aren't allowed.*/
            
            var validChars="\[^\\s" + specialChars + "\]";
            
            /* The following pattern applies if the "user" is a quoted string (in
            which case, there are no rules about which characters are allowed
            and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
            is a legal e-mail address. */
            
            var quotedUser="(\"[^\"]*\")";
            
            /* The following pattern applies for domains that are IP addresses,
            rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
            e-mail address. NOTE: The square brackets are required. */
            
            var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
            
            /* The following string represents an atom (basically a series of non-special characters.) */
            
            var atom=validChars + '+';
            
            /* The following string represents one word in the typical username.
            For example, in john.doe@somewhere.com, john and doe are words.
            Basically, a word is either an atom or quoted string. */
            
            var word="(" + atom + "|" + quotedUser + ")";
            
            // The following pattern describes the structure of the user
            
            var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
            
            /* The following pattern describes the structure of a normal symbolic
            domain, as opposed to ipDomainPat, shown above. */
            
            var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
            
            /* Finally, let's start trying to figure out if the supplied address is valid. */
            
            /* Begin with the coarse pattern to simply break up user@domain into
            different pieces that are easy to analyze. */
            
            var matchArray=emailStr.match(emailPat);
            
            if (matchArray==null) {
            
            /* Too many/few @'s or something; basically, this address doesn't
            even fit the general mould of a valid e-mail address. */
            
            alert("The email address you entered is incorrect.    \nPlease reenter (checking for @ and .)");
            return false;
            }
            var user=matchArray[1];
            var domain=matchArray[2];
            
            // Start by checking that only basic ASCII characters are in the strings (0-127).
            
            for (i=0; i<user.length; i++) {
            if (user.charCodeAt(i)>127) {
            alert("Ths username contains invalid characters.");
            return false;
               }
            }
            for (i=0; i<domain.length; i++) {
            if (domain.charCodeAt(i)>127) {
            alert("Ths domain name contains invalid characters.");
            return false;
               }
            }
            
            // See if "user" is valid 
            
            if (user.match(userPat)==null) {
            
            // user is not valid
            
            alert("The username doesn't seem to be valid.");
            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("Destination IP address is invalid!");
            return false;
               }
            }
            return true;
            }
            
            // Domain is symbolic name.  Check if it's valid.
             
            var atomPat=new RegExp("^" + atom + "$");
            var domArr=domain.split(".");
            var len=domArr.length;
            for (i=0;i<len;i++) {
            if (domArr[i].search(atomPat)==-1) {
            alert("The domain name does not seem to be valid.");
            return false;
               }
            }
            
            /* domain name seems valid, but now make sure that it ends in a
            known top-level domain (like com, edu, gov) or a two-letter word,
            representing country (uk, nl), and that there's a hostname preceding 
            the domain or country. */
            
            if (checkTLD && domArr[domArr.length-1].length!=2 && 
            domArr[domArr.length-1].search(knownDomsPat)==-1) {
            alert("The address must end in a well-known domain or two letter " + "country.");
            return false;
            }
            
            // Make sure there's a host name preceding the domain.
            
            if (len<2) {
            alert("This address is missing a hostname!");
            return false;
            }
            
            // If we've gotten this far, everything's valid!
            return true;
}

function fcnRequireValue(fld)
{ // disallow a blank field
  if(!fld.value.length)
  { status= 'The ' + fld.name + ' field cannot be left blank.'; return false; }
  return true;
}

function fcnFixSSN(fld)
{ // tenacious SSN correction; fieldname isn't a big consideration, probably only one SSN per form 
  if(!fld.value.length) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  if(val.length = 0)
  { status= 'No Social Security Number was entered.'; return false; }
  val= val.replace(/\D/g,'');
  if( val.length < 9 )
  {
    status= 'The Social Security Number you provided is not long enough.';
    return false;
  }
  if( val.length > 9 )
  {
    status= 'The Social Security Number you provided is too long.';
    return false;
  }
  fld.value= val.substring(0,3) + '-' + val.substring(3,5) + '-' + val.substring(5,12);
  return true;
}

function fcnFixIntByObj(fld)
{ // integer check/complainer 
  if(!fld.value.length) return true; // blank fields are the domain of requireValue 
  var val= parseInt(fld.value);
  var id = fld.id;
  
  if(isNaN(val))
  { // parse error 
    //alert('The ' + fld.name + ' field must contain a whole number.');
    alert("The quantity field must contain a whole number");

	//place focus on field
	document.getElementById(id).focus();
	
	return false;
  }
  fld.value= val;
  return true;
}

function fcnFixIntByVal(fld)
{ // integer check/complainer 
  //if(fld == "") return true; // blank fields are the domain of requireValue 
  var val= parseInt(fld);
  
  if(isNaN(val))
  { // parse error 
	return false;
  }
  return true;
}

function fcnFixFloatByObj(fld)
{ // decimal number check/complainer 
  if(!fld.value.length) return true; // blank fields are the domain of requireValue 
  var val= parseFloat(fld.value);
  if(isNaN(val))
  { // parse error 
    status= 'The ' + fld.name + ' field must contain a number.';
    return false;
  }
  fld.value= val;
  return true;
}

function fcnFixFloatByVal(fld)
{ // decimal number check/complainer 
  if(fld == "") return true; // blank fields are the domain of requireValue 
  var val= parseFloat(fld);
  if(isNaN(val))
  { // parse error 
    return false;
  }
  return true;
}

function fcnFixMoney(fld)
{ // monetary field check
  if(!fld.value.length) return true; // blank fields are the domain of requireValue 
  var val= fld.value;
  if(val.indexOf('$') == 0)
    val= parseFloat(fld.value.substring(1,40));
  else
    val= parseFloat(fld.value);
  if(isNaN(val))
  { // parse error 
    status= 'The ' + fld.name + ' field must contain a dollar amount.';
    return false;
  }
  var sign= ( val < 0 ? '-': '' );
  val= Number(Math.round(Math.abs(val)*100)).toString();
  while(val.length < 2) val= '0'+val;
  var len= val.length;
  val= sign + ( len == 2 ? '0' : val.substring(0,len-2) ) + '.' + val.substring(len-2,len+1);
  fld.value= val;
  return true;
}