﻿function loadStates(cbo, id)
{
    //clear select options
    var iLength = cbo.options.length;
    for(i=0;i<iLength;i++)
    {
        cbo.options[0] = null;
    }

    //Add not selected option
    if(id == 'US')
        cbo.options[0] = new Option('Please Select a State...','');
    else if(id =='CA')
        cbo.options[0] = new Option('Please Select a Province...','');
    else
        cbo.options[0] = new Option('Please Select a County...','');
	
    var j = 1
    for(i=0;i<arrState.length;i++)
    {
        if(arrState[i][0] == id)
        {
	        //Add not selected option
	        cbo.options[j] = new Option(arrState[i][2], arrState[i][1]);
	        j++;
        }
    }
    
}
    
function validateForm(theFrm)
{

	var reason = "";

	//Check required fields
	reason += validateEmpty(theFrm.txtContactName);
	reason += validateEmpty(theFrm.txtStoreName);
	reason += validateEmpty(theFrm.txtAddress1);
	reason += validateEmpty(theFrm.txtCity);
	reason += validateEmpty(theFrm.txtEmail);
	reason += validateEmpty(theFrm.txtConfirmEmail);
	reason += validateEmpty(theFrm.txtZip);
	reason += validateEmpty(theFrm.txtPhone);
	reason += validateNotSelected(theFrm.cboState);
	
	if (reason != "") {
    		alert("Some fields need information:\n" + reason);
    		return false;
  	}

	//Validate data in fields
	reason += validateEmail(theFrm.txtEmail, theFrm.txtConfirmEmail);
	

	if (reason != "") {
    		alert("Some fields need correction:\n" + reason);
    		return false;
  	}
	
}

function validateBillingForm(theFrm)
{

	var reason = "";

	//Check required fields
	reason += validateEmpty(theFrm.txtContactName);
	reason += validateEmpty(theFrm.txtStoreName);
	reason += validateEmpty(theFrm.txtAddress1);
	reason += validateEmpty(theFrm.txtCity);
	reason += validateEmpty(theFrm.txtEmail);
	reason += validateEmpty(theFrm.txtConfirmEmail);
	reason += validateEmpty(theFrm.txtZip);
	reason += validateEmpty(theFrm.txtPhone);
	reason += validateNotSelected(theFrm.cboState);
	
	//check required billing fields
	reason += validateEmpty(theFrm.txtBillingAddress1);
	reason += validateEmpty(theFrm.txtBillingCity);
	reason += validateNotSelected(theFrm.cboBillingState);
	reason += validateEmpty(theFrm.txtBillingZip);
	
	//check required CC fields
	reason += validateEmpty(theFrm.txtCCName);
	reason += validateNotSelected(theFrm.cboCCType);
	reason += validateEmpty(theFrm.txtCCNumber);
	reason += validateNotSelected(theFrm.cboCCMonth);
	reason += validateNotSelected(theFrm.cboCCYear);
	reason += validateEmpty(theFrm.txtCCSecurity);
	
	if (reason != "") {
    		alert("Some fields need information:\n" + reason);
    		return false;
  	}

	//Validate data in fields
	reason += validateEmail(theFrm.txtEmail, theFrm.txtConfirmEmail);
	reason += validateCC(theFrm.txtCCNumber, theFrm.cboCCType);
	reason += validateCVC2(theFrm.txtCCSecurity, theFrm.cboCCType);

	if (reason != "") {
    		alert("Some fields need correction:\n" + reason);
    		return false;
  	}
  	
  	//Make sure they agree to terms
  	if(theFrm.chkAgree.checked == false)
  	{
  	    alert("You must agree to the terms of the program before placing your order.");
  	    return false;
  	}
  	
  	//enable controls
    document.getElementById("txtBillingAddress1").disabled = false;
    document.getElementById("txtBillingAddress2").disabled = false;
    document.getElementById("txtBillingCity").disabled = false;
    document.getElementById("txtBillingZip").disabled = false;
    
	
}

function validateEmpty(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "The required field " + fld.name + " has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function validateNotSelected(fld) {
    var error = "";
 
    if (fld.value == 0||fld.value == '') {
        fld.style.background = 'Yellow'; 
        error = "The required field " + fld.name + " has not been selected.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}


function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "You didn't enter a username.\n";
    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
        fld.style.background = 'Yellow'; 
        error = "The username is the wrong length.\n";
    } else if (illegalChars.test(fld.value)) {
        fld.style.background = 'Yellow'; 
        error = "The username contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}


function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
        error = "The password is the wrong length. \n";
        fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
        fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'White';
    }
   return error;
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld, fld2) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else if (!(fld.value == fld2.value)) {
        fld.style.background = 'Yellow';
	    fld2.style.background = 'Yellow';
        error = "The email address and confirm email do not match.\n";
    } else {
        fld.style.background = 'White';
	    fld2.style.background = 'White';
    }
    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";
        fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    }
    return error;
}

function validateCVC2(fld, fldType) {
    var error = "";    

    if (isNaN(parseInt(fld.value))) {
        error = "The security code contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (fldType.value == "AMERICAN EXPRESS"){
        if(!(fld.value.length == 4)) {
        error = "The security code is the wrong length. American Express requires a 4-digit code on the front of the card.\n";
        fld.style.background = 'Yellow';
        }    
    } else if (fldType.value == "DISCOVER" || fldType.value == "MASTERCARD" || fldType.value == "VISA"){
        if(!(fld.value.length == 3)) {
        error = "The security code is the wrong length. Your CC requires a 3-digit code on the back of the card.\n";
        fld.style.background = 'Yellow';
        }    
    }
    return error;
}

function validateCC(fld, fldType){
    var error = "";
    
    if(fldType.value == "AMERICAN EXPRESS")
    {
        if(!isAmex(fld.value))
        {
            error = "The AMEX card is invalid. Make sure to include all numbers without spaces.\n";
            fld.style.background = 'Yellow';
        }
    }
    else if(fldType.value == "DISCOVER")
    {
        if(!isDiscover(fld.value))
        {
            error = "The Discover card is invalid. Make sure to include all numbers without spaces.\n";
            fld.style.background = 'Yellow';
        }
    }
    else if(fldType.value == "MASTERCARD")
    {
        if(!isMC(fld.value))
        {
            error = "The Mastercard is invalid. Make sure to include all numbers without spaces.\n";
            fld.style.background = 'Yellow';
        }
    }
    else if(fldType.value == "VISA")
    {
        if(!isVisa(fld.value))
        {
            error = "The Visa card is invalid. Make sure to include all numbers without spaces.\n";
            fld.style.background = 'Yellow';
        }
    }
    return error;
}

/*---------------------------------------------------------------*/
/*                                                               */
/* Function  : isVisa()                                           */
/* Purpose   : Validate CC number following visa specs      */
/*                                                                  */
/*                                                               */
/* Parameters:     cc - the cc number                                                       */
/*                                                               */
/* Returns   : boolean                                              */
/*                                                               */
/* Usage     : isVisa(cc)                                           */
/*---------------------------------------------------------------*/

     function isVisa( cc )
     {
          if( (cc.substring(0,1) == 4) && (cc.length == 16) 
          || (cc.length == 13) )
          {
               return isCreditCard( cc );
          }
          return (false);
     }


/*---------------------------------------------------------------*/
/*                                                               */
/* Function  : isMC()                                           */
/* Purpose   : Validate CC number following MasterCard specs      */
/*                                                                  */
/*                                                               */
/* Parameters:     cc - the cc number                                                       */
/*                                                               */
/* Returns   : boolean                                              */
/*                                                               */
/* Usage     : isMC(cc)                                           */
/*---------------------------------------------------------------*/
     function isMC( cc )
     {
          if( (cc.length == 16) && (cc.substring(0,2) == 51) 
          || (cc.substring(0,2) == 52) || (cc.substring(0,2) == 53)
          || (cc.substring(0,2) == 54) || (cc.substring(0,2) == 55) )
          {
               return isCreditCard( cc );
          }
          return (false);
     }
/*---------------------------------------------------------------*/
/*                                                               */
/* Function  : isAmex()                                           */
/* Purpose   : Validate CC number following AMEX specs      */
/*                                                                  */
/*                                                               */
/* Parameters:     cc - the cc number                                                       */
/*                                                               */
/* Returns   : boolean                                              */
/*                                                               */
/* Usage     : isAmex(cc)                                           */
/*---------------------------------------------------------------*/
     function isAmex( cc )
     {
          if( (cc.length == 15) && (cc.substring(0,2) == 34) 
                               || (cc.substring(0,2) == 37) )
          {
               return isCreditCard( cc );
          }
          return (false);
     }
/*---------------------------------------------------------------*/
/*                                                               */
/* Function  : isDiscover()                                           */
/* Purpose   : Validate CC number following Discover specs      */
/*                                                                  */
/*                                                               */
/* Parameters:     cc - the cc number                                                       */
/*                                                               */
/* Returns   : boolean                                              */
/*                                                               */
/* Usage     : isDiscover(cc)                                           */
/*---------------------------------------------------------------*/
     function isDiscover( cc )
     {
     if( (cc.length == 16) && (cc.substring(0,4) == 6011) )
          {
               return isCreditCard( cc );
          }
          return (false);
     }


function isCreditCard(ccNumb) 
{  // v2.0
    var valid = "0123456789"  // Valid digits in a credit card number
    var len = ccNumb.length;  // The length of the submitted cc number
    var iCCN = parseInt(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

    // 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
        }
      }
    }
    return bResult; // Return the results
}
