﻿//#############################################
//#
//# - quote_v2.js - form validation.
//# - Anthony De Stefano * ADestefa@us.ibm.com
//# - Last Mod: 4/12/2002 9:42PM
//# - v1.0.0  initial build
//# - v1.1.1  CCE updates
//# - v2.0.0  Lang updates
//#
//# It is required to load this file into any form that wants to use RAQ function.
//# -------------------------------------------
//#
//# This script provides client-side form validation based on user defined required fields.
//# To install this script just call it as a source file using script tags with src attribute.
//# To link this script with your form:
//#   1- name the form "quote"
//#   2- link submit button to quote() function by using onclick event handler  (<input type="image" onclick="quote()" src="">).
//# -check the docfile for more information.
//# docfile: /shop/americas/content/emails/quote/docs/help/quote_js.html
//#
//# dependencies:
//#  /emails/quote/quote.cgi
//#
//#
//##############################################

//@@@@@@@@@@@@@@@ UPDATE THESE SETTINGS AS NEEDED @@@@@@@@@@@@@@@@
var debug = 0;             // Debug switch
// missing quote form error
var FormNameErrMsg_en_US   = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_en_US = '"Warning!"  You have not filled out the following required form fields:';

var FormNameErrMsg_fr_CA = "ERReuR!\n\nLe formulaire est introuvable dans le document.\n\nVeuillez le renommer et contiuer";
var ReqFieldErrMsg_fr_CA = '"Attention!"  Les zones suivantes n\'ont pas été remplies :';

var FormNameErrMsg_en_CA   = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_en_CA = '"Warning!"  You have not filled out the following required form fields:';

//  
var FormNameErrMsg_de_US  = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_de_US = '"Warning!"  You have not filled out the following required form fields:';

//  
var FormNameErrMsg_es_US   = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_es_US = '"Warning!"  You have not filled out the following required form fields:';

//
var FormNameErrMsg_fr_US = "ERReuR!\n\nLe formulaire est introuvable dans le document.\n\nVeuillez le renommer et contiuer";
var ReqFieldErrMsg_fr_US = '"Attention!"  Les zones suivantes n\'ont pas été remplies :';

var FormNameErrMsg_jp_US   = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_jp_US = '"Warning!"  You have not filled out the following required form fields:';


var FormNameErrMsg_uk_US   = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_uk_US = '"Warning!"  You have not filled out the following required form fields:';

var FormNameErrMsg_it_US   = "ERROR!\n\nQuote form not found in document.\n\nPlease rename your form to 'quote' to contiue";
var ReqFieldErrMsg_it_US = '"Warning!"  You have not filled out the following required form fields:';





//------------------------- DO NOT EDIT BELOW THIS LINE ------------------------------------------------------------------------------------
userReqFields = new Array();

appReqFields = new Array();
appReqFields[0] = "brand";
appReqFields[1] = "store";
appReqFields[2] = "cntry";
appReqFields[3] = "lang";

appReqExample = new Array();
appReqExample[0] = "iSeries      (name of product brand";
appReqExample[1] = "IBMPublicUSA (shopper group name)";
appReqExample[2] = "_840         (used in filename)";
appReqExample[3] = "/en_US/      (used in path)";


var msg="";



function setAffiliate() {

        var ckString = document.cookie;
        var ckName = "sourceid0=";
        var offset = -1;
        offset = ckString.indexOf(ckName,0);
        if (offset >= 0) {
                var affString = "";
                var start = 0;
                var end = 0;
                start = offset + ckName.length;
                start++;
                end = start + 1;
                affString = ckString.substring(start,end);

                 // check affiliate cookie's second char and return track number
                 if ((affString == "S") || (affString == "s") || (affString == "B") || (affString == "b")) {
                    return "SBRAQ";
                  }

                  else if ((affString == "M") || (affString == "m"))
                  {
                   return "MBRAQ";
                  }

                  else // not MBC/SBC customer
                  {
                  return 0;
                  }

        }

}

//**********************************
// main add to cart button handler
//**********************************
function quote() {




 // quote form as f
 var f = document.quote ;
//---------------------------------------------------------------------------------------------------
//  Don't wasted time! Cut debugging cycles for the developer.
//  First validate the quote form for groupsite required fields.
//  Missing groupsite data will render the cgi unable to locate cntry_list and thank_you pages.
//  If any required fields are missing - msg error to developer and exit.
//---------------------------------------------------------------------------------------------------
  var goodConfig = checkQuoteConfiguration(f);
  if(!goodConfig) { return }

 // get user defined required fields
 // by loading any field with "req_" in name (req_1,req_2,etc..) into array
 // define required fields by coding then as hidden and using naming convention:
 // "req_#" as in req_0,req_1,req_2,etc.... (name="req_1" value="[field name]")
 userReqFields = loadUserReqFields(f);

 // req field search result flag
 var foundReqField=0;
 var msg = new Array();
 var req_error=0;
 var re = /_/

//------------------------------------------------------------
// - loop each user defined required field and extract field data
// - reset match flag
// - loop each form element and extract field data
// - search all elements for required field name
// - if required field found increment total found counter
// - if required field found trip match flag on
// - or if required field not found store field name for error msg
// - do final compare on num of required fields and num found
// - return false if values do not match and msg error to user
// - return true if all required fields found to submit quote
//------------------------------------------------------------
// loop required fields list
 for(i=0;i < userReqFields.length;i++)
    {
    // init flag
    foundReqField=0;

    // loop over every element in the form
    // search for any required field
    for(z=0;z<f.elements.length;z++)
      {
      // read in this field's data
      var thisType  = f.elements[z].type;
      var thisName  = f.elements[z].name;
      var thisValue = f.elements[z].value;

      // if this field matches required name
      if(thisName == userReqFields[i])
        {

        // check for empty text field value
        // --------------------------------------------------
        if(thisType == 'text'|| thisType == 'TEXT')
          {
          if(thisValue == "")
            {
            msg[msg.length] = cleanUnderscore(thisName) +"\n";
            req_error++;
            }
          }
          // check non-selected drop down (select field)
          // --------------------------------------------------
          else if(thisType == "select-one" || thisType == "SELECT-ONE")
          {
          if(f.elements[z].selectedIndex == 0)
            {
            msg[msg.length] = cleanUnderscore(thisName) + "\n";
            req_error++;
            }
          }
          // check for empty textarea
          // --------------------------------------------------
          else if(thisType == "textarea" || thisType == "TEXTAREA")
          {
          if(thisValue == "")
            {
            msg[msg.length] = cleanUnderscore(thisName) + "\n";
            req_error++;
            }
          }
          // check for unselected radio group
          // --------------------------------------------------
          else if(thisType == "radio" || thisType == "RADIO")
          {

           // get radio group length
          var radioLen = f.elements[f.elements[z].name].length;
          var test =0;

//          alert("RADIO LEN:"+radioLen);
          // loop radio group
          for(c=0;c<radioLen;c++)
            {

            // get this radio index in group
            var search = f.elements[f.elements[z].name];

//            alert("This radio"+search+"\n\nChecked?\n"+search[c].checked);

            // test this radio for checked
            if(search[c].checked)
              {
               test = 1;
              }
            }

//           alert("FINAL - any checked?\n\n"+ test);
          // filter checked radio
          if(!test)
            {
            var last = msg.length;
            if (last > 0) last--;
          else msg[0] = "";
//            alert('var last = ' +last);

            var temp = thisName;
            var temp2 = cleanUnderscore(temp);

            var search = msg[last];
//            alert("LAST MSG:"+search);
//            alert("cleanUnderScore:"+temp2);

            if(search.indexOf(temp2) == -1)
              {
               msg[msg.length] =  temp2 + "\n";
               req_error++;
              }
            }
            else
            {
//            alert("radio checked!")
            }


          }  // field type

        }    // req name search

      }      // form elements loop

    }        // required field loop


var reqFieldsTable = "\n------------------------\n";
 // required field list msg
 for(i=0;i<msg.length;i++)
    {
    reqFieldsTable += msg[i];
    }
// validate all groupsite req fields are present in quote form
 if(req_error > 0)
  {
  var fields = (userReqFields.length - req_error);
  var err;
  
  var err = eval("ReqFieldErrMsg_" + f.lang.value)
  
  if(err){
  alert(err +  reqFieldsTable);
  }else{
  alert(ReqFieldErrMsg_en_US + reqFieldsTable);
  }
  
  return false;
   
 }
 else
 // The script asumes that the "document.quote.Email_address" EXISTS.
 {
  //alert("all good sending...");

 var result =  _validateEmail(f.Email_address);

  if(result){
  // t affiliate id into brand hidden field
  var affID = setAffiliate();
  if(affID)
     {
     f.cntry.value = f.cntry.value + "\n SourceID["+affID+"]";
     }
  return true;
  }else{ return false; }
  //f.submit();
  }
}

// ***************************************************************
// This function has been added by Leonardo Feltrín (feltrin@ar.ibm.com)
// If the email entered is ok -------> returns TRUE
// If the email entered is not ok -------> returns FALSE
function _validateEmail(field) {
  var str = new String(field.value);
  while (str.substring(str.length-1,str.length) == ' ')
    str = str.substring(0, str.length-1);

  if (window.RegExp) {
    var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
    var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.\\_]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
    var reg1 = new RegExp(reg1str);
    var reg2 = new RegExp(reg2str);
    if (!reg1.test(str) && reg2.test(str))
    {}
    else
    {
    document.quote.Email_address.focus();
    document.quote.Email_address.select();
    window.alert("The e-mail entered is wrong. Please, check it and try again.");
    return false;
    }
  } else {
    if(str.indexOf("@") >= 0)
    {}
    else
    {
    field.focus();
    field.select();
    return false;
    }
  }
return true;
}
// ***************************************************************


function cleanUnderscore(str) {

 var search = str.indexOf("_");
 if(search != -1)
   {
   str = str.replace("_"," ");
   }
 return str;
}
//*********************************************
// load required hidden fields from coupon form
// into query string in order to redirect
// promotion page form submit to the popup window.
//*********************************************
function checkQuoteConfiguration(f){
var foundFields=0;
var foundReqField = false;
// define application groupsite required fields - we need this data to build file paths for required files
// validate form name
if(!document.quote)
  {
  var err;
//  eval("err = FormNameErrMsg_" + f.lang.value);
//  alert(err);
alert("quote form not found!");
  return 0;
  }
//------------------------------------------------------------
// - loop each application defined required field and extract field data
// - reset match flag
// - loop each form element and extract field data
// - search each form element for required field name
// - if app required field found increment total found counter
// - if app required field found trip match flag on
// - if app required field not found store field name for error msg
// - do final compare on num of required fields and num required found
// - return false if values do not match and msg error to developer
// - return true if all required fields found to submit quote
//------------------------------------------------------------

var msg="";
var test="";
// loop application required fields
for(i=0;i<appReqFields.length;i++)
   {
   //debug ? test += "req field:"+appReqFields[i] : die=0;

   // reset match flag
   foundReqField = false;

   // loop over every element in the form
   // search for any required field
   for(z=0;z<f.elements.length;z++)
     {
     // read in this field's data
     var thisType  = f.elements[z].type;
     var thisName  = f.elements[z].name;
     var thisValue = f.elements[z].value;

     if(thisName == appReqFields[i])
       {
       foundReqField= true;
       foundFields++
       }
     }

     if(!foundReqField)
       {
       msg += '<input type="hidden" name="'+ appReqFields[i] + '" value="' + appReqExample[i] + '" \>\n';
       //alert("required field not found:"+appReqFields[i]);
       }
   }
  //debug ? alert(test): die=0;
// required field list msg
var appReqFieldsTable = "\n\nMISSING REQUIRED RAQ HIDDEN FIELDS:\n-----------------------------------------------------\n" + msg;


// validate all groupsite req fields are present in quote form
if(foundFields == appReqFields.length)
  {
  return 1;
  }
  else
  {
  var fields = (appReqFields.length - foundFields)

  if(confirm("Your RAQ form is missing " + fields  + " required field(s).\n\nYou need these fields to continue.\nPlease add the following list to your form and try again\n" +  appReqFieldsTable + "\n\nWould you like to read the help doc on this file?"))
    {
    location.href="/cgi-bin/shop/americas/emails/quote/docs/help/quote_js.html";
    }

  return 0;
  }
}
function loadUserReqFields(f) {

var userReqFields = new Array();
var msg="";


// loop quote form and check for required fields
for(i=0;i<f.elements.length;i++)
   {
   var thisField = f.elements[i].name;
   var thisValue = f.elements[i].value;

   // if this field is user defined required field
   if(thisField.indexOf("req_") != -1)
     {

     msg += thisValue + "\n";
     // save required field in list
     userReqFields[userReqFields.length] = thisValue;
     }
   }
//alert(msg);
return userReqFields;
}

function valueGetter() {
  var msgWindow=window.open("")
    for (var i = 0; i < document.quote.elements.length; i++) {
      msgWindow.document.write(document.quote.elements[i].name + "<BR>")
         }
      }

function findChecked(radioGroup) {
//alert("running findChecked: "+radioGroup.length)
for(i=0;i<radioGroup.length;i++)
   {
   if(radioGroup[i].checked)
     {
      return i;
     }
   }
return 0;
}

//********************************************
// read promo checkboxes for order selection
// single quantity - any products
//********************************************
function checkOptions(f){
// loop over every element in the form
 for(i=0;i<f.elements.length;i++)
   {
    // filter quantity input field named "q_"
   if(f.elements[i].name.indexOf("q_") != -1)
     {
     // check if this field is "checked"
     if(f.elements[i].checked)
       {
       // set the checked radio value quantity to 1
       f.elements[i].value=1;
       // ok ready for cart
       validOrder=1;
       }
     }
  }
}

//********************************************
// read promo radio group for order selection
// single quantity - mutually exclusive products
//********************************************
function checkExclusiveOptions(form){

  // loop over every element in the form

  //  the radio group from coupon form
  var theGroup = form;

    // loop over each radio field
    for(i=0;i<theGroup.length;i++)
      {

     // if this radio "checked"
      if(theGroup[i].checked)
        {
        return 1;
        }
      }
 return 0;
}
//********************************************
// read promo radio group for order selection
// single quantity - mutually exclusive products
//********************************************
function checkSelectOptions(f){

 // loop over every element in the form
 for(i=0;i<f.elements.length;i++)
   {

   // get this fields name
   var thisName = f.elements[i].name;
   // get this fields value
   var thisType = f.elements[i].type;

   // filter select field type only
   if(thisType == "select-one")
     {
     // ok ready for cart
     validOrder=1;
     }
    }
}
//******************************
// assorted character filters
//******************************
function isDigit(character)
{
  var value = false;

  if ((character >= '0') && (character <= '9'))
  {
    value = true;
  }

  return value;
}

function isLetter(character)
{
  var value = false;

  if (((character >= 'A') && (character <= 'Z')) || ((character >= 'a') && (character <= 'z')))
  {
    value = true;
  }

  return value;
}

function isSpace(character)
{
  var value = false;

  if ((character == ' ') || (character == '\r') || (character == '\n') || (character == '\t'))
  {
    value = true;
  }

  return value;
}

function isAlphaNumeric(string)
{



  var value = false;

  for (var i = 0; i < string.length; i++)
  {
    if (isDigit(string.charAt(i)) || isLetter(string.charAt(i)))
    {
      value = true;
    }
    else
    {
      value = false;
      break;
    }
  }

  return value;
}

function isBlank(string)
{
  var value = true;

  for (var i = 0; i < string.length; i++)
  {
    if (!isSpace(string.charAt(i)))
    {
      value = false;
      break;
    }
  }

  return value;
}

function isUnsignedInteger(string)
{
  var value = false;

  for (var i = 0; i < string.length; i++)
  {
    if (isDigit(string.charAt(i)))
    {
      value = true;
    }
    else
    {

      value = false;
      break;
    }
  }

  return value;
}



if(debug){ alert("quote_v2.js loading complete") }
