
     // Quikstore order form javascripts

     // The number of the <form> where the fields are.
     // This is zero based so the default is 0.
     // If you add a form above this, let's say in the
     // header.html template, you need to change this to 1.

var formNumber = 0;

     // These javascripts are used to validate
     // entries in the form fields and also to
     // save the user data in a cookie

     // The first two functions below are where
     // you would set the field names should you
     // need to add some to the list(s).

     // 1. function requiredFields() validates that the
     //    entries are filled in when the form is
     //    submitted.

     // 2. function saveUserInfo() sets a single cookie for each
     //    that contains all of the information in all of the form
     //    fields used in the orderform. There is also a list of
     //    fields that are NOT saved when this function is executed.
     //    You can add to this list as needed.

     // All remaining functions below are basically private
     // functions used by the main 2 functions above.


// -------------------------------------------------------------------
function requiredFields(type){

     // Setup an array of the required
     // form field names to validate:

 var requiredFields = new Array("Billing_Name",
                                "Billing_Address",
                                "Billing_City",
                                "Billing_State",
                                "Billing_Zip",
                                "Billing_Country",
                                "Billing_Phone",
                                "Email_Address");

 var len = requiredFields.length -1;

     // Add appropriate fields for
     // credit cards and checks

 if(type == "credit_card"){
     requiredFields[len + 1] = "Card_Number";
     requiredFields[len + 2] = "Name_On_Card";
     requiredFields[len + 3] = "Expire_Date";
 }
 if(type == "check"){
     requiredFields[len + 1] = "Bank_Name";
     requiredFields[len + 2] = "Name_On_Account";
     requiredFields[len + 3] = "Account_Number";
     requiredFields[len + 4] = "ABA_Routing_Code";
 }

     // Loop through the form fields and
     // test each of the required fields

     for(j = 0; j < requiredFields.length; j++){
          var requiredField = document.forms[formNumber].elements[requiredFields[j]].value;
          if(requiredField == ""){
               var label = "";
               for (i=0; i < requiredFields[j].length; i++) {
                    character = requiredFields[j].charAt(i);
                    if ("_".indexOf(character) != -1){
                         label += " ";
                    }
                    else{
                         label += character;
                    }
               }
               alert("You forgot to fill in the \"" + label + "\" field.\n" +
                     "This field is required before processing your order.");
               document.forms[formNumber].elements[requiredFields[j]].focus();
               return false;
          }
     }

 if(type == "credit_card"){
     if(!checkExpireDate()){
          return false;
     }
 }

return true;
}

// -------------------------------------------------------------------
function saveUserInfo(type){

     // This function saves the data from the
     // orderform in a single cookie called
     // "userInfo". This cookie is saved in
     // HEX format so that it makes it much
     // harder to read.

     // This is a list of credit card and
     // check fields that are NOT saved to
     // cookies

var notSaved = new Array();

if(type == "credit_card"){
     notSaved[0] = "Name_On_Card";
     notSaved[1] = "Card_Number";
     notSaved[2] = "Expire_Date";
}
if(type == "check"){
     notSaved[0] = "Bank_Name";
     notSaved[1] = "Account_Number";
     notSaved[2] = "Name_On_Account";
     notSaved[3] = "ABA_Routing_Code";
}

     // create and set the hex encrypted
     // userInfo cookie

 var userCookie = "";

 for(i = 0; i < document.forms[formNumber].elements.length; i++){
     var inType = document.forms[formNumber].elements[i].type;
     if(inType == "text"){
        var cookieName = document.forms[formNumber].elements[i].name;
        var cookieValue = document.forms[formNumber].elements[i].value;
        var cookieLen = cookieValue.length;

        // Set cookies if they are not credit card fields
        // We set those fields blank.

        for(j = 0; j < notSaved.length; j++){
          if(cookieName == notSaved[j]){
               cookieValue = "";
               break;
          }
        }
        if(cookieValue != ""){

          // Replace the colons, equal signs and commas
          // so they don't screw with the cookie.

          var strippedValue = "";
          for (k=0; k < cookieValue.length; k++) {
               var character = cookieValue.charAt(k);
               if((character == ":")||(character == "=")||(character == ",")){
                    character = " ";
               }
               strippedValue += character;
          }

               // create the cookie

          if(userCookie == ""){
               userCookie += cookieName + "=" + strippedValue;
          }
          else{
               userCookie += ":" + cookieName + "=" + strippedValue;
          }
        }
     }
   }

     // Convert to hex and write the cookie

var encStr = str2hex(escape(userCookie));
setCookie('userInfo',encStr);
}

// -------------------------------------------------------------------
function checkRequiredFields(type){

     // Checks to make sure the various
     // form fields are filled in

     // First check the required fields

     var Required = requiredFields(type);
     if(!Required){
          return false;
     }

     if(type == "credit_card"){

          // Then the payment fields
          // Comment (//) these next to lines for testing:

          var Payment = checkCard();
          if(!Payment){
               return false;
          }
     }
     else{
          return true;
     }
}

// -------------------------------------------------------------------
function formFill(){

     // Loads all of the form fields
     // when the order form is displayed.

   var myCookie = getValue('userInfo');
   var strCookie = myCookie.split(':');
   var COOKIES = new Array();
   for(i=0; i < strCookie.length; i++){
     var PAIRS = strCookie[i].split('=');
     COOKIES[PAIRS[0]] = PAIRS[1];
   }

   for(i = 0; i < document.forms[formNumber].elements.length -1; i++){
     var inType = document.forms[formNumber].elements[i].type;
     var fieldName = document.forms[formNumber].elements[i].name;
     var fieldCookie = COOKIES[fieldName];

     if((inType == "text")&&
        (fieldCookie != null)&&
        (fieldCookie != "undefined")){
          document.forms[formNumber].elements[i].value = fieldCookie;
     }

          // Set the customer number so it can be used again

     if((inType == "hidden")&&(fieldName == "Customer_Number")){
          var custNum = getCookie("Customer_Number");
          if((custNum != null)&&(custNum != "")){
               document.forms[formNumber].elements[i].value = custNum;
          }
     }
   }
}


// -------------------------------------------------------------------
function getCookie(name){

     // Simply retreives a cookie

if((name == "")||(name == null)||(name == "undefined")){
    return null;
}

var cname = name + "=";
var dc = document.cookie;

     if (dc.length > 0) {
          begin = dc.indexOf(cname);
          if (begin != -1) {
               begin += cname.length;
               end = dc.indexOf(";", begin);
               if (end == -1) end = dc.length;
               return unescape(dc.substring(begin, end));
          }
     }
return null;
}

// -------------------------------------------------------------------
function setCookie(name, value) {

     // Simply sets a cookie that's
     // good for one year.

     var now = new Date();
     var then = new Date(now.getTime() + 31536000000);
     document.cookie = name + "=" + escape(value) + "; expires=" + then.toGMTString() + "; path=/";
}
// -------------------------------------------------------------------
function getValue(name) {

     // Gets a hex cookie and returns the
     // string value.

     var value = getCookie(name);
     var deStr = unescape(hex2str(value));
return deStr;
}


// -------------------------------------------------------------------
function isCreditCard(st) {

     // Tests the credit card number.
     // Encoding only works on cards
     // with less than 19 digits

     if (st.length > 19)
          return (false);
     sum = 0; mul = 1; l = st.length;
     for (i = 0; i < l; i++) {
          digit = st.substring(l-i-1,l-i);
          tproduct = parseInt(digit ,10)*mul;
          if (tproduct >= 10)
               sum += (tproduct % 10) + 1;
          else
               sum += tproduct;
          if (mul == 1)
               mul++;
          else
               mul--;
     }
     if ((sum % 10) == 0)
          return (true);
     else
          return (false);
}
// -------------------------------------------------------------------
function strip(val) {

     // Strips the dashes, spaces, etc
     // from the credit card number

val = "" + val;
     if (!val)
          return "";
     var result = "";
     for (i=0; i < val.length; i++) {
          character = val.charAt(i);
          if ("0123456789".indexOf(character) != -1)
          result += character;
     }
return result;
}
// -------------------------------------------------------------------
function checkCard(){

     // Checks the credit card field for
     // empty and invalid card entries

     var cardNumField = "Card_Number";

     var cardField = document.forms[formNumber].elements[cardNumField];
     var entry = document.forms[formNumber].elements[cardNumField].value;
     if(entry == ""){
          alert('You did not enter a valid credit card number\n' +
               'Please check your entry and try again.');
          cardField.focus();
          return false;
     }
     var strippedEntry = strip(entry);
     if((!isCreditCard(strippedEntry))||(strippedEntry.length == 0)){
          alert('The credit card number you entered could not be validated.\n' +
                'Please check the number and try again.');
          cardField.focus();
          cardField.select();
          return false;
     }
return true;
}


// -------------------------------------------------------------------
function str2hex(inStr) {

     // Converts a normal string to a hex string

   if(inStr == null){ return null; }
   var l = inStr.length;
   var i=0;
   var retStr = new String;
   for(i=0;i<l;i++) {
      var uStr = inStr.charCodeAt(i);
      retStr = retStr + twoCharHex(uStr);
   }
return retStr.toUpperCase();
}

// -------------------------------------------------------------------
function hex2str(inStr) {

     // Converts a hex string to normal string

   if(inStr == null){ return null; }
   var l = inStr.length;
   var retStr = new String;
   var i=0;
   for(i=0; i<l; i+=2) {
     retStr = retStr + String.fromCharCode("0x" + inStr.substr(i,2));
   }
return retStr;
}

// -------------------------------------------------------------------
function twoCharHex(i) {
   if(i==0){ return "00"; }
   else if (i < 16){ return "0" + i.toString(16); }
   return i.toString(16);
}

// -------------------------------------------------------------------
function checkExpireDate() {

     // Get the field value
     var expireField = document.forms[formNumber].elements['Expire_Date'].value;

     // Strip off the non-numeric characters
     var cleanExpire = strip(expireField);
     document.forms[formNumber].elements['Expire_Date'].value = cleanExpire;

     // check the length
     if(cleanExpire.length < 4){
          alert("The expiration date you entered is invalid.\n" +
                "Please enter a valid expiration date");
          document.forms[formNumber].elements['Expire_Date'].focus();
          return false;
     }

     // make sure the date is in the future
     var expireMonth = cleanExpire.substring(0,2) -1;
     var expireYear = "20" + cleanExpire.substring(2,4);
     var today = new Date();
     var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
     var expireDay = monthDays[expireMonth];
     var expire = new Date(expireYear,expireMonth,expireDay);
     if(expire < today){
          alert("The expiration date you entered is invalid.\n\n" +
                "Please enter a valid expiration date for the credit card.");
          document.forms[formNumber].elements['Expire_Date'].focus();
          return false;
     }

return true;
}
