
     // Quikstore order form javascripts



     // 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",
                                "Email_Verify");

 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 == "wire"){
     requiredFields[len + 1] = "Bank_Name";
     requiredFields[len + 2] = "Name_On_Account";
     requiredFields[len + 3] = "Account_Number";
     requiredFields[len + 4] = "ABA_Routing_Code";
 }
 if(type == "check"){
     return true;
 }

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

     for(j = 0; j < requiredFields.length; j++){
          var requiredField = document.forms[0].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[0].elements[requiredFields[j]].focus();
               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[0].elements.length; i++){
     var inType = document.forms[0].elements[i].type;
     if(inType == "text"){
        var cookieName = document.forms[0].elements[i].name;
        var cookieValue = document.forms[0].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 for a carriage return - force clicking the button not the enter key
    var Keypress = onKeyPress()
    if(!Keypress){
       return false;
    }
     // 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[0].elements.length -1; i++){
     var inType = document.forms[0].elements[i].type;
     var fieldName = document.forms[0].elements[i].name;
     var fieldCookie = COOKIES[fieldName];

      if((inType == "text")&&
        (fieldCookie != null)&&
        (fieldCookie != "undefined")){
            if(document.forms[0].elements[i]){
                document.forms[0].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[0].elements[i].value = custNum;
          }
     }
   }
}


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

     // Simply retreives a cookie

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[0].elements[cardNumField];
     var entry = document.forms[0].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 validateSubtotal(){
 var subTotal = document.forms[1].checkSubtotal.value;
 var subTvalue = subTotal.substring(2,subTotal.length);
 subTvalue = subTvalue - 0

 if(subTvalue < 25){
 alert("There is a minimum order of $25.00.  Please change the quantities or add" + "\n\n" +
 "another item! Be sure to hit the MODIFY CART button on QTY changes.");
 return false;
 }

 return true;
 }
// ------------------------------------------------------------------
// Used on the checkout pages to make sure the Enter has not been pressed
function onKeyPress () {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
alert("Please click on the Submit Secure Order Button instead of pressing the Enter Key.");
return false
}
return true
}
document.onkeypress = onKeyPress;
// --

// ------------------------------------------------------------------
// Used on Shipping Screen to validate the States
function checkState(form){
var selectIndex;
var CountryValue;
var fullCountry;

for(i = 0; i < form.elements.length -1; i++){
     if(form.elements[i].name == "22_destCountry"){
          selectIndex = form.elements[i].selectedIndex;
          CountryValue = form.elements[i].options[selectIndex].value;
          fullCountry = form.elements[i].options[selectIndex].text;
     }
     if(form.elements[i].name == "Mailing_State"){
          var stateValue = form.elements[i].value;
          if((CountryValue == "US")&&(stateValue == "")){
            alert("\nSince you selected " + fullCountry + " for your country, you" +
                  "\nmust enter your state abbreviation before going to checkout.\n");
            form.elements[i].focus();
            return false;
          }
     document.cookie = "Mailing_State=" + escape(stateValue) + "; path=/";
     }
}
return true;
}


// ------------------------------------------------------------------
// Used on all pages for spammers
function emlhandler(x,y,z){
// x = acct, y = image, z = alt text
 var a,b,c,d,e,f,g,h,i
 a='<a href=\"mai'
 if (x) b=x
 else b='info';
 c='\">'
 a+='lto:'
 b+='@'
 e='</a>'
 if (z) f=z
 else f='';
 b+='compudirect.net'
 g='<img src=\"/images/'
 if (y) { //image
  	i='\" alt=\" '+ f +' \" border=\"0\">';
	d=g+y+i;
	document.write(a+b+c+d+e)
	return true;
}
if (z) d=z;
else d=b;
document.write(a+b+c+d+e)
return true;
}

// ------------------------------------------------------------------
// Validate email addresses

function emailCheck (emailStr) {
/* 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 +")*$")
/* Domains that we will not accept: */
var badEmailDomains = new Array("yahoo.com",
                                "hotmail.com");

/* 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("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// 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
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

for(i=0;i<=badEmailDomains.length;i++){
    if(domain == badEmailDomains[i]){
        alert("I'm sorry but we cannot ship to customers with free email addresses. We are sorry for the inconvienience but this is necessary as a security precaution. For orders, please phone them in at 866-OKI4YOU.");
        return false;
    }
}

// If we've gotten this far, everything's valid!
return true;
}

// Gary: popup code
function popup(mylink, windowname, w, h, scrl)
{
if (! window.focus)return true;
var href;
var width;
var height;
var scrolly;
if (w == '')
	width = '400';
else
	width = w;
	
if (h == '')
	height = '500';
else
	height = h;
	
if (scrl == '')
	scrolly = 'no';
else
	scrolly = scrl;
	
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
window.open(href, windowname, 'width='+width+',height='+height+',scrollbars='+scrolly);
return false;
}
