function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
} 

function parseVal(val)
{
   while (val.charAt(0) == '0')
      val = val.substring(1, val.length);

   return val;
}

function fieldinerror(fld) {
    fld.style.background = 'Yellow';
    fld.focus();
}

function validateCheckbox(fld, truefalse) {
    //alert('VCb:'+ fld);
    var error="";
    var checkedvalue = fld.checked;
    //alert('checkedvalue!=truefalse:'+(checkedvalue!=truefalse));
    if (checkedvalue==truefalse) {
        fld.style.background = 'White';
    } else {
        fieldinerror(fld);
        error = "You must select the checkbox.\n";
    }
    return error;
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    
    if (fld.value == "") {
        error = "You didn't enter an email address.\n";
        fieldinerror(fld);
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fieldinerror(fld);
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fieldinerror(fld);
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fieldinerror(fld);
        error = "You didn't enter a username.\n";
    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
        fieldinerror(fld);
        error = "The username is the wrong length.\n";
    } else if (illegalChars.test(fld.value)) {
        fieldinerror(fld);
        error = "The username contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    } 
    return error;
}

function validatePostalCode(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     
    // Check that a Canadian postal code is valid
    if (stripped.length>0) {
        if (stripped.length == 6 && stripped.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/)!= -1)  {
            fld.style.background = 'White';
        }
        else {
            fieldinerror(fld);
            error = "The postal code is invalid.\n";
        }
    }
    return error;
}


function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        error = "You didn't enter a phone number.\n";
        fieldinerror(fld);
    } else if (isNaN(parseVal(stripped))) {
        error = "The phone number contains illegal characters.\n";
        fieldinerror(fld);
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        fieldinerror(fld);
    } else {
        fld.style.background = 'White';
    }
    return error;
}
                
function validateEmpty(fld) {
    var error = "";
    var trimmed = fld.value.replace(/^\s+|\s+$/g, '') ;  
    
    if (trimmed.length == 0) {
        fieldinerror(fld);
        error = "The required field " + fld.name + " has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;   
}

function validateCreditCardDate(month,year){
    var error = "";
    var bResult=true;
    var ccdate = month.value;
    //alert ('1');
    var d = new Date();
    
    if (!(month.value.length == 2)) {
        if (!(month.value.length == 1)) {
          bResult=false;
        } else {
        //could be just missing zero at beginning
            month.value='0'+month.value;
        }
    }
    //alert ('2');
    if(bResult){
        //alert ('2.1');
        var smonth = month.value;
        var syear = year.value;
        //alert ('2.2:' + syear);
        var iyear = parseVal(syear);
        //alert ('2.3:' + smonth);
        var imonth = parseVal(smonth);
        //alert ('2.3.1:' + imonth);
        var fullyear = d.getFullYear();
        var nextmonth = d.getMonth()+1;
        //alert ('2.4:' + fullyear);
        //alert ('2.4.1:' + nextmonth);
        if(iyear==fullyear) {
          if(imonth<(d.getMonth()+1)) {
            //alert ('2.5:');
            bResult=false;
          }
        }else {
            if(iyear<fullyear) {
              //alert ('2.6:');
              bResult=false;
            }
        }
    }

    //alert ('3');
    if(!bResult){
        fieldinerror(year);
        fieldinerror(month);
        error = "Invalid Credit Card Expiration Date\n"
    } else {
        month.style.background = 'White';
        year.style.background = 'White';
    }
    //alert ('4');
    return error;   
}


function validateCreditCardNumber(fld) {
    /* Created by: David Leppek

    Basically, the alorithum takes each digit, from right to left and muliplies each second
    digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
    the multiple are then added together for a new number (1 + 2 = 3). You then add up the 
    string of numbers, both unaltered and new values and get a total sum. This sum is then
    divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
    name Mod 10 or Modulus 10. */
    var error = "";
    var ccNumb = fld.value;
    var valid = "0123456789";  // Valid digits in a credit card number
    var len = ccNumb.length;  // The length of the submitted cc number
    var iCCN = parseVal(ccNumb);  // integer of ccNumb
    var sCCN = ccNumb.toString();  // string of ccNumb
    sCCN = sCCN.replace (/^s+|s+$/g,'');  // strip spaces
    var iTotal = 0;  // integer total set at zero
    var bNum = true;  // by default assume it is a number
    var bResult = false;  // by default assume it is NOT a valid cc
    var temp;  // temp variable for parsing string
    var calc;  // used for calculation of each digit

    //alert ('vccN 1:');
    // Determine if the ccNumb is in fact all numbers
    for (var j=0; j<len; j++) {
      temp = "" + sCCN.substring(j, j+1);
      if (valid.indexOf(temp) == "-1"){bNum = false;}
    }

    // if it is NOT a number, you can either alert to the fact, or just pass a failure
    if(!bNum){
      /*alert("Not a Number");*/bResult = false;
    }

    // Determine if it is the proper length 
    if((len == 0)&&(bResult)){  // nothing, field is blank AND passed above # check
      bResult = false;
    } else{  // ccNumb is a number and the proper length - let's see if it is a valid card number
      if(len >= 15){  // 15 or 16 for Amex or V/MC
        for(var i=len;i>0;i--){  // LOOP throught the digits of the card
          calc = parseInt(iCCN) % 10;  // right most digit
          calc = parseInt(calc);  // assure it is an integer
          iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
          i--;  // decrement the count - move to the next digit in the card
          iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
          calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
          calc = calc *2;                                 // multiply the digit by two
          // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
          // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
          switch(calc){
            case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
            case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
            case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
            case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
            case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
            default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
          }                                               
        iCCN = iCCN / 10;  // subtracts right most digit from ccNum
        iTotal += calc;  // running total of the card number as we loop
      }  // END OF LOOP
      if ((iTotal%10)==0){  // check to see if the sum Mod 10 is zero
        bResult = true;  // This IS (or could be) a valid credit card number.
      } else {
        bResult = false;  // This could NOT be a valid credit card number
        }
      }
    }
    //alert ('vccN 10:');
    // change alert to on-page display or other indication as needed.
    if(!bResult){
        fieldinerror(fld);
        error = "This is not a valid Credit Card Number\n"
    } else {
        fld.style.background = 'White';
    }
    return error;   
}

