// Javascript Code for Request Pricing page:
// Making, storing, and retreiving cookies used for filling in the form,
// plus filling-in checkbox based on info sent in URL from previous page.
// Copyright 2001-2006 David Roth. All Rights Reserved.

var numberOfProducts;  // Counter of checkbox elements (Global)
var numberOfFieldsets = 7;  // Number of fieldset groupings on the page minus 1 -- 7 as of 12-19-01
var productsCookieName = 'ProductsPR';
var idCookieName = 'IdPR';
var maxPRCount = 8;   // Limit of products allowed to be checked per submission - GoldMine's Web Import ContSupp Limit

// First thing: check to see if cookies can be used...
var acceptsCookies = true;
var cookiesMessage = "";
if (document.cookie=='') {  // If no existing cookies...
  document.cookie = "CookieCheck=Yes"; // Try to set a cookie
  if (document.cookie.indexOf("CookieCheck=Yes") == -1) {  // If it doesn't exist...
    cookiesMessage = '<h5><font color="#993333">(If Cookies were enabled on your browser, previously checked boxes and filled fields will persist on subsequent visits to this page.)</font></h5>';
    acceptsCookies = false;
  }
}

// code that fills in the form, called from the <body onload="fill_Form()"> element...
function fill_Form() {

// Count the number of product checkboxes using Javascript when this code starts
numberOfProducts = 0;  // Counter of checkbox elements
var formElements = document.forms["req_pricing"].elements;  // var to avoid recalc each time
for (i=0; i<formElements.length;i++) {
  if (formElements[i].type == "checkbox") 
    numberOfProducts++;
}

  restoreCookies(); // This will restore even when Cookie setting is "Prompt". If setting is "No", it will demure gracefully...
  markCheckbox();
  // fill-in the 4 hidden fields which gather properties
  window.onerror=null; // ignore errors generated, mainly by NN3..
  document.req_pricing.Screen_Width.value = window.screen.width;
  document.req_pricing.Screen_Height.value = window.screen.height;
  document.req_pricing.Color_Depth.value = window.screen.colorDepth;
  document.req_pricing.Platform.value = navigator.platform;
}

// Restore the contents the form: Product Checkboxes from Session-only cookie, demographics from 6-month cookie...
function restoreCookies() {
  cutCookie( getCookie( productsCookieName ) );
  if (cookieArray[0] != "*") {
    for (var i=1; i<(numberOfProducts+numberOfFieldsets); i++) {  // (fieldsets interspersed with the checkboxes...)
      if (document.req_pricing.elements[i].checked != "undefined")
        document.req_pricing.elements[i].checked = (cookieArray[i]=="true")? true:false ;
    }
  }
  cutCookie( getCookie( idCookieName ) );
  if (cookieArray[0] != "*") {
    document.req_pricing.Name.value = cookieArray[1];
    document.req_pricing.Company.value = cookieArray[2];
    document.req_pricing.Department.value = cookieArray[3];
    document.req_pricing.Address1.value = cookieArray[4];
    document.req_pricing.Address2.value = cookieArray[5];
    document.req_pricing.City.value = cookieArray[6];
    document.req_pricing.State.value = cookieArray[7];
    document.req_pricing.Zip.value = cookieArray[8];
    document.req_pricing.Country.value = cookieArray[9];
    document.req_pricing.Phone1.value = cookieArray[10];
    document.req_pricing.Fax.value = cookieArray[11];
    document.req_pricing.Website.value = cookieArray[12];
    document.req_pricing.Email.value = cookieArray[13];
    document.req_pricing.Brand.value = cookieArray[14];
    document.req_pricing.Model.value = cookieArray[15];
  }
}

// Parse the whole cookie in an array of one field per index...
function cutCookie(wholeCookie) {
  cookieArray = new Array();
  var i = 0, j = 0, crumbLength = 0;
  if ((wholeCookie == null) || (wholeCookie == "*")) {   // Cookie expired or non-existent...
    cookieArray[0] = "*";
    return;
  }
  while (crumbLength < wholeCookie.length) {
    crumbLength = (wholeCookie.indexOf("`",j)>0)? wholeCookie.indexOf("`",j):wholeCookie.length;
    cookieArray[i] = wholeCookie.substring(j,crumbLength);
    i++;
    j = crumbLength + 1;
  }
}

// Find the specific cookie
function getCookie(cookieName) {
  var cookieEqualSign = cookieName + "=";
  var i = 0;
  while (i < document.cookie.length) {
    var j = i + cookieEqualSign.length;
    if (document.cookie.substring(i,j) == cookieEqualSign) {
      var l = document.cookie.indexOf(";",j);
      if (l == -1) l = document.cookie.length;
      return unescape(document.cookie.substring(j,l));
    }
    i = document.cookie.indexOf(" ",i) + 1;
    if (i == 0) break;  // that's -1 plus 1 = 0...
  }
  return "*"; // could not find that cookie...
}

// Checkmark the checkbox as passed in the link on the preceeding page
function markCheckbox() {
  product=''+this.location; // get the full URL string including passed column value
  product=product.substring((product.indexOf('?'))+1); // strip everything before the checkbox value (i.e., the URL)
  product=product.substring(0,(product.indexOf('#'))); // strip everything after the checkbox value (i.e, the named anchor)
  if ((elmt=document.req_pricing.elements[product])) { elmt.checked = true; elmt.focus(); }// if it exists, check the box and focus on it -- double parenthesis are for old [Netscape] browsers who can't evaluate and assign at the same time...
}

// Restrict requests to the maxPRCount limit
// Called from the onSubmit="return countCheckedBoxes()" line within the <form>...
function countCheckedBoxes() {
var prCount = 0;      // Counter of products checked
var formElements = document.forms["req_pricing"].elements;  // var to avoid recalc each time
for (i=0; i<formElements.length;i++) {
  if (formElements[i].type == "checkbox" && formElements[i].checked) 
    prCount++;
  }
  if (prCount > maxPRCount) {
    alert("You may request a maximum of "+maxPRCount+" products for pricing.\n\n\r            Please choose the "+maxPRCount+" products on\n\r            which you'd like to receive pricing.");
    return false;
  }
  else return true;
}

// Verify the form was filled out correctly, store the cookies, and then allow submit to complete...
// Called from the onSubmit="return processForm()" line within the <form>...
function processForm() {
  if (validate()) {
    storeCookies();
    return true;
  }
  else return false;
}

// Validate Name, Company, E-mail, Microscope Brand and Model fields...
function validate() {
  if (document.req_pricing.Name.value == "") {
    document.req_pricing.Name.style.backgroundColor = "#ffff99";
    document.req_pricing.Name.focus();
    alert("Please enter your name.");
    return false;
  }
  else if (document.req_pricing.Company.value == "") {
    document.req_pricing.Company.style.backgroundColor = "#ffff99";
    document.req_pricing.Company.focus();
    alert("Please enter your company.");
    return false;
  }
  else if (document.req_pricing.Address1.value == "") {
    document.req_pricing.Address1.style.backgroundColor = "#ffff99";
    document.req_pricing.Address1.focus();
    alert("Please enter your address.");
    return false;
  }
  else if (document.req_pricing.City.value == "") {
    document.req_pricing.City.style.backgroundColor = "#ffff99";
    document.req_pricing.City.focus();
    alert("Please enter your city.");
    return false;
  }
  else if (document.req_pricing.State.value == "") {
    document.req_pricing.State.style.backgroundColor = "#ffff99";
    document.req_pricing.State.focus();
    alert("Please enter your state or province.");
    return false;
  }
  else if (document.req_pricing.Zip.value == "") {
    document.req_pricing.Zip.style.backgroundColor = "#ffff99";
    document.req_pricing.Zip.focus();
    alert("Please enter your zip or postal code.");
    return false;
  }
  else if (!document.req_pricing.Email.value.match( /^(([^\<\>\(\)\[\]\.\,\;\:\s\@\"\\]+(\.[^\<\>\(\)\[\]\.\,\;\:\s\@\"\\]+)*)|(\".+\"))\@(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}|(([0-1]?[0-9]{1,2}\.)|(2[0-4][0-9]\.)|(25[0-5]\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5])))$/ )) {
    document.req_pricing.Email.style.backgroundColor = "#ffff99";
    document.req_pricing.Email.focus();
    alert("Please enter a valid e-mail address.");
    return false;
  }
  else if (document.req_pricing.Brand.value == "") {
    document.req_pricing.Brand.style.backgroundColor = "#ffff99";
    document.req_pricing.Brand.focus();
    alert("Please enter your microscope brand.");
    return false;
  }
  else if (document.req_pricing.Model.value == "") {
    document.req_pricing.Model.style.backgroundColor = "#ffff99";
    document.req_pricing.Model.focus();
    alert("Please enter your microscope model.");
    return false;
  }
  return true; // Form is valid enough to be submitted to CGI script...
}

// Store the two cookies...
function storeCookies() {
  if (acceptsCookies) {
    // Store product request information in a cookie to last only during the current session...
    var productsCookie = "0"; // the first 'item' of the whole cookie...
    for (var i=1; i<(numberOfProducts+numberOfFieldsets); i++) {  // (fieldsets interspersed with the checkboxes...)
      if (document.req_pricing.elements[i].checked != "undefined") // if it's a real checkbox...
        productsCookie = productsCookie + '`' + document.req_pricing.elements[i].checked;
    }
    document.cookie = productsCookieName + "=" + escape( productsCookie );

    // Store identification information in another cookie to last six months...
    var idCookie = "0"; // the first 'item' of the whole cookie...
    idCookie = idCookie + '`' + document.req_pricing.Name.value;
    idCookie = idCookie + '`' + document.req_pricing.Company.value;
    idCookie = idCookie + '`' + document.req_pricing.Department.value;
    idCookie = idCookie + '`' + document.req_pricing.Address1.value;
    idCookie = idCookie + '`' + document.req_pricing.Address2.value;
    idCookie = idCookie + '`' + document.req_pricing.City.value;
    idCookie = idCookie + '`' + document.req_pricing.State.value;
    idCookie = idCookie + '`' + document.req_pricing.Zip.value;
    idCookie = idCookie + '`' + document.req_pricing.Country.value;
    idCookie = idCookie + '`' + document.req_pricing.Phone1.value;
    idCookie = idCookie + '`' + document.req_pricing.Fax.value;
    idCookie = idCookie + '`' + document.req_pricing.Website.value;
    idCookie = idCookie + '`' + document.req_pricing.Email.value;
    idCookie = idCookie + '`' + document.req_pricing.Brand.value;
    idCookie = idCookie + '`' + document.req_pricing.Model.value;

    var expire = new Date();
    expire.setTime(expire.getTime() + (183 * 24 * 3600000));  // Expires in six months...
    document.cookie = idCookieName + "=" + escape( idCookie ) + "; expires=" + expire.toGMTString();
  }
}

