<!--
//---  Revision History
//---  082405 - BM - Created Order Form
//---  
//--------------------------------------------------------------------------------
//  Defined Variables
//--------------------------------------------------------------------------------
  strSalestax       = 0.00
     
//--------------------------------------------------------------------------------
//  Check the Field for invalid characters
//--------------------------------------------------------------------------------
// "https://www.skipjackic.com/scripts/EvolvCC.dll?Authorize"
// "https://www.skipjackic.com/secure/echo.asp"

//------------------------------------------------------------------------------------------
//  Get the current Date
//------------------------------------------------------------------------------------------
function GetDate(){
// Get current date
   var now = new Date();

// What day number is it
   var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();

// Convert year to four figure format
   function y2k(number)
   {return (number < 1000) ? number + 1900 : number;}

// Join it all together
   today = (now.getMonth() + 1) + "/" + date + "/" + (y2k(now.getYear())) ;

   return today;
}

function MM_callJS(jsStr)
{ 
  return eval(jsStr)
}

//--------------------------------------------------------------------------------
//   Generate Unique Order Number 
// * Calculates number of Milliseconds between midnight (GMT) on 1/1/1970 
//   and the current date/time
//--------------------------------------------------------------------------------
function GenerateOrderNumber()
{
  tmToday = new Date();
  return tmToday.getTime();
}

//######################################################################
//### Generic Functions for Event Validation
//######################################################################
//=== isKeyOnlyNumbers(e)
//======================================================================
//=== Description: Keeps a user from entering specified characters into a form element
//===       Input: e - the javascript event
//=== Uses Func's: none
//===     Returns: true if restricted character - false if not restricted
//===     Example: onkeypress="if (isKeyOnlyNumbers(event)) {return false;}"
//===     Created: 10.16.00 - L2 / Last Modified: 10.16.00 - L2
//======================================================================
function isKeyOnlyNumbers(e)
{
  if (navigator.appName == "Netscape") { var nCheckChar = e.which;   }
  else                                 { var nCheckChar = e.keyCode; }
  
  var sCheckChar = String.fromCharCode(nCheckChar);
  
  if (!( nCheckChar > 45 && nCheckChar < 58))
  { 
    e.returnValue = false;
    return true;
  }
  else { return false; }  
}

//#####################################################################################
//### Generic Functions for Buttons
//#####################################################################################
//=== changeButton(sFormName,sElementName,sValue,sErrMsg)
//=====================================================================================
//=== Description: Sets a form button's value to a "in process" state
//===              and disallows them from being clicked again
//===       Input: sFormName - the form in which the element exists
//===              sElementName - the button element
//===              sValue - the value that button is being assigned on click
//===              sErrMsg - the message that will be displayed is clicked again
//===     Returns: true/false - depending on the button already being clicked or not
//=== Uses Func's: setTextValue()
//===     Example: onclick="if (changeButton(this.form.name,this.name,'Processing...',
//===                          'Already in the state of Processing your Transaction.  
//===                           Please Wait...')) {this.form.submit();}"
//===     Created: 08.08.01 - L2 / Last Modified: 00.00.00 - L2
//=====================================================================================
var bSubmitted = false;
function changeButton(sFormName,sElementName,sValue,sErrMsg)
{
  setTextValue(sFormName,sElementName,sValue);
  if (bSubmitted) { alert(sErrMsg);    return false; }
  else            { bSubmitted = true; return true;  }
}

function changeButtonBack(sFormName,sElementName,sValue)
{
  setTextValue(sFormName,sElementName,sValue);
  bSubmitted = false;
}

function setTextValue(sFormName,sElementName,sValue)
{ eval('document.'+sFormName+'.'+sElementName+'.value="'+sValue+'"') }

//#####################################################################################
//### Generic Functions for Field Validation/Formatting
//#####################################################################################
//--------------------------------------------------------------------------------
//    Function: replaceChars(strOrig,strOut,strAdd)
// Description: Replaces a string with another string
//       Input: strOrig - the string that is being modified
//              strOut  - what to replace
//              strAdd  - what to replace with
//     Returns: the modified string
//--------------------------------------------------------------------------------
function replaceChars(strOrig,strOut,strAdd) 
{
  strTemp = "" + strOrig;
  while (strTemp.indexOf(strOut)>-1) 
  {
    nCharPos = strTemp.indexOf(strOut);
    strTemp = "" + (strTemp.substring(0, nCharPos) + strAdd + strTemp.substring((nCharPos+ strOut.length), strTemp.length));
  }
  return strTemp;
}
//--------------------------------------------------------------------------------
//    Function: isEmpty(strInput)
// Description: See if an input value has been entered
//       Input: strInput - string being checked
//     Returns: true  - if empty
//              false - otherwise
//--------------------------------------------------------------------------------
function isEmpty(strInput)
{
  if (strInput.length == 0 || strInput == null) { return true;  }
  else                                          { return false; }
}

//#####################################################################################
//### Generic Functions for Text Boxes
//#####################################################################################

function setTextValue(sFormName,sElementName,sValue)
{ eval('document.'+sFormName+'.'+sElementName+'.value="'+sValue+'"') }

//=== setTextBoxColors(sElement,sFormName,sBackColor,sTextColor)
//======================================================================
//=== Description: Changes the background and text color for a text field
//===       Input: sFormName    - form name
//===              sElementName - form element
//===              sBackColor   - background color for text box
//===              sTextColor   - text color for text box
//=== Uses Func's: None
//===     Returns: Nothing
//===     Example: setTextBoxColors(sElement,sFormName,'#CC3300','WHITE');
//===     Created: 01.03.01 - L2 / Last Modified: 01.11.01 - L2
//======================================================================
function setTextBoxColors(sElement,sFormName,sBackColor,sTextColor)
{
  eval('document.' + sFormName + '.' + sElement + '.style.backgroundColor = sBackColor;');
  eval('document.' + sFormName + '.' + sElement + '.style.color           = sTextColor;');
}
//--------------------------------------------------------------------------------
//--- Format Money to a Number
//--------------------------------------------------------------------------------
function formatMoneyToNumber(strAmount)
{
  // Remove all extra characters
  strAmount = replaceChars(strAmount,'$','');  // Remove '$'
  strAmount = replaceChars(strAmount,',','');  // Remove ','
  strAmount = replaceChars(strAmount,' ','');  // Remove ' '

  if ( strAmount.indexOf('.') != strAmount.lastIndexOf('.') ) // Make sure there aren't two decimals in number
  { strAmount = strAmount.substring(0,strAmount.lastIndexOf('.')); }
  return strAmount;
}
//--------------------------------------------------------------------------------
//    Function: formatMoney(strAmount)
// Description: Formats to $X,XXX.XX
//       Input: strAmount
//     Returns: strAmount in $X,XXX.XX format
//--------------------------------------------------------------------------------
function formatMoney(strAmount)
{
  strAmount = '' + formatMoneyToNumber(strAmount);

  // Split up amount
  strDollar   = '' + Math.floor(strAmount);
  nCents      = 100 * (strAmount - strDollar) + 0.5;
  strTenth    = '' + Math.floor(nCents/10);
  strHundreth = '' + Math.floor(nCents%10);

  // Add commas
  nCommas     = Math.ceil((strDollar.length/3)-1);  // Numbers of commas needed
  for (var nPlace = 1; nPlace < nCommas+1; nPlace++)
  {
    nLength   = strDollar.length - nPlace + 1;
    nCommaPos = nLength - (3 * nPlace);
    strDollar = strDollar.substring(0,nCommaPos)+','+strDollar.substring(nCommaPos,strDollar.length);
  }
  
  // Put it all together
  strAmount   = '$' + strDollar + '.' + strTenth + strHundreth;

  return strAmount;
}
//--------------------------------------------------------------------------------
//    Function: isMoneyField(strFormName,strElementName)
// Description: Check field to see if its properly formated for money
//       Input: strFormName, strElementName - the form and element names being checked
//     Returns: true  - if field only contains proper characters
//              false - otherwise & pop-up required field prompt
//--------------------------------------------------------------------------------
function isMoneyField(strFormName,strElementName)
{
  strInput = eval('document.'+strFormName+'.'+strElementName+'.value');
  strInput = formatMoneyToNumber(strInput);
  if ( !isNumber(strInput) )
  { 
    if ( !isEmpty(strInput) )
    { requireField(strElementName,strFormName,"The value that you have entered (" + strInput + ") is invalid!\n\nPlease format it so that it only contains numbers or [$-,.] characters.\n\nExample: $100.00 or $10,000.00") }
    return false;
  }
  return true;
}
//--------------------------------------------------------------------------------
//--- Description: Strip Alpha characters from input
//---       Input: sInput - string to be stripped
//--- Uses Func's: isNumber
//---     Returns: correctly formated string
//---     Example: stripAlpha('B12Z3') //--- Returns '123'
//---     Created: 01.25.01 - L2 / Last Modified: 00.00.00 - L2
//--------------------------------------------------------------------------------
function stripAlpha(sInput)
{
  if (!isNumber(sInput)) //--- Make sure number contains no letters
  { 
    var sTemp, sTempNumber, sChar;
    sTemp = '';
    sTempNumber = sInput + ' '; //--- Add a space to the end for substing function

    for (nCount=0;nCount<sInput.length;nCount++)
    {
      sChar = sTempNumber.substring(nCount,nCount+1);  //--- Strip out one character at a time
      if (isNumber(sChar)) { sTemp += sChar; }         //--- Add to string only if's a number
    }
    sInput = sTemp;
  }
  return sInput;
}
//--------------------------------------------------------------------------------
//    Function: isNumberField(strFormName,strElementName)
// Description: Check field to see if it only contains numberic characters
//       Input: strFormName, strElementName - the form and element names being checked
//     Returns: true  - if field only contains proper characters
//              false - otherwise & pop-up required field prompt
//--------------------------------------------------------------------------------
function isNumberField(strFormName,strElementName)
{
  strInput = eval('document.'+strFormName+'.'+strElementName+'.value');
  if ( !isNumber(strInput) )  
  {
    if ( !isEmpty(strInput) )
    { requireField(strElementName,strFormName,"The value that you have entered (" + strInput + ") is invalid!\n\nPlease format it so that it only contains numbers.") }
    return false;
  }
  return true;
}
//-----------------------------------------------
// is a number
//-----------------------------------------------
function isNumber(strInput)
{
  strInput = '' + strInput;
  var reg = /^[0-9.\-]+$/;
  if (reg.test(strInput)) { return true;  } 
  else                    { return false; }
}
//-----------------------------------------------
// is a float
//-----------------------------------------------
function isFloat(strInput)
{
  strInput = '' + strInput;
  var reg = /^[0-9]+[.][0-9]+$/;
  if (reg.test(strInput)) { return true;  } 
  else                    { return false; }
}

//#####################################################################################
//### Form Specific Functions
//#####################################################################################
//---
//--------------------------------------------------------------------------------
//--- Declare Constants
//--------------------------------------------------------------------------------
m_sFormMain     = 'formMain';
m_sFormFinal    = 'formFinal';
m_sErrorMsg     = 'Required Information.';

//--------------------------------------------------------------------------------
//--- Check to see if the field is Empty ---
//--------------------------------------------------------------------------------
function checkRequiredField(sFormName,sElementName,sErrorMsg)
{
  if ( eval('isEmpty(document.'+sFormName+'.'+sElementName+'.value)') ) 
  { 
    requireField(sElementName,sFormName,sErrorMsg); 
    return false; 
  }
  else
  { return true; }
}
//--------------------------------------------------------------------------------
//--- Alert user that field is required & set the cursor to that field
//--- Modified from standard to add field color changing
//--------------------------------------------------------------------------------
function requireField(strElement,strFormName,strAlert)
{
  alert(strAlert);
  setFocusOnField(strElement,strFormName);
  setTextBoxColors(strElement,strFormName,'#CC3300','WHITE');
}
//--------------------------------------------------------------------------------
//--- Set the cursor to that field
//--------------------------------------------------------------------------------
function setFocusOnField(strElement,strFormName)
{
  eval('document.' + strFormName + '.' + strElement + '.focus();');
  eval('document.' + strFormName + '.' + strElement + '.select();');
}

//=== isFieldOfLength(sElementName,sFormName,sErrorMsg,nLengthMin,nLengthMax)
//======================================================================
//=== Description: Verifys that a string is within a specified length
//===       Input: sFormName, sElementName - the form and element names being checked
//===              sErrorMsg  - the error message that is passed to requiredField()
//===              nLengthMin - the minimum number of characters
//===              nLengthMax - the maximum number of characters
//=== Uses Func's: isEmpty(), requiredField(), getElementValue()
//===     Returns: true  - field is within length parameters
//===              false - field is outside of length parameters
//===     Example: if (!isFieldOfLength('formMain','password','Must be 8-16 Characters',8,16)) { return false; };
//===     Created: 08.16.02 - L2 / Last Modified: 00.00.00 - L2
//======================================================================
function isFieldOfLength(sElementName,sFormName,sErrorMsg,nLengthMin,nLengthMax)
{
// alert(sElementName + " / " + sFormName + " / " + sErrorMsg + " / " + nLengthMin + " / " + nLengthMax)
 
  var sValue = getElementValue(sFormName,sElementName);
  
  if (!(( sValue.length >= nLengthMin ) && ( sValue.length <= nLengthMax )))
  {    
    requireField(sElementName,sFormName,sErrorMsg); 
    return false; 
  }
  else
  { return true; }
}

function getElementValue(sFormName,sElementName)
{ return eval('document.' + sFormName + '.' + sElementName + '.value') }

//--------------------------------------------------------------------------------
//    Function: isCreditCardField(strFormName,strElementName)
// Description: Checks to see that the number passes the Luhn Mod-10 test
//       Input: strFormName, strElementName - the form and element names being checked
//     Returns: true  - if field only contains proper characters
//              false - otherwise & pop-up required field prompt
//--------------------------------------------------------------------------------
function isCreditCardField(strFormName,strElementName)
{
  strInput = eval('document.'+strFormName+'.'+strElementName+'.value');
  strInput = replaceChars(strInput,' ','');  // Remove ' '  
  strInput = replaceChars(strInput,'-','');  // Remove '-'  
  if ( !isCreditCard(strInput) )  
  {
    if ( !isEmpty(strInput) )
    { requireField(strElementName,strFormName,"The value that you have entered (" + strInput + ") is invalid!\n\nPlease check the credit card number once again.") }
    return false;
  }
  return true;
}

function isCreditCard(strInput) 
{
  if (strInput.length > 19) return (false);  // Encoding only works on cards with less than 19 digits
  sum = 0; mul = 1; l = strInput.length;
  for (i = 0; i < l; i++) 
  {
    digit    = strInput.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);
}

//--------------------------------------------------------------------------------
//--- Maps the Return/Enter key to the Submit Button
//--------------------------------------------------------------------------------
function keyMapEnterToSubmit()
{
 var nKey=event.keyCode;
 if (nKey==13) 
 {
   //--- Mag Stripe Reader already submits an enter key 
   if ( !isEmpty(document.formMain.sjname.value) )  
  
       { document.formMain.btnSubmit.click(); };
 }
}

//-------------------------------------------------------------------------------
// Calculate the transaction total
//-------------------------------------------------------------------------------
function transactionTotal()
{
  var saleamount      = 0.00;
      strCalcShipping = 0.00;

//  Calculate Item Amount  
  itemamount = document.formMain.prodQuantity1.value * document.formMain.prodPrice1.value

//               document.formMain.prodQuantity2.value * document.formMain.prodPrice2.value +
//               document.formMain.prodQuantity3.value * document.formMain.prodPrice3.value;
               
//  Calculate Sales Tax for Arizona  
  if ( document.formMain.state.value == 'OH' )
       {salestaxamount = itemamount * strSalestax;}
  else {salestaxamount = 0.00}
  
//  salestaxamount = Math.round(salestaxamount);

//  Calculate Shipping Amount  
//  if ( itemamount >  100.00)  {strCalcShipping = 16.00};
//  if ( itemamount <= 100.00)  {strCalcShipping = 11.00};
//  if ( itemamount <=  25.00)  {strCalcShipping =  6.00};

    strCalcShipping = 0.00;

//  Calculate Total Purchase Amount  
//  saleamount     = itemamount + salestaxamount + strCalcShipping;
  saleamount = itemamount

  if (saleamount == '') {saleamount = 0.00};

  saleamount     = (Math.round(saleamount * 100)) / 100;

//  Update Purchase Total area with new amounts
//  document.formMain.itemamount.value        = formatMoney(itemamount);
//  document.formMain.shippingamount.value    = formatMoney(strCalcShipping);
//  document.formMain.salestaxamount.value    = formatMoney(salestaxamount);
  document.formMain.transactionamount.value = formatMoney(saleamount);
}


//=== getLastChars(sInput,nNumChars) 
//======================================================================
//=== Description: Returns a specified number of character from the end of string
//===       Input: sInput - initial value
//===     Returns: string
//=== Uses Func's: none
//===     Example: getLastChars('1234567890',5) ==> "67890"
//===     Created: 12.20.02 - L2 / Last Modified: 00.00.00 - L2
//======================================================================
function getLastChars(sInput,nNumChars)
{ return sInput.substring(sInput.length-nNumChars,sInput.length); }

//###############################################################################
//### Client side order validation
//###############################################################################
function isValidOrder()
{
  //--- Credit Card Information ---
  if (!checkRequiredField(m_sFormMain,'accountnumber','Credit Card # Required!'))  { return false; };
  if ( !isCreditCardField(m_sFormMain,'accountnumber') )                           { return false; };
  if (!checkRequiredField(m_sFormMain,'month','Expiration Month Required!'))       { return false; };
  if (!checkRequiredField(m_sFormMain,'year','Expiration Year Required!'))         { return false; };
  if (!checkRequiredField(m_sFormMain,'cvv2','CVV2 # Required!'))                  { return false; };

  //--- Payment Information ---
  if (!checkRequiredField(m_sFormMain,'customername','Customer Name Required!'))   { return false; };
  if (!checkRequiredField(m_sFormMain,'streetaddress','Street Address Required!')) { return false; };
  if (!checkRequiredField(m_sFormMain,'city','City Required!'))                    { return false; };

  if ( isEmpty(document.formMain.state.value) )
       {alert('State Required!');
        return false;
       }

  if (!checkRequiredField(m_sFormMain,'zipcode','Zip Code Required!'))             { return false; };
  if (!checkRequiredField(m_sFormMain,'shiptophone','Phone Number Required!'))     { return false; };
  if (!checkRequiredField(m_sFormMain,'email','Email Address Required!'))          { return false; };

      document.formMain.transactionamount.value = formatMoney(document.formMain.transactionamount.value);
      
  if (document.formMain.transactionamount.value == "$0.00")
     { requireField('transactionamount','formMain','Transaction amount cannot be $0.00!'); return false; }
  if (document.formMain.transactionamount.value == "")
     { requireField('transactionamount','formMain','Transaction Amount Needed!'); return false; }

  return true;
}

//###############################################################################
//### Final Submission of Form
//###############################################################################

function sendOrder()
{
    if (isValidOrder())
    {
      document.formFinal.ordernumber.value          = 'WEB' + GenerateOrderNumber();

      document.formFinal.accountnumber.value        = document.formMain.accountnumber.value;
      document.formFinal.month.value                = document.formMain.month.value;
      document.formFinal.year.value                 = document.formMain.year.value;
      document.formFinal.cvv2.value                 = document.formMain.cvv2.value;

      document.formFinal.name.value                 = document.formMain.customername.value;
      document.formFinal.streetaddress.value        = document.formMain.streetaddress.value;
      document.formFinal.streetaddress2.value       = document.formMain.streetaddress2.value;
      document.formFinal.city.value                 = document.formMain.city.value;
      document.formFinal.state.value                = document.formMain.state.value;
      document.formFinal.zipcode.value              = document.formMain.zipcode.value;
      document.formFinal.country.value              = document.formMain.country.value;
      document.formFinal.shiptophone.value          = document.formMain.shiptophone.value;
      document.formFinal.email.value                = document.formMain.email.value;

//      document.formFinal.shiptoname.value           = document.formMain.shiptoname.value;
//      document.formFinal.shiptostreetaddress.value  = document.formMain.shiptostreetaddress.value;
//      document.formFinal.shiptostreetaddress2.value = document.formMain.shiptostreetaddress2.value;
//      document.formFinal.shiptocity.value           = document.formMain.shiptocity.value;
//      document.formFinal.shiptostate.value          = document.formMain.shiptostate.value;
//      document.formFinal.shiptozipcode.value        = document.formMain.shiptozipcode.value;
//      document.formFinal.shiptocountry.value        = document.formMain.shiptocountry.value;

//      document.formFinal.itemamount.value           = document.formMain.itemamount.value;
//      document.formFinal.shippingamount.value       = document.formMain.shippingamount.value;
//      document.formFinal.salestaxamount.value       = document.formMain.salestaxamount.value;
      document.formFinal.transactionamount.value    = formatMoneyToNumber(document.formMain.transactionamount.value);
      
      document.formFinal.comment.value              = document.formMain.comment.value;

      document.formFinal.orderstring.value          = makeItemString();

      if (changeButton('formMain','btnSubmit','Processing...',
         'Already in the state of Processing your Transaction.  Please Wait...'))
  
         {document.formFinal.submit();} 
    }
}

function makeItemString()
{

   var ItemCode;
   var ItemDesc;
   var ItemQnty;
   var ItemAmount;
   var sDiv = "~";
   var sEndDiv = "~||"
   var ItemString = "";
   var MainForm = "formMain";

   var NumItems = 1;
   var i = 1;

   for ( i = 1; i <= NumItems; i++ )
   {
      ItemCode   = eval( "document." + MainForm + ".prodCode" + i );
      ItemDesc   = eval( "document." + MainForm + ".prodName" + i );
      ItemQnty   = eval( "document." + MainForm + ".prodQuantity" + i );

      
      ItemAmount = eval( "document." + MainForm + ".prodPrice" + i + ".value" );

      if ( ItemQnty.value != "" && ItemAmount != "$0.00" && ItemAmount != "" )
      {
         ItemString += ItemCode.value + sDiv;
         ItemString += ItemDesc.value + sDiv;
         ItemString += formatMoneyToNumber( ItemAmount ) + sDiv;
         ItemString += ItemQnty.value + sDiv;
         ItemString += "N" + sEndDiv;
      }
      // only add non-zero items

   } // loop through line items

   return ItemString;

} // makeItemString
