/*
 * functions.js
 * 
 * Contains javascript functions used in the shopping cart and checkout
 * features of stadiometer.com.  Originally derived from code written
 * by somebody else embedded in the HTML.  All functions have undergone
 * a complete rewrite as of 11.25.2005.
 *
 * Micah Carrick - email@micahcarrick.com
 *
*/

// this is for the hourglass display in cartinc and checkout.
if (window.Event)
   document.captureEvents(Event.CLICK | Event.KEYPRESS | Event.KEYDOWN | Event.MOUSEDOWN);

document.onclick = checkoutEventHandler;
document.onkeypress = checkoutEventHandler;
document.onkeydown = checkoutEventHandler;
document.onmousedown = checkoutEventHandler;

var bAllowEvent = true;

function checkoutEventHandler()
{
      if (bAllowEvent) return true;
      else return false;
}

// Is this still being used?
var sProtocol = document.location.protocol;
sProtocol = sProtocol.substring(0,5);
if (sProtocol == 'https') sProtocol = 'https:'

// preload invisible zip code graphic for cartinc
var bZipUpdateRequired = false;
var changeZipGraphic = new Image(160, 20);
changeZipGraphic.src = sProtocol+"//www.stadiometer.com/cart/images/change_zip2.gif";

function ieMacCheck()
{
   var detect = navigator.userAgent.toLowerCase();

	if ((detect.indexOf('mac') != -1) && (detect.indexOf('msie') != -1))
	{
	  jsError("ieMacCheck()", '005');    
	}
}

function validateParams(oF)
{
   /*
   Ensures that all fields in the form passed in oF which are required (indicated
   by a double underscore prefix) are not empty.  This is for use on adding items
   to the cart which have extra parameters.  If the parameters have not been specified,
   then the function returns false preventing the form from being submitted.  Should
   be used in the form's onSubmit event: onsubmit="return validateParams(this);"
   */
   
   var sName="";
   var sValue="";
   var sErr="";
   
   // iterate through elements and find required fields.
   for (var i=0; i < oF.elements.length; i++) 
   {
     sName = oF.elements[i].name;
     sValue = oF.elements[i].value;
     if (sName.substring(0,2) == "__")
     {
        if (sValue == "")
        {
            // empty parameter.  Make a readable name for the error message
            var objRegExp =  new RegExp( '_', 'gi' );
            if (objRegExp)
            {
               sName = sName.replace(objRegExp, ' ');
            }
            
            // append this item to the error message
            sErr = sErr + "'" + sName.substring(2) + "' is a required field.\n"; 
        }
     }
   }
   if (sErr != "")
   {
      // if an error message has been formed, then there were errors.  Display 
      // the message and return false.
      alert(sErr);
      return false;  
   }
   
   else return true; // we're all good to go. :)
}

function showZipButton() 
{
   
   /*
   Shows the "change zip code" button in the cart when the user types a new
   zip code in the input box.
   */
   
   if (bZipUpdateRequired == false) {
      oEl = getObj('zip_button');
      oEl.src = changeZipGraphic.src;
      oEl.style.cursor = "pointer";
      bZipUpdateRequired = true;
   }
}

function checkout(sSite) 
{
   
   /* 
   checkout from cartinc by first changing action of the form so that it's not just
   updating the form and returning to the current page.
   */
   
   var oForm = getFormObj('noname');
   waitForReload();
   oForm.action = "https://www.stadiometer.com/cart/addcookie.php?act=checkout&page="+sSite; 
   oForm.submit();
}

function s_checkout(sSite) 
{
   
   /* 
   checkout from cartinc by first changing action of the form so that it's not just
   updating the form and returning to the current page.  Uses secure HTTPS link for redir.
   */

   var oForm = getFormObj('noname');
   waitForReload();
   oForm.action = "https://www.stadiometer.com/cart/addcookie.php?act=checkout&page="+sSite; 
   oForm.submit();
}

function empty_cart(sLink)
{
   /*
   Confirms that the user wants to empty the entire cart and proceeds to 
   the addcookie.php script to remove the items from the cart.
   */
   
   var sMsg = "Are you sure you want to remove all the items from your cart?";
   if (confirm(sMsg)) 
   {
      window.location.href = sLink;
   }
}
   
function changeDisplay(sID, bVisible) 
{
   /*
   Changes a layer's display property.  
   true = 'display: block;'
   false = 'display: none;'
   */  
   
   var oEl = getObj(sID);
   
   if (bVisible) oEl.style.display = 'block';
   else oEl.style.display = 'none';
}

function changeVisibility(sID, bVisible) 
{
   /*
   Changes a layer's visibility property.  
   true = 'visibility: visible;'
   false = 'visibility: hidden;'
   */   

   var oEl = getObj(sID);
   
   if (bVisible) oEl.style.visibility = 'visible';
   else oEl.style.visibility = 'hidden';
}

function countryChanged()
{
   /*
   Used to toggle the state from a select box to an input box when the country 
   is NOT united states.  Requires that the checkState function is called when 
   the form is submitted to ensure that the right value for state is submitted 
   with the POST vars.  This should be called in the country select onChange 
   event.
   */
   
   var theForm = getFormObj('billing');
   
   if(theForm.Country.value == "United States")
   {
      changeDisplay('state_select', true);
      changeDisplay('state_input', false);
   } else {
      changeDisplay('state_select', false);
      changeDisplay('state_input', true);
   }
}

function checkState()
{
   /* 
   If the country is not the US, then this function will take the value in the 
   standard input and put it into the hidden State form field.  Otherwise, 
   it takes the value in the state select box and puts it into the hidden form 
   field.
   */
 
   var theForm = getFormObj('billing');
     
   if(theForm.Country.value != "United States")
   {     
      theForm.State.value = theForm.StateB.value; 
      if ((theForm.State.value == "" || !theForm.State.value) && theForm.StateB.value != "")
      {
         jsError('checkState()', '005');
         return false;
      }
   } else {
      theForm.State.value = theForm.StateA.options[theForm.StateA.selectedIndex].value; 
      if ((theForm.State.value == "" || !theForm.State.value) && theForm.StateA.options[theForm.StateA.selectedIndex].value != "")
      {
         jsError('checkState()', '005');
         return false;
      } 
   }

   return true;
}

function removeCharacters( strValue, strMatchPattern ) {
   
   /* 
   Strips the specified characters from the string replacing them with a blank char
   */
   
   var objRegExp =  new RegExp( strMatchPattern, 'gi' );
   if (!objRegExp)
   {
      jsError('removeCharacters()', '004');
      return "";  
   }
   return strValue.replace(objRegExp,'');
}

function continueCheckout() 
{
   /*
   Performs all required javascript validation and checks before submitting the form.  
   */
     
   // move stateA or stateB into hidden state field
   if (!checkState()) return false;
      
   // ensure required fields are filled in
   if (!validateCheckingFields()) return false;
   
   // validate the credit card
   if (!testCreditCard()) return false;

   waitForReload();
   return true;
    
}

function validateCheckingFields() 
{
   /*
   Validates that all of the required fields are present.
   */  
   
   var oForm = getFormObj('billing');
   var oFocus;
   var retVal = true;
   var sMsg = '';
   
   // ensure required shipping fields
   if (oForm.ShipName.value == '') 
   {
      sMsg = sMsg + "'First Name' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.ShipName;
      retVal = false;
   }
   if (oForm.ShipSurname.value == '') 
   {
      sMsg = sMsg + "'Last Name' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.ShipSurname;
      retVal = false;
   }
   if (oForm.ShipAddress.value == '') 
   {
      sMsg = sMsg + "'Address Line 1' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.ShipAddress;
      retVal = false;
   }
   if (oForm.ShipCity.value == '') 
   {
      sMsg = sMsg + "'City' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.ShipCity;
      retVal = false;
   }
   if (oForm.ShipState.value == '') 
   {
      sMsg = sMsg + "'State' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.ShipState;
      retVal = false;
   }
   if (oForm.ShipPhone.value == '') 
   {
      sMsg = sMsg + "'Phone' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.ShipPhone;
      retVal = false;
   }
   
   // fixed fields but MUST BE PRESENT
   if (oForm.fixed_shipping_zip.value == '')
   {
      sMsg = sMsg + "'Zip' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.x_zip;
      retVal = false;
   }
   if (oForm.fixed_country.value == '')
   {
      sMsg = sMsg + "'Country' is a required field for Shipping Information\n";
      if (!oFocus) oFocus = oForm.x_country;
      retVal = false;
   }
      
   // ensure required billing fields
   if (oForm.Name.value == '') 
   {
      sMsg = sMsg + "'First Name' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Name;
      retVal = false;
   }
   if (oForm.Surname.value == '') 
   {
      sMsg = sMsg + "'Last Name' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Surname;
      retVal = false;
   }
   if (oForm.Email.value == '') 
   {
      sMsg = sMsg + "'Email' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Email;
      retVal = false;
   }
   if (oForm.Address.value == '') 
   {
      sMsg = sMsg + "'Address Line 1' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Address;
      retVal = false;
   }
   if (oForm.City.value == '') 
   {
      sMsg = sMsg + "'City' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.City;
      retVal = false;
   }
   if (oForm.State.value == '') 
   {
      sMsg = sMsg + "'State' is a required field for Billing Information\n";
      if (!oFocus && oForm.Country == 'Unites States') oFocus = oForm.StateA;
      else if (!oFocus) oFocus = oForm.StateB;
      retVal = false;
   }
   if (oForm.Country.value == '') 
   {
      sMsg = sMsg + "'Country' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Country;
      retVal = false;
   }
   if (oForm.Zip.value == '') 
   {
      sMsg = sMsg + "'Zip Code' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Zip;
      retVal = false;
   }
   if (oForm.Phone.value == '') 
   {
      sMsg = sMsg + "'Phone' is a required field for Billing Information\n";
      if (!oFocus) oFocus = oForm.Phone;
      retVal = false;
   }
   
   // If something is not valid, we scroll to the top and focus the first
   // missing object.
   
   if (!retVal)
   {
      scroll(0,0);
      alert(sMsg);
      oFocus.focus();
   }
   
   return retVal;  
}
function testCreditCard () {
   
   // validates all the credit card form data and the credit card
   // number.  Since this is used when the form is submitted, I'm
   // also putting some other "last steps" in the block of code
   // where the credit card is deamed valid.
   
   bForm = getFormObj('billing');
   
   e = bForm.pay1;
   e.value = removeCharacters(e.value, ' *');
   e.value = removeCharacters(e.value, '-*');
   
   myCardNo = e.value;
   
   e = bForm.paytype;
   myCardType = e.options[e.selectedIndex].value;
   
   // ensure the name on card field is filled out.
   
   myName = bForm.pay2.value;
   if (myName.length == 0) 
   {
     alert ("Please enter the name as it appears on the credit card.");
     return false;
   }
  
  // check the ccv value if the different billing address is checked.
  // should be 3 digits for all cards except amex which should be 4.
  
   myCVV = bForm.cvv.value;

   if (myCardType != 'American Express' && myCVV.length != 3) {
      
      alert ("CVV number must be 3 digits.");
      return false;    
       
   } else if (myCardType == 'American Express' && myCVV.length != 4) {
      
      alert ("CVV number must be 4 digits.");
      return false;    
      
   }
  
   // check to ensure the expiration date chosen is AFTER the current
   // date.  This ensures that the user isn't just leaving those values
   // what they were when the page was loaded.
   
   expMonth = bForm.pay4_1.value;
   expYear = bForm.pay4_2.value;
   
   var oDate = new Date();
   if (!oDate || !oDate.getFullYear()) 
   {      
      // no support for date object
      jsError('testCreditCard()', '003');
      return false;
   }
   thisMonth = oDate.getMonth() + 1;
   thisYear = oDate.getFullYear();
  
   if (thisYear > expYear) 
   {
      alert("Credit card is expired.");
      return false;
   } 
   else if ((thisYear == expYear) && (expMonth < thisMonth))
   {
      alert("Credit card is expired.");
      return false;
   }
  
   // validate the card (references functions in creditcard.js)
   if (checkCreditCard (myCardNo,myCardType)) {
      return true;
   } 
   else {
      alert (ccErrors[ccErrorNo]);
      return false;
   }
}

function copyShippingToBilling() 
{
   /*
   Here's a doozie.  This is used to copy all of the shipping fields to the
   billing fields when the checkbox is checked.  Has to consider whether
   the state fields are input or select boxes, etc.  So that makes it kind
   of slow and therefore it is ONLY used when checkbox is checked and not
   for each fields onblur event--that is handled one at a time.
   */
   
   var oForm = getFormObj('billing');
   var copyFields = oForm.SameBillInfo.checked;
   
   if (copyFields)   
   {
      // copy over field values
      oForm.Name.value = oForm.ShipName.value;
      oForm.Surname.value = oForm.ShipSurname.value;
      oForm.Company.value = oForm.ShipCompany.value;
      oForm.Email.value = oForm.ShipEmail.value;
      oForm.Address.value = oForm.ShipAddress.value;
      oForm.Address2.value = oForm.ShipAddress2.value;
      oForm.City.value = oForm.ShipCity.value;
      oForm.Zip.value = oForm.fixed_shipping_zip.value;
      oForm.Phone.value = oForm.ShipPhone.value;
      
      // ensure proper field highlighting on required fields
      fieldLostFocus(oForm.Name, oForm.Name.value, true);
      fieldLostFocus(oForm.Surname, oForm.Surname.value, true);
      fieldLostFocus(oForm.Email, oForm.Email.value, true);
      fieldLostFocus(oForm.Address, oForm.Name.Address, true);
      fieldLostFocus(oForm.City, oForm.City.value, true);
      fieldLostFocus(oForm.Zip, oForm.Zip.value, true);
      fieldLostFocus(oForm.Phone, oForm.Phone.value, true);
            
      // gets tricky here for selecting the state and country stuff when
      // copying over.  

      // Change the country to fixed_country.
      for (i=0; i<oForm.Country.length; i++) {
         if (oForm.Country.options[i].value == oForm.fixed_country.value)
         {
            oForm.Country.options[i].selected = true;
         } else {
            oForm.Country.options[i].selected = false;
         }
      }
      
      // Call countryChanged() to update the billing state input
      countryChanged();
      
      // Get the appropriate value for the shipping state
      var sStateValue;
      if (oForm.fixed_country.value == "United States")
      {
         sStateValue = oForm.ShipState.options[oForm.ShipState.selectedIndex].value;
      } else {
         sStateValue = oForm.ShipState.value;
      }
      
      // Copy the appropriate state value to the billing side
      if (oForm.Country.value == "United States")
      {
         for (i=0; i<oForm.StateA.length; i++) {
            if (oForm.StateA.options[i].value == sStateValue)
            {
               oForm.StateA.options[i].selected = true;
            } else {
               oForm.StateA.options[i].selected = false;
            }
         }
         
         if (sStateValue != "" && oForm.StateA.style) oForm.StateA.style.backgroundColor = "";
         
      } else {
         
         oForm.StateB.value = sStateValue;
         if (sStateValue != "" && oForm.StateB.style) oForm.StateB.style.backgroundColor = "";
         
      }     
   } 
   else
   {
      oForm.Name.value = "";
      oForm.Surname.value = "";
      oForm.Company.value = "";
      oForm.Email.value = "";
      oForm.Address.value = "";
      oForm.Address2.value = "";
      oForm.City.value = "";
      oForm.Zip.value = "";
      oForm.Phone.value = "";
      oForm.StateA.options[0].selected = true;
      oForm.StateB.value = "";
      // oForm.Country.options[0].selected = true; <-- no good.  Selects afghanistan
   }
   
   // if (oForm.Company.value == "") qmgsBlur();
   // else qmgsFocus('');
}

function fieldGotFocus(oField, sValue, bRequired)
{
   // do nothing yet...
   qmgsBlur();
   return;
}

function fieldLostFocus(oField, sValue, bRequired)
{
   /*
   called by each of the checkout fields to peform the necessary highlighting
   or clearing of highlight on required fields.  If the field is empty, and
   it is required, it is highlighted. Otherwise, highlight is cleared. If it's
   a required field, and the same billing info option is checked, then this will
   also copy the value down to the billing info fields.
   */
   
   var oForm = getFormObj('billing');

   if (!oField) 
   {
      jsError('fieldLostFocus()', '002'); 
      return;
   }
   
   // modify bgcolor of the element if the style element is available
   if (oField.style)
   {  
      if (bRequired && sValue == '') oField.style.backgroundColor = '#fffbc0';
      else oField.style.backgroundColor = '';
   }
   
   if (oForm.SameBillInfo.checked)
   {
      // copy the appropriate field and ensure appropriate bg color
      if (oField.name == 'ShipName') 
      {  
         oForm.Name.value = sValue; 
         fieldLostFocus(oForm.Name, oForm.Name.value, true);
      } 
      else if (oField.name == 'ShipSurname') 
      {
         oForm.Surname.value = sValue;
         fieldLostFocus(oForm.Surname, oForm.Surname.value, true);
      }
      else if (oField.name == 'ShipCompany') 
      {
         oForm.Company.value = sValue;
      }
      else if (oField.name == 'ShipEmail') 
      {  
         oForm.Email.value = sValue;
         fieldLostFocus(oForm.Email, oForm.Email.value, true);
      }
      else if (oField.name == 'ShipAddress') 
      {
         oForm.Address.value = sValue;
         fieldLostFocus(oForm.Address, oForm.Name.Address, true);
      }
      else if (oField.name == 'ShipAddress2') 
      {
         oForm.Address2.value = sValue;
      }
      else if (oField.name == 'ShipCity') 
      {
         oForm.City.value = sValue;
         fieldLostFocus(oForm.City, oForm.City.value, true);
      }
      else if (oField.name == 'ShipState') 
      {
         copyShippingToBilling(); // little more tricky on this one
      }
      else if (oField.name == 'ShipPhone')
      {
         oForm.Phone.value = sValue;
         fieldLostFocus(oForm.Phone, oForm.Phone.value, true);
      }
      else if (oField.name == 'x_zip') 
      {
         oForm.Zip.value = sValue;
         fieldLostFocus(oForm.Zip, oForm.Zip.value, true);
      }
   }
}

var zipButton = 0;
function updateShipZipCartinc()
{
   var oF = getFormObj('noname');
   
   if (oF.zip.value == "")
   {
      zipButton = 1; 
      alert ("Please enter your shipping destination Zip Code in the box at left.");
      return;  
   } 
   else zipButton = 0;

   updateCartFromCartinc();
}

function checkZipField() {
   
   /*
   Checks to ensure the zip code field has been filled in on the cart.  Uses the
   global variable zipButton.
   */
   
   var oForm = getFormObj('noname');
   
   if (zipButton == 1) return false;
   return true;
}

function updateShipZip()
{
   /*
   copy the value in the shipping zip field that user enters into the hidden field
   in the noname form which is submitted to addcookie.php to update the shipping
   calculations
   */
   
   var nForm = getFormObj('noname');
   var bForm = getFormObj('billing');
   
   if (bForm.x_zip.value == "")
   {
      alert ("Please enter your shipping destination Zip Code in the box at left.");
      return;  
   }
   nForm.zip.value = bForm.x_zip.value;
   updateCartFromCheckout(true);
}

function updateShipCountry()
{
   /*
   copy the value in the shipping country field that user enters into the hidden field
   in the noname form which is submitted to addcookie.php to update the shipping
   calculations
   */
   
   var bForm = getFormObj('billing');
   var nForm = getFormObj('noname');
   var oBox = bForm.x_country;
   var oField = nForm.country; 
   
   oField.value = oBox.options[oBox.selectedIndex].value;
   updateCartFromCheckout(true);
}

function updateShippingMethod(sValue)
{
   /*
   copy the value in the shipping method field that user click into the hidden field
   in the noname form which is submitted to addcookie.php to update the shipping
   calculations
   */
   
   var oForm = getFormObj('noname');
   
   oForm.ShipType.value = sValue;
   updateCartFromCheckout(true);
}

function removeCartItem(sURL, itemId, sSite)
{
   var oForm = getFormObj('noname');
   
   oForm.action = sURL + "?itemid="+itemId+"&act=remove&site="+sSite;
   updateCartFromCheckout(true);
}

function continueShopping(sAction)
{
   var oForm = getFormObj('noname');
   
   oForm.action = sAction;
   updateCartFromCheckout(false);   
}

function updateCartFromCartinc()
{
   waitForReload();
   oF = getFormObj('noname');
   oF.submit();
}

function updateCartFromCheckout(bShowRefresh)
{
   /*
   Performs steps needed to setup the form before submitting it to addcookie.php and
   ensures that session variables are updated.
   */
   
   if (!bAllowEvent) return;
   
   var oFrom = getFormObj('billing');
   var oToo = getFormObj('noname');
   var sName;
   var vValue;
   
   // ensure state is copied from StateA or StateB field
   checkState();
   
   // itterate through fields and copy any to the noname form that have already
   // been filled in so that they can be passed to addcookie.php and added to 
   // the sessions vars.
   
   for (i=0; i<oFrom.elements.length; i++) {
      sName = oFrom.elements[i].name;
      vValue = oFrom.elements[i].value;
      if (oToo.elements[sName])
      {
         // special cases
         if (sName == 'SameBillInfo') 
         {
            oToo.elements['SameBillInfo'].value = oFrom.elements['SameBillInfo'].checked;
         } 
         
         else 
         {
            // if (sName == 'qmgs') alert(vValue);
            oToo.elements[sName].value = vValue;
         }
      }
   }  
   
   // submit form and show the refresh screen
   oToo.submit(); 
      
   waitForReload();
   // if (bShowRefresh) showRefreshScreen('Please wait, re-claculating shipping...');

}

function waitForReload()
{
   /*
   Sets up a wait cursor and toggles the bAllowEvent flag.  The bAllowEvent flag
   is used by checkoutEvents.js which will prevent mouse clicks and key presses
   while the page is reloading.
   */
   
   setStyleByTag('A','cursor', 'wait', 1);
   setStyleByTag('DIV','cursor', 'wait', 1);
   setStyleByTag('INPUT','cursor', 'wait', 1);
   setStyleByTag('IMG','cursor', 'wait', 1);
   setStyleByTag('TD','cursor', 'wait', 1);
   setStyleByTag('FONT','cursor', 'wait', 1);
   setStyleByTag('BODY','cursor', 'wait', 1);
     
   bAllowEvent = false;  
}

// setStyleByTag: given an element type, style property and 
// value, and whether the property should override inline styles or
// just global stylesheet preferences, apply the style.
// args:
//  e - element type or id
//  p - property
//  v - value
//  g - boolean 0: modify global only; 1: modify all elements in document
function setStyleByTag(e, p, v, g) {
	if(g) {
		var elements = document.getElementsByTagName(e);
		for(var i = 0; i < elements.length; i++) {
			elements.item(i).style[p] = v;
		}
	} else {
		var sheets = document.styleSheets;
		if(sheets.length > 0) {
			for(var i = 0; i < sheets.length; i++) {
				var rules = sheets[i].cssRules;
				if(rules.length > 0) {
					for(var j = 0; j < rules.length; j++) {
						var s = rules[j].style;
						// selectorText broken in NS 6/Mozilla: see
						// http://bugzilla.mozilla.org/show_bug.cgi?id=51944
						ugly_selectorText_workaround();
						if(allStyleRules) {
							if(allStyleRules[j] == e) {
								s[p] = v;
							}			
						} else {
							// use the native selectorText and style stuff
							if(((s[p] != "") && (s[p] != null)) &&
							   (rules[j].selectorText == e)) {
								s[p] = v;
							}
						}

					}
				}
			}
		}
	}
}

function showRefreshScreen(sMsg)
{
   /*
   Blanks the screen with just the message so that the user doesn't continue clicking
   buttons and what not when the form is being submitted.
   */
   
   var o = getObj('docBody');    // 'docBody' is a DIV around the entire page
   o.innerHTML = '<br /><br /><center>'+sMsg+'</center>';   

}

function checkAlerts() {
   var o = getObj('auth_declined');
   if (o.value == 1) {
      alert("Your credit card was not approved.\nPlease verify all information and try again.");
   }
   o = getObj('auth_invalid');
   if (o.value == 1) {
      alert("Your credit card information is not valid.\nPlease verify all information and try again.");
   }    
}

function qmgsFocus(sAorB)
{

   /*
   The qmgs field (or the input box for company) has recived focus. This is where
   we ensure the options for qmgs are visible and set the qmgs hidden form field
   */
   
   // show the government sales selection option
   changeDisplay('qmgs_div_a', true);
   changeDisplay('qmgs_div_b', true);
      
   // get objects
   var f = getFormObj('billing');
   var qmgsObj = f.elements['qmgs'];
   var _qmgsObj;
   
   if (sAorB == 'a') _qmgsObj = f._qmgs_a[0];
   else if (sAorB == 'b')  _qmgsObj = f._qmgs_b[0];  
   
   // set the hidden field (the one that actually gets posted
   if (_qmgsObj && _qmgsObj.checked) qmgsObj.value = "1";
   else qmgsObj.value = "0";
   
}

function qmgsBlur()
{

   /*
   The qmgs field (or the input box for company) has lost focus. We
   hide the qmgs stuff if it's empty.  Otherwise, it stays "open"
   */
   
   
   var f = getFormObj('billing');
   
   if (f.elements['Company'].value.length <= 0 &&
       f.elements['ShipCompany'].value.length <= 0 &&
       f.elements['qmgs'].value == 0)
   {

      changeDisplay('qmgs_div_a', false);
      changeDisplay('qmgs_div_b', false);
   }
}

function companyBlur()
{
   
}

function getFormObj(sName)
{
   /*
   Return the form object or error if it does not exist.
   */
   
   if (document.forms[sName]) return document.forms[sName];
   else jsError("getFormObj('"+sName+"')", '001');
}

function getObj(sId)
{
   /*
   Return the object of the requested ID if it exists, and the browser supports the
   getElementById method. Otherwise throw an error.
   */
   
   if (document.getElementById(sId)) return document.getElementById(sId);
   else jsError("getObj('"+sId+"')", '002');
     
}

function jsError(sFunc, sErrNo)
{
   /*
   Error somewhere in javascript.  Redirect to error page notifying user to call the
   1-800 number and log the error.
   */
   
   var sNewHref = "http://www.stadiometer.com/cart/jserror.php?err="+sErrNo+"&func="+sFunc;
   sNewHref = sNewHref + "&page=" + window.location.href;
   window.location.href = sNewHref;
}
