function valve_win () {
  window.open('https://images.westpacsupply.com/ValveSpecs1.htm','ValveSpecs','top=0,left=150,width=800,height=800,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
}

function selectAll(listbox) {
  var i;
  for (i = 0; i < listbox.options.length; i++) {
      listbox.options[i].selected = true;
  }
  return false;
}

function toggle_checks (formobj) {
/**********************************************************
 * reverse the checkedness of all checkboxes in this form *
 **********************************************************/
 var i;

 for (i = 0; i < formobj.elements.length; i++) {
     if (formobj.elements[i].type == "checkbox") {
         if (formobj.elements[i].checked) {
             formobj.elements[i].checked = false;
         } else {
             formobj.elements[i].checked = true;
         }
     }
 }
}

function toggle_some_checks (formobj, pattern) {
/****************************************************************
 * reverse the checkedness of any checkboxes that match pattern *
 ****************************************************************/
 var i;

 for (i = 0; i < formobj.elements.length; i++) {
     if (formobj.elements[i].type == "checkbox") {
         var result;
         var efield = formobj.elements[i].name;
         result = efield.match(pattern);
         if (result != null) {
             if (formobj.elements[i].checked) {
                 formobj.elements[i].checked = false;
             } else {
                 formobj.elements[i].checked = true;
             }
         }
     }
 }
}

function opt_smartinteger (t) {
  // assist user in entering a valid integer
  // but a blank is allowed. This is the optional part!
  var result;
  var pattern = /^\d+$/;
  var efield = t.value;
 
  result = efield.match(pattern);
  if (result != null) {
      return true;
  } else {
      t.value = '';
      alert("Please enter a number");
      return true;
  }

}
function opt_smartemail (t) {
  // assist user in entering a valid email address
  // but a blank is allowed. This is the optional part!
  var result;
  var pattern = /^[\w\-\.]+@[\w\-\.]+$/;
  var efield = t.value;
 
  result = efield.match(pattern);
  if (result != null) {
      return true;
  } else {
      t.value = '';
      alert("Please enter a valid email address");
      return true;
  }

}

function opt_smartstring (t) {
  // assist user in entering words, numbers, dashes, underscores and a space
  // but a blank is allowed. This is the optional part!
  var result;
  var pattern = /^[\w\-\s\.]+$/;
  var efield = t.value;
 
  result = efield.match(pattern);
  if (result != null) {
      return true;
  } else {
      t.value = '';
      if (efield != '') {
          alert("Only letters, numbers, spaces, underscores, dots and dashes are allowed");
      }
      return true;
  }
}

function opt_smartstring2 (t) {
  // assist user in entering words, numbers, dashes, underscores
  // no blanks. This is the optional part!
  var result;
  var pattern = /^[\w\-\.]+$/;
  var efield = t.value;
 
  result = efield.match(pattern);
  if (result != null) {
      return true;
  } else {
      t.value = '';
      alert("Only letters, numbers, underscores, dots and dashes are allowed");
      return true;
  }
}

function opt_smartphone(t) {
// Check for correct phone number
  var result;
  var pattern = /^\d{10}$/;
  var efield = t.value;
  efield = strip_non_numeric(efield);
 
  result = efield.match(pattern);
  if (result != null) {
      return true;
  } else {
      t.value = '';
      alert("Please enter a valid phone number");
      return true;
  }
}

function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if (isNaN(num)) num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if (cents<10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
      num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
  }
  return (((sign)?'':'-') + num + '.' + cents);
}

function strip_non_numeric(textval) {
/*********************************************
 * formats string for only digits characters *
 *********************************************/
  var v = "0123456789";
  var newtext;
  var i;
  var letter;
  for (i=0; i<textval.length; i++) {
      letter = textval.charAt(i);
      if (v.indexOf(letter,0) != -1) {
          newtext += letter;
      }
  }
  return newtext;
}

function opt_smartdate (t) {
  // assist user in entering a valid date (mm/dd/yyyy)
  // but a blank is allowed. This is the optional part!
  // It converts 4 digit years to 2 digit years. It looks for
  // leap year correctness and defaults to today's date.
  var result;
  var pattern_1d = /^\d$/;
  var pattern_2d = /^\d\d$/;
  var pattern_3ds = /^(\d)(\d\d)$/; // assume m-dd
  var pattern_4d = /^\d\d\d\d$/;
  var pattern_4ds = /^(\d\d)(\d\d)$/; // assume mm-dd
  var pattern_6d = /^(\d\d)(\d\d)(\d\d)$/;
  var pattern_8d = /^(\d\d)(\d\d)(\d\d\d\d)$/;
  var pattern_6ds = /^(\d\d)\/(\d\d)\/(\d\d)$/;
  var pattern_8ds = /^(\d\d)\/(\d\d)\/(\d\d\d\d)$/;
  var pattern_garbage = /^([a-zA-Z]+)$/;
  var datefield = t.value;
  var ok = 0; // assume garbage
                                                                                                        
  if (datefield == ".") {
      datefield = get_month() + "/" + get_day() + "/" + get_fullyear();
  }

  // convert dashes and dots to dashes to slashes
  if (datefield != null) {
      datefield = (datefield.split("-")).join("/");
      datefield = (datefield.split(".")).join("/");
  } else {
     t.value = '';
     return true;
  }
  result = datefield.match(pattern_garbage);
  if (result != null) {
      t.value = '';
      return true;
  }

  result = datefield.match(pattern_8d);
  if (result != null) {
      datefield = result[1] + '/' + result[2] + '/' + result[3];
      ok = 1;
  }
  result = datefield.match(pattern_8ds);
  if (result != null) {
      ok = 1;
  }

  result = datefield.match(pattern_6d);
  if (result != null) {
      datefield = result[1] + '/' + result[2] + '/' + result[3];
      ok = 1;
  }
  result = datefield.match(pattern_6ds);
  if (result != null) {
      ok = 1;
  }

  result = datefield.match(pattern_3ds);
  if (result != null) {
      datefield = '0' + result[1] + '/' + result[2] + '/' + get_year();
      ok = 1;
  }
  result = datefield.match(pattern_4ds);
  if (result != null) {
      datefield = result[1] + '/' + result[2] + '/' + get_year();
      ok = 1;
  }
  if (ok != 1) {
      t.value = '';
      return true;
  }
                                                                                                        
  // Assume now its properly formatted with dashes. Split into 3 fields: mm dd yyyy
  var a = datefield.split("/");
  if ((a[0] == "") || (a[0] == null)) a[0] = get_month();
  result = a[0].match(pattern_1d); // one digit month test
  if (result != null) a[0] = "0" + a[0]; // matched one digit month
  result = a[0].match(pattern_2d); // 2 digit month test
  if (result == null) a[0] = get_month(); // not 2 digit month, use today
  if ((a[0] > 12) || (a[0] < 1)) a[0] = get_month();
                                                                                                        
  if ((a[1] == "") || (a[1] == null)) a[1] = get_day();
  result = a[1].match(pattern_1d); // 1 digit day test
  if (result != null) a[1] = "0" + a[1]; // matched 1 digit day
  result = a[1].match(pattern_2d); // 2 digit day test
  if (result == null) a[1] = get_day(); // not 2 digit day, use today
  if (a[1] < 1) a[1] = get_day();
                                                                                                        
  if ((a[2] == "") || (a[2] == null)) a[2] = get_year();
  result = a[2].match(pattern_2d); // 2 digit year test
  if (result == null) {
      result = a[2].match(pattern_4d); // 4 digit year test
      if (result == null) {
          // not 2 or 4 digit year, use this year
          a[2] = get_year();
      }
  } else {
      // 2 digit year, convert to 4 digit year
      a[3] = get_fullyear();
      a[3] = a[3].substr(0,2); // get century
      a[2] = a[3] + a[2]; // convert to 4 digits
  }
                                                                                                        
  var lastdayofmonth = get_last_day(a[0],a[2]);
  if (a[1] > lastdayofmonth) a[1] = lastdayofmonth;
                                                                                                        
  t.value = a[0] + "/" + a[1] + "/" + a[2];
  return true;
}

function validateCreditCard(w) {
  w.value = strip_non_numeric(w);

  // validate number
  var a;
  var c;
  var i;
  var j;
  var k;
  var m;
  j = w.length / 2;
  if (j < 6.5 || j > 8 || j == 7) return false;
  k = Math.floor(j);
  m = Math.ceil(j) - k;
  c = 0;
  for (i=0; i<k; i++) {
    a = w.charAt(i*2+m) * 2;
    c += a > 9 ? Math.floor(a/10 + a%10) : a;
  }
  for (i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
  return (c%10 == 0);
}

function qcount(q, orig, min, max, pack) {
  // also tests for non whole numbers
  // pack means multiple of, 2 means only even numbers are allowed
                                                                                                    
  var retvalue;
  var quantity = q.value; // current value of input box
  var testval = Math.round(quantity);
                                                                                                    
  if (testval != quantity) {
      alert("Only whole numbers are allowed");
      q.value = orig;
      return false;
  }
                                                                                                    
  testval = quantity % pack; // modulo function
  if (testval != 0) {
      // not multiple of pack size
      alert("Quantities must be a multiple of " + pack);
      q.value = orig;
      return false;
  }
                                                                                                    
  // Up And Down Changes allowed
  if (max != -1) {
      if (quantity > max) {
          alert("Quantities above " + max + " are not allowed");
          q.value = orig;
          return false;
      }
  }
  if (min != -1) {
      if (quantity < min) {
          alert("Quantities below " + min + " are not allowed");
          q.value = orig;
          return false;
      }
  }
  if (quantity != orig) {
      haveChange = true; // if user fails to hit save button
  }
  return true;
}

function digits_only (field, event) {
/************************************************
 * allow enter key, tab and digits only         *
 * usage: onkeypress="digits_only(this,event);" *
 # 48-57 = digits, enter, tab, del, backsp      *
 ************************************************/
  var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  //var keychar = String.fromCharCode(keycode);
                                                                                                    
  if (keycode == 46) {
      //return false; // period
      return true; // period
  }
  if (keycode >= 48 && keycode <= 57) {
      return true; // digits
  }
  if (keycode == 13) {
      return true; // enter
  }
  if (keycode == 8) {
      return true; // tab
  }
  if (keycode == 9) {
      return true; // del
  }
  if (keycode == 46) {
      return true; //backspace
  }
                                                                                                    
  return false;
}

function confirmChange(field) {
  var $ok;
  $ok = confirm('You currently have parts in your cart.\nChanging to a different customer account will clear your cart.\nDo you wish to continue?');
  if ($ok) field.form.submit();
  return $ok;
}

function showCustSelected(dropdown, origValue, cartItemCount) {
// fill in a span/div tag with customer name & address info 
  var custid;
  var ok = true;
  if (cartItemCount > 0) {
      //ok = confirm('Changing the customer account will clear your cart.\nDo you wish to continue?');
  }
  if (ok) {
    dropdown.form.submit();
  } else {
    // change back to original selected option
    var i;
    for (i = 0; i < dropdown.options.length; i++) {
        if (dropdown.options[i].value == origValue) {
            dropdown.options[i].selected = true;
        }
    }
    return false;
  }
}

function showCustSelected2(dropdown, origValue, cartItemCount, recallflag) {
// fill in a span/div tag with customer name & address info
  var custid;
  var ok = true;
  if (cartItemCount > 0) {
      if (recallflag == "Y") {
          ok = confirm('Changing the customer account will clear your cart and lose changes on this recalled order.\nDo you wish to continue?');
      } else {
          //ok = confirm('Changing the customer account will clear your cart.\nDo you wish to continue?');
      }
  }
  if (ok) {
    dropdown.form.submit();
  } else {
    dropdown.value = origValue;
    return false;
  }
}

function refreshBranchDropdown(theform) {
    var partid = theform.partid.value;

    var opt = {
        method: 'post',
        postBody: 'p=' + partid
    }
    new Ajax.Updater('BranchDropdown', 'ajax_inquiry_branch_dropdown.php', opt);
}

function showHidePayDivs(dropdown) {
    var i;
    for (i = 0; i < dropdown.options.length; i++) {
        if (dropdown.options[i].value == "CC") {
            if (dropdown.options[i].selected) {
               document.getElementById('creditform').style.display = 'block';
               document.getElementById('cc_number').focus();
            } else {
               document.getElementById('creditform').style.display = 'none';
            }
        }
        if (dropdown.options[i].value == "CK") {
            if (dropdown.options[i].selected) {
               document.getElementById('checkform').style.display = 'block';
            } else {
               document.getElementById('checkform').style.display = 'none';
            }
        }
        if (dropdown.options[i].value == "CS") {
            if (dropdown.options[i].selected) {
               document.getElementById('cashform').style.display = 'block';
            } else {
               document.getElementById('cashform').style.display = 'none';
            }
        }
    }
}

function verifyPayMethod(theform) {
  if (theform.paychoice.value == "CC") {
      if (theform.ccchoice.value == "") {
          if (theform.cc_type.value == "") {
              alert("Credit Card type must be selected");
              return false;
          }
          if (theform.cc_number.value == "") {
              alert("Credit Card number cannot be blank");
              return false;
          } else {
              if (!validateCreditCard(theform.cc_number.value)) {
                  alert("Invalid credit card number");
                  return false;
              }
          }
          if (theform.cc_expmonth.value == "") {
              alert("Credit Card expiration month must be selected");
              return false;
          }
          if (theform.cc_expyear.value == "") {
              alert("Credit Card expiration year must be selected");
              return false;
          }
          if (theform.cc_cardholdername.type == "text") {
              if (theform.cc_cardholdername.value == "") {
                  alert("Credit Card card holder name cannot be blank");
                  return false;
              }
          } else {
              if (theform.cc_firstname.value == "") {
                  alert("Credit Card first name cannot be blank");
                  return false;
              }
              if (theform.cc_lastname.value == "") {
                  alert("Credit Card last name cannot be blank");
                  return false;
              }
          }
          if (theform.cc_address1.value == "") {
              alert("Credit Card address line 1 cannot be blank");
              return false;
          }
          if (theform.cc_city.value == "") {
              alert("Credit Card city cannot be blank");
              return false;
          }
          if (theform.cc_state.value == "") {
              alert("Credit Card state cannot be blank");
              return false;
          }
          if (theform.cc_zip.value == "") {
              alert("Credit Card zip cannot be blank");
              return false;
          }
      }
  }
  if (theform.paychoice.value == "CK") {
      //if (theform.ck_firstname.value == "") {
          //alert("First name cannot be blank");
          //return false;
      //}
      //if (theform.ck_lastname.value == "") {
          //alert("Last name cannot be blank");
          //return false;
      //}
      //if (theform.ck_address1.value == "") {
          //alert("Address cannot be blank");
          //return false;
      //}
      //if (theform.ck_city.value == "") {
          //alert("City cannot be blank");
          //return false;
      //}
      //if (theform.ck_state.value == "") {
          //alert("State cannot be blank");
          //return false;
      //}
      //if (theform.ck_zip.value == "") {
          //alert("Zip cannot be blank");
          //return false;
      //}
      //if (theform.ck_bank_name.value == "") {
          //alert("Bank name cannot be blank");
          //return false;
      //}
      if (theform.ck_number.value == "") {
          alert("Check number cannot be blank");
          return false;
      }
      //if (theform.ck_aba.value == "") {
          //alert("Bank Routing number cannot be blank");
          //return false;
      //}
      //if (theform.ck_aba2.value == "") {
          //alert("Retyped bank routing number cannot be blank");
          //return false;
      //}
      //if (theform.ck_account.value == "") {
          //alert("Check account number cannot be blank");
          //return false;
      //}
      //if (theform.ck_account2.value == "") {
          //alert("Retyped check account number cannot be blank");
          //return false;
      //}
      //if (theform.ck_account.value != theform.ck_account2.value) {
          //alert("Check account numbers do not match in both fields");
          //return false;
      //}
      //if (theform.ck_aba.value != theform.ck_aba2.value) {
          //alert("Bank routing numbers do not match in both fields");
          //return false;
      //}
  }
}

function convert_enter (field, event) {
/****************************************************************************
 * cause enter key to act like tab key and avoid it causing form submission *
 * usage: onkeypress="convert_enter(this,event);"                           *
 ****************************************************************************/
  var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

  if (keycode == 13) {
     /**********************************
      * set i to field number in form, *
      * then set focus to next one.    *
      **********************************/
      var i;
      for (i = 0; i < field.form.elements.length; i++) if (field == field.form.elements[i]) break;
      i = (i + 1) % field.form.elements.length;  // wraparound to first
      field.form.elements[i].focus();
      return false;
  } else return true;
}

function opt_smartzip (t) {
 /*********************************************
  * assist user in entering a legal zipcode *
  * If garbage then return null (blank field) *
  *********************************************/
  var result;
  var pattern_close  = /^(\d+)\-(\d+)$/;
  var pattern_close2 = /^(\d+)$/;
  var datefield = t.value;

  result = datefield.match(pattern_close);
  if (result != null) {
     /**************************************************
      * Found a number with decimal places, so trim it *
      * down to 2 decimal places.                      *
      *************************************************/
      t.value = result[1] + '-' + result[2];
      return true;
  }

  result = datefield.match(pattern_close2);
  if (result != null) {
     /******************************************
      * Append decimal place since its missing.*
      ******************************************/
      t.value = result[1];
      return true;
  }

  t.value = '';
  return true;
}

function opt_smartmoney (t) {
 /*********************************************
  * assist user in entering a + dollar amount *
  * It chops off more than 2 decimal places.  *
  * If garbage then return null (blank field) *
  *********************************************/
  var result;
  var pattern_close  = /(\d+)\.(\d+)/;
  var pattern_close2 = /(\d+)/;
  var datefield = t.value;

  result = datefield.match(pattern_close);
  if (result != null) {
     /**************************************************
      * Found a number with decimal places, so trim it *
      * down to 2 decimal places.                      *
      *************************************************/
      t.value = result[1] + '.' + trim_decimal_places(result[2]);
      return true;
  }

  result = datefield.match(pattern_close2);
  if (result != null) {
     /******************************************
      * Append decimal place since its missing.*
      ******************************************/
      t.value = result[1] + '.00';
      return true;
  }

  t.value = '';
  return true;
}

function mis_print(id, doctype, formtype) {
  var opt = {
      method: 'post',
      postBody: 'id=' + id + "&t=" + doctype + "&f=" + formtype,
      onSuccess: function(t) {
          // show alert popup
          alert(t.responseText);
      },
      on404: function(t) {
          alert('Error 404: ajax_mis_print.php "' + t.statusText + '".');
      },
      onFailure: function(t) {
          alert('Error ' + t.status + ' -- ' + t.statusText);
      }
  }
  new Ajax.Request('ajax_mis_print.php', opt);
}

function mis_print_fq(id, doctype, formtype, fq) {
  var opt = {
      method: 'post',
      postBody: 'id=' + id + "&t=" + doctype + "&f=" + formtype + "&q=" + fq,
      onSuccess: function(t) {
          // show alert popup
          alert(t.responseText);
          window.close();
      },
      on404: function(t) {
          alert('Error 404: ajax_mis_print.php "' + t.statusText + '".');
      },
      onFailure: function(t) {
          alert('Error ' + t.status + ' -- ' + t.statusText);
      }
  }
  new Ajax.Request('ajax_mis_print.php', opt);
}

function printerPopUp(URL) {
  // MIS print popup
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=300,height=300,left = 362,top = 134');");
}

function popupLogin(URL) {
  // show login page in popup window
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=300,height=300,left = 362,top = 134');");
}

function validateMagtekCreditCard(t) {

  var re = new RegExp(/^%B/)
  var m = re.exec(t.value);

  if (m == null) { 
      if (t.value == "") {
          return(false);
      }
      if (!validateCreditCard(t.value)) {
          alert("Invalid credit card number");
          t.value = "";
          return(false);
      }

      // Get card type.
      var cardNum = t.value;
      var cType = "";
      var visa = "^4[0-9]{12}(?:[0-9]{3})?$";
      var re = new RegExp(visa)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "VI";
      }

      var masterCard = "5[1-5][0-9]{14}$";
      var re = new RegExp(masterCard)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "MC";
      }
               
      var americanExpress = "^3[47][0-9]{13}$";
      var re = new RegExp(americanExpress)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "AX";
      }
               
      var discover = "^6(?:011|5[0-9]{2})[0-9]{12}$";
      var re = new RegExp(discover)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "DI";
      }
               
      var dropdown = document.getElementById("cc_type"); 
      var i;
      for (i = 0; i < dropdown.options.length; i++) {
          if (dropdown.options[i].value == cType) {
              dropdown.options[i].selected = true;
          }
      }
  } else {
      var magstripe = document.getElementById("cc_magstripe"); 
      magstripe.value = t.value;

      var tokens = t.value.split("^");
      var cc_num = document.getElementById("cc_number");
      var cardNum = tokens[0].substring(2);
      cc_num.value = cardNum; 

      var holder = document.getElementById("cc_cardholdername"); 
      var holderfirst = document.getElementById("cc_firstname"); 
      var holderlast = document.getElementById("cc_lastname"); 
      var name = tokens[1].split("/"); // last then first
      name[1] = name[1].replace(/^\s+|\s+$/g, '');
      name[0] = name[0].replace(/^\s+|\s+$/g, '');
      if (name[1] != "") {
          holder.value = name[1] + " " + name[0];
          holderfirst.value = name[1];
          holderlast.value = name[0];
      } else {
          // missing firstname, assume space delimited
          holder.value = name[0];
          var namesplit = name[0].split(" "); // first then last
          holderfirst.value = namesplit[0];
          holderlast.value = namesplit[1];
      }
      tok2 = tokens[2];
      var year = tok2.substr(0,2);
      var month = tok2.substr(2,2);
      var serviceCode = tok2.substr(4,3);
      var cvv2 = document.getElementById("cc_cvv2"); 
      //cvv2.value = serviceCode;
      var expyear = document.getElementById("cc_expyear"); 
      expyear.value = "20" + year;
      var expmonth= document.getElementById("cc_expmonth"); 
      //expmonth.value = month;
      var i;
      for (i = 0; i < expmonth.options.length; i++) {
          if (expmonth.options[i].value == month) {
              expmonth.options[i].selected = true;
          }
      }

      // Get card type.
      var cType = "";
      var visa = "^4[0-9]{12}(?:[0-9]{3})?$";
      var re = new RegExp(visa)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "VI";
      }
      var masterCard = "5[1-5][0-9]{14}$";
      var re = new RegExp(masterCard)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "MC";
      }
               
      var americanExpress = "^3[47][0-9]{13}$";
      var re = new RegExp(americanExpress)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "AX";
      }
               
      var discover = "^6(?:011|5[0-9]{2})[0-9]{12}$";
      var re = new RegExp(discover)
      var m = re.exec(cardNum);
      if (m != null ) { 
          cType = "DI";
      }
               
      var dropdown = document.getElementById("cc_type"); 
      for (i = 0; i < dropdown.options.length; i++) {
          if (dropdown.options[i].value == cType) {
              dropdown.options[i].selected = true;
          }
      }
  }
}

function convert_enter_magtek (field, event) {
/****************************************************************************
 * cause enter key to act like tab key and avoid it causing form submission *
 * usage: onkeypress="convert_enter(this,event);"                           *
 ****************************************************************************/
  var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

  if (keycode == 13) {
     /**********************
      * User pressed enter *
      **********************/
      validateMagtekCreditCard(field);
      return false;
  } else return true;
}

function showHideReportSettings() {
  if (document.getElementById('settings').className == 'divShown') {
      document.getElementById('settings').className = 'divHidden';
  } else {
      document.getElementById('settings').className = 'divShown';
  }
}

function get_month() {
   // return string of 2 digit current month

   var d = new Date();
   var mon = d.getMonth() + 1;
   if (mon < 10) mon ="0" + mon;
   return mon.toString();
}

function get_day() {
   // return string of 2 digit current month

   var d = new Date();
   var day = d.getDate();
   if (day < 10) day = "0" + day;
   return day.toString();
}

function get_year() {
   // return string of 2 digit current year

   var d = new Date();
   var year = d.getFullYear();
   year = year.toString();
   year = year.substr(2,2);
   return year.toString();
}

function get_fullyear() {
   // return string of 4 digit current year

   var d = new Date();
   var year = d.getFullYear();
   year = year.toString();
   return year.toString();
}

function recall_order(id) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'id=' + id
  }
  new Ajax.Updater('titletext', 'ajax_recall_order.php', opt);
}

function showHideSearchCriteria() {
  if (document.getElementById('advsearch').className == 'divShown') {
      document.getElementById('advsearch').className = 'divHidden';
  } else {
      document.getElementById('advsearch').className = 'divShown';
  }
}

function get_last_day(month, year) {
   // return last day of the month

   var daylist = [31,28,31,30,31,30,31,31,30,31,30,31];
   if (year == 0) {
      daylist[1] = 29; // century leap year
   } else {
      var leap = year / 4;
      var leap2 = Math.floor(leap);
      if (leap == leap2) daylist[1] = 29;  // regular leap year
   }
   month = month - 1;
   var lastday = daylist[month];
   return lastday.toString();
}

function clearInvFilter(theform) {
  theform.search_invno.value = "";
  theform.search_pono.value = "";
  theform.search_claimno.value = "";
  theform.search_startdate.value = "";
  theform.search_enddate.value = "";
  theform.search_partno.value = "";
  theform.credits_only.checked = false;
  theform.hide_credits.checked = false;
  theform.f.value = "";
  return false;
}

function clearInvLinesFilter(theform) {
  theform.search_invno.value = "";
  theform.search_pono.value = "";
  theform.search_linepono.value = "";
  theform.search_claimno.value = "";
  theform.search_startdate.value = "";
  theform.search_enddate.value = "";
  theform.search_partno.value = "";
  theform.f.value = "";
  return false;
}

function viewcart_enter (f,e) {
/**********************************************************
 * user pressed enter on this field, submit update        *
 * usage: onkeypress="return viewcart_enter(this,event);" *
 **********************************************************/
  if (!e) e = window.event;  
  var code = (e.keyCode) ? e.keyCode : e.which;
 
  if (code == 13 || code == 3) {
      document.mainform.updcart.click();
      return false;
  }
  return true;
}

function showInvoiceByNumber(theform) {
  var invnum;
  invnum = theform.invnum.value;
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'id=' + invnum
  }
  new Ajax.Updater('dummy', 'ajax_show_invoice_by_number.php', opt);
}

function doQSA(id) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'id=' + id
  }
  new Ajax.Updater('dummy', 'ajax_quick_sa.php', opt);
}

function doQDEACK(id) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'id=' + id
  }
  new Ajax.Updater('dummy', 'ajax_quick_deack.php', opt);
}

function rememberLogin(cbox) {
// user requests to remember login with cookie for 90 days
  if (cbox.checked) {
      // set
      Set_Cookie('ServallUser', $('username4').value, '90', '/', '', '');
  } else {
      // clear
      Delete_Cookie('ServallUser', '/', '');
  }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime(today.getTime());

  if (expires) {
      expires = expires * 1000 * 60 * 60 * 24; // in days
  }
  var expires_date = new Date(today.getTime() + (expires));

  document.cookie = name + "=" + escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

function Get_Cookie(check_name) {
  // note: document.cookie only returns name=value, not the other components
  // note: that in cases where cookie is initialized but no value, null is returned
  var a_all_cookies = document.cookie.split( ';' ); // name and value pairs array
  var a_temp_cookie = '';
  var cookie_name = '';
  var cookie_value = '';
  var cookie_found = false; // set boolean t/f default f

  for ( i = 0; i < a_all_cookies.length; i++ ) {
      // now we'll split apart each name=value pair
      a_temp_cookie = a_all_cookies[i].split( '=' );

      // and trim left/right whitespace while we're at it
      cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

      // if the extracted name matches passed check_name
      if (cookie_name == check_name) {
          cookie_found = true;
          // we need to handle case where cookie has no value but exists (no = sign, that is):
          if (a_temp_cookie.length > 1 ) {
              cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
          }
          return cookie_value;
          break;
      }
      a_temp_cookie = null;
      cookie_name = '';
  }
  if (!cookie_found) {
      return null; // cookie missing
  }
}

function Delete_Cookie(name, path, domain) {
// expire a cookie
  if (Get_Cookie(name)) document.cookie = name + "=" +
  ( ( path ) ? ";path=" + path : "") +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function forgotPassword(element) {
  // let database email user his password
  if (element.value == '') {
      alert('User name cannot be blank');
      return false;
  }

  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'id=' + encodeURIComponent(element.value)
  }
  new Ajax.Updater('dummy', 'ajax_email_password.php', opt);
  return false;
}

function changeShipMethod(element) {
  var ok, origshipmethod;
  origValue = $('ORIGSHIPMETHOD').value;
  ok = showShipviaAlert(element.value);
  if (ok) {
      element.form.submit();
  } else {
    var i;
    for (i = 0; i < element.options.length; i++) {
        if (element.options[i].value == origValue) {
            element.options[i].selected = true;
        }
    }
  }
  return ok;
}

function showCash(id) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'id=' + id
  }
  new Ajax.Updater('dummy', 'ajax_show_cash.php', opt);
}

function showCashPopUp(URL) {
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=300,height=300,left = 362,top = 134');");
}

function findXCoord(obj) {
    // return objects position on page
    var curleft = 0;
    if (obj.offsetParent) {
        do {
          curleft += obj.offsetLeft;
        } while (obj = obj.offsetParent);
    }
    return curleft;
}

function findYCoord(obj) {
    // return objects position on page
    var curtop = 0;
    if (obj.offsetParent) {
        do {
          curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return curtop;
}


function showEmailStatementForm(element) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'x=' + xPos + '&y=' + yPos
  }
  new Ajax.Updater('emailStatementBox', 'ajax_get_email_statement_form.php', opt);
}

function submitEmailStatementRequest(theform) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'custid=' + encodeURIComponent($('custid').value) + '&month=' + encodeURIComponent(theform.month.value) + '&year=' + encodeURIComponent(theform.year.value) + '&email=' + encodeURIComponent(theform.email.value)
  }
  new Ajax.Updater('dummy', 'ajax_email_statement.php', opt);
}

function getApplyDiscountForm(element) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'x=' + xPos + '&y=' + yPos
  }
  new Ajax.Updater('discountBox', 'ajax_get_apply_discount_form.php', opt);
}

function getApplyDiscountForm2(element) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'x=' + xPos + '&y=' + yPos
  }
  new Ajax.Updater('discountBox', 'ajax_get_apply_discount_form2.php', opt);
}

function applyDiscount(theform) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'percent=' + encodeURIComponent(theform.percent.value) + '&reason=' + encodeURIComponent(theform.reason.value)
  }
  new Ajax.Updater('dummy', 'ajax_apply_discount.php', opt);
}

function applyDiscount2(theform) {
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'percent=' + encodeURIComponent(theform.percent.value) + '&reason=' + encodeURIComponent(theform.reason.value)
  }
  new Ajax.Updater('dummy', 'ajax_apply_discount2.php', opt);
}

function checkUserExists(event) {
  // $('userid').observe('blur', checkUserExists);
  var element = Event.element(event);
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'userid=' + encodeURIComponent(element.value)
  }
  new Ajax.Updater('dummy', 'ajax_check_userid_exists.php', opt);
}   

function showCustNotes(element, custid) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  if (custid == '') {
      return false;
  }
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'custid=' + encodeURIComponent(custid) + '&x=' + xPos + '&y=' + yPos 
  }
  new Ajax.Updater('notesBox', 'ajax_show_cust_notes.php', opt);
  return false;
}

function trim_spaces (field, event) {
/************************************************
 * allow enter key, tab and digits only         *
 * usage: onkeypress="trim_spaces(this,event);" *
 # 48-57 = digits, enter, tab, del, backsp      *
 ************************************************/
  var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  //var keychar = String.fromCharCode(keycode);

  if (keycode == 32) {
      return false; // space
  }

  return true;
}

function trapEnterUpdateButton(event) {
  // view_cart.php page only
  // $('foo').observe('keypress', trapEnterUpdateButton);
  var element = Event.element(event);
  Event.stop(event);
  if (event.keyCode == Event.KEY_RETURN) {
      $('updcart').click();
  }
}

function doNPC(element, partid) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'partid=' + encodeURIComponent(partid) +'&x=' + xPos + '&y=' + yPos
  }
  new Ajax.Updater('NPCBox', 'ajax_do_npc.php', opt);
  return false;
}

function checkPriceError(field) {
  var line, basefieldname, extras;
  var fieldname = field.id;
  var pattern = /^(\D+)(\d+)$/;
  result = fieldname.match(pattern);
  if (result != null) {
      basefieldname = result[1];
      line = result[2];
  } else {
      return true;
  }
  if (basefieldname == "price") {
      origprice = "origprice" + line;
      if (field.value == "" || field.value == "1" || field.value == "1.00") {
          alert('Price is invalid on line ' + line);
          field.value = $(origprice).value;
          return false;
      }
  }
  return true;
}

function branchQuickOrder(element, brno) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  if (brno == '') {
      return false;
  }
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'brno=' + encodeURIComponent(brno) +'&x=' + xPos + '&y=' + yPos
  }
  new Ajax.Updater('branchBox', 'ajax_inquiry_quick_order.php', opt);
  return false;
}

function showLocations(element, partid, brno, locations) {
  var xPos, yPos;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  if (brno == '') {
      return false;
  }
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'p=' + encodeURIComponent(partid) + '&brno=' + encodeURIComponent(brno) + '&l=' + locations +'&x=' + xPos + '&y=' + yPos
  }
  new Ajax.Updater('branchBox', 'ajax_inquiry_locations.php', opt);
  return false;
}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function sendSignupRequest(theform) {
  if (theform.name.value == "") {
      alert("Name cannot be blank");
      theform.name.focus();
      return false;
  }
  if (theform.phone.value == "") {
      alert("Phone cannot be blank");
      theform.phone.focus();
      return false;
  }
  if (theform.email.value == "") {
      alert("Email cannot be blank");
      theform.email.focus();
      return false;
  }

  var result;
  var pattern = /^[\w\-\.]+@[\w\-\.]+$/;
  var efield = theform.email.value;
  result = efield.match(pattern);
  if (result == null) {
      theform.email.value = '';
      alert("Please enter a valid email address");
      theform.email.focus();
      return false;
  }

  if (theform.account.value == "") {
      alert("Account # cannot be blank");
      theform.account.focus();
      return false;
  }
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'name=' + encodeURIComponent(theform.name.value) +
        '&phone=' + encodeURIComponent(theform.phone.value) + 
        '&email=' + encodeURIComponent(theform.email.value) + 
        '&account=' + encodeURIComponent(theform.account.value)
  }
  new Ajax.Updater('dummy', 'ajax_signup_request.php', opt);
  return false;
}

function quote_print_fq(id, doctype, formtype, fq) {
  var opt = {
      method: 'post',
      postBody: 'id=' + id + "&t=" + doctype + "&f=" + formtype + "&q=" + fq,
      onSuccess: function(t) {
          // show alert popup
          alert(t.responseText);
          window.close();
      },
      on404: function(t) {
          alert('Error 404: ajax_mis_print.php "' + t.statusText + '".');
      },
      onFailure: function(t) {
          alert('Error ' + t.status + ' -- ' + t.statusText);
      }
  }
  new Ajax.Request('ajax_mis_print.php', opt);
}

function showPartPopup(element, title, msg, imagedir) {
  var i, xPos, yPos, box;
  xPos = findXCoord(element);
  yPos = findYCoord(element);
  xPos += 90;
  yPos -= 20;
  if (msg == '') {
      return false;
  }
  box = '<table border="0" width="100%">';
  box += '<tr>';
  box += '<td align="left">';
  box += '<span class="boxtitletext">' + title + '</span>';
  box += '</td>';
  box += '<td align="right">';
  box += '<a class="redlink" href="#" onclick="$(\'partPopupBox\').style.visibility = \'hidden\';"><img src="' + imagedir + '/deleteme.png" border="0"></a>';
  box += '</td>';
  box += '</tr>';
  box += '</table>';
  box += '<table border="0">';
  box += '<tr>';
  box += '  <td>';
  datarows = msg.split("|");
  box += '    <ul type="circle">';
  for (i = 0; i < datarows.length; i++ ) {
    box += '<li>' + datarows[i];
  }
  box += '    </ul>';
  box += '  </td>';
  box += '</tr>';
  box += '</table>';

  $('partPopupBox').innerHTML = box;
  $('partPopupBox').style.visibility = 'visible';
  $('partPopupBox').style.top = yPos + 'px';
  $('partPopupBox').style.left = xPos + 'px';
  return false;
}

function showRoutingFinder() {
  var thestring = "";
  if ($('sRouting') != null) {
      thestring = $('sRouting').value;
  }
  var opt = {
      method: 'post',
      evalScripts: 'true',
      postBody: 'sRouting=' + encodeURIComponent(thestring)
  }
  new Ajax.Updater('routingBox', 'ajax_show_routing_finder.php', opt);
  return false;
}

function loadServiceBox() {
  var opt = {
    method: 'post',
    evalScripts: 'true'
  }
  new Ajax.Updater('serviceBox', 'ajax_show_service_box.php', opt);
}

function saveServiceCode(element) {
  var code, value;
  code = element.name;
  value = element.value;
  if (element.checked) {
      var opt = {
          method: 'post',
          postBody: 'code=' + code + "&value=" + value,
          onSuccess: function(t) {
              loadServiceBox();
          }
      }
      new Ajax.Request('ajax_save_service_code.php', opt);
  } else {
      //uncheck with blank value
      var opt = {
          method: 'post',
          postBody: 'code=' + code + "&value=N",
          onSuccess: function(t) {
              loadServiceBox();
          }
      }
      new Ajax.Request('ajax_save_service_code.php', opt);
  }
}

function saveShippingOption(element) {
  var code, value;
  code = element.name;
  value = element.value;
  var opt = {
      method: 'post',
      postBody: 'code=' + code + "&value=" + encodeURIComponent(value),
      onSuccess: function(t) {
          loadServiceBox();
      }
  }
  new Ajax.Request('ajax_save_shipping_code.php', opt);
}

function ignoreEnterKey(event) {
    // $('foo').observe('keypress', ignoreEnterKey);
    var keycode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keycode == 13 || keycode == 3) {
        Event.stop(event); // prototype handler
        return false;
    }
    return true;
}

