/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Common JavaScript functions used to calculate and validate form-based ordering forms.
//
// Naming Structure for form items

//
// Items to Customize in this script
// 		- Discount Groups
//		- Required Fields
//		- Sales Tax
//
// Items to add to Order Form
//		- Before codeing
//			- Decide what fields are required.
//			- Product Codes (Client have some?)
//			- Discounts
//			- Shipping Rates
//			- Ship-To States
// 		- To Form Container
//			- Name = '[Whatever]' This script does not use the name but rather grabs the document.forms[0] object. The name is often used in other web apps however... Probably a good idea to make it as descriptive as possible.
//			- Add 'onSubmit="return formChecker(this);"'
//		- Add Hidden Fields
//			- name="ord_quantity_Flat" value=""
//			- name="ord_quantity_Grid" value=""
//
//		- For Each Item to purchase
//			- Hidden Fields with the following properties:
// 				- Items are configured by adding a prefix and a suffux to a product code
//				- Prefix: 'itm_'
//				- Suffixes:
//					- '_d' : Description
//					- '_p' : Price
//					- '_g' : Discount Group (Configured in the matrix below - not required)
//					- '_s' : Shipping Type - Values should be either 'Flat' or 'Grid'
//					- '_q' : Quantity
//					- '_x' : eXtended price (used to show line item expanded totals, ie: 5 @ $20 = $100)
//				- Add to 'itm_[whatever]_q' Select Box, 'onChange="itm_calc();"'
//				- Add to 'itm_[whatever]_x' Input Box, 'disabled onChange="return fail_change();"'
//		- For Each Field that user cannot update (ie: subtotal, tax, shipping, discounts, grandtotal, etc.)
//				- Add 'disabled onChange="return fail_change();"' to container.
//		- For Each Field that should trigger a re-calculation of cat, add 'onChange="itm_calc();"'
//		- Names for other Fields (make hidden if not used.
//			- Number of units in order: 'ord_quantity'
//			- Discount: 'ord_discount'
//			- Ship State: 'Shipping_State'
//			- Shipment Sub-Total: 'ord_subtotal'
//			- Sales Tax Box: 'ord_taxadded'
//			- Shipping Charges: 'ord_shipping'
//			- Order Total: 'ord_grandtot'
//

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SETUP DISCOUNT GROUPS by specifying the first 3 columns in this array...
// column 0, "groupname" -- the name of the discount group that items can belong to by setting a hidden input with a "_g" suffix
// column 1, "min" -- minimum number of bottles that must be purchased from THIS GROUP in order for anything to be applied.
// column 2, "pct" -- is the percentage discount to apply to all items in this GROUP, as long as "min" number were purchased.
// cols. 3 and 4 are internal counters used by the program
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var arrDiscounts = new Array();
//                          groupname,          min,    pct,    qty,    sub
arrDiscounts[0] = new Array('grpMain',          12,      .10,   0,      0);
arrDiscounts[1] = new Array('grpMain',   		24,      1,   0,      0);	//need to work on tiered discounts
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SETUP SALES TAX RATE

var SALES_TAX = .0775;

function isEmpty(inputStr) {
	return ((inputStr == '' || inputStr == null) ? true : false);
}

function requireValue(e, msg) {
	if (e.options) {
		// element is a listbox...
		if (isEmpty(e.options[e.selectedIndex].value)) {
			e.focus();
			alert(msg);
			return false;
		}
	}
	else {
		// is NOT a ListBox
		if (isEmpty(e.value)) {
			e.focus();
			e.select();
			alert(msg);
			return false;
		}
	}
	return true;
}

/*function isValidCreditCard(type, ccnum) {
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}
*/
function formChecker(theForm) {

	rv = true;
	if (rv) { rv = requireValue(theForm.Billing_Name, 'Please enter the name to whom you\'d like this order billed.'); }
	if (rv) { rv = requireValue(theForm.Billing_Address, 'Please enter the billing address'); }
	if (rv) { rv = requireValue(theForm.Billing_City, 'Please enter the billing city'); }
	if (rv) { rv = requireValue(theForm.Billing_State, 'Please select the state to which this order will be billed.'); }
	if (rv) { rv = requireValue(theForm.Billing_Zip, 'Please enter the billing zip code.'); }
	if (rv) { rv = requireValue(theForm.Billing_Phone, 'Please enter the billing telephone number.'); }
	if (rv) { rv = requireValue(theForm.Billing_Email, 'Please enter the billing email.'); }
	if (rv) {
		var MethodPmt = document.getElementById("Payment_Method").checked;

		if (MethodPmt == false) {
			} 
	}

	// was anything selected?
	if (rv) {
		var blnSomething = false;
		for (var i=0; i<theForm.length; i++) {
			e=theForm.elements[i];	
			if ( (Left(e.name,4) == 'itm_') && (Right(e.name,2) == '_q') ) {		// is this a line-item subtotal?
				if (e.selectedIndex > 0) {
					blnSomething = true;
				}
			}
			if ( (Left(e.name,4) == 'itm_') && (Right(e.name,2) == '_q') ) {		// is this a line-item subtotal?
				if (e.checked == true) {
					blnSomething = true;
				}
			}
		}
		if (!blnSomething) {
			alert('There was nothing selected to purchase for this shipment.');
			rv = false;
		}
	}
	// note that we need to re-enable our currently disabled item and order input fields so that they, too, get sent with the rest of form!
	if (rv) { enable_order(); }
	return rv;
}

	/*
	function copy_shipping_info () {

var f = document.forms[0];
var found_flag = false;
var arrFields = new Array();
arrFields[0] = new Array('Billing_Name','Shipping_Contact');
arrFields[1] = new Array('Billing_Address','Shipping_Address');
arrFields[2] = new Array('Billing_City','Shipping_City');
arrFields[3] = new Array('Billing_State','Shipping_State');
arrFields[4] = new Array('Billing_Zip','Shipping_Zip');
arrFields[5] = new Array('Billing_Phone','Shipping_Phone');
	

	if (f.elements['same_ship'].checked) {
		for (var i=0; i<arrFields.length; i++) {
			orig = f.elements[arrFields[i][0]];
			copy = f.elements[arrFields[i][1]];
			if (orig.options) {
				// element is a listbox...
				for (var j=0;j<copy.options.length;j++) {
					if (copy.options[j].value) {		
						if (copy.options[j].value == orig.options[orig.selectedIndex].value) {
							copy.selectedIndex = j;
							found_flag = true;
							copy.disabled = true;
							itm_calc();
						}
					}
				}
				if (!found_flag) {
				alert ('I am sorry, but currently we cannot ship to '+orig.options[orig.selectedIndex].value);
				}
			}
			else {
				copy.value = orig.value;
				copy.disabled = true;
			}
		}
	}
	else {
		for (var i=0; i<arrFields.length; i++) {
			copy = f.elements[arrFields[i][1]];
			copy.disabled = false;
		}	
	}

}
	*/
function enable_order() {

// enable all "_x" elements
// enable all "ord_" elements
// enable all "shipping_" elements
// recalc one last time!
	
	var f = document.forms[0];   var e;
	
	for (var i=0; i<f.length; i++) {
		e=f.elements[i];	
		if ( (Left(e.name,4) == 'itm_') && (Right(e.name,2) == '_x') ) {		// is this a line-item subtotal?
			e.disabled = false;
		}
		if ( Left(e.name,4) == 'ord_' ) {										// is this an order summary field?
			e.disabled = false;
		}
		if ( Left(e.name,9) == 'Shipping_' ) {										// is this a shipping field?
			e.disabled = false;
		}
	}
	itm_calc();
}

function fail_change() {
	// manually prevent "disabled" form inputs from being modified in netscape 4...
	alert('The form element you adjusted is a calculated, read-only field that is not meant to be modified.');
	itm_calc();
	return false;
}

function MakeInt(input) {

	var teststring = new String(input);
	var newstring = new String('');

	while (teststring.length > 0) {
		if (Left(teststring,1)!=',') {
			newstring=newstring+Left(teststring,1);
		}
		teststring = Right(teststring,(teststring.length-1));
	}
	return(newstring-0);
}

function moneyFormat(input) {
	var dollars = Math.floor(input);
	var tmp = new String(input);
	for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
		if ( tmp.charAt(decimalAt)=="." )
			break;
	}
	var cents  = '' + Math.round(input * 100);
	cents = cents.substring(cents.length-2, cents.length)
	dollars += ((tmp.charAt(decimalAt+2)=='9')&&(cents=='00'))? 1 : 0;
	if ( cents == '0' )
		cents = '00';
	var remainderstring = new String(dollars);
	dollars='';
	stringlength = remainderstring.length;
	for (var stringpos = 1; stringpos <= stringlength; stringpos++) {
		dollars = Right(remainderstring,1)+dollars;
		if ((stringpos < stringlength) && ((stringpos%3)==0)) dollars = ','+dollars;
		remainderstring = Left(remainderstring,remainderstring.length-1);
	}
	return(dollars + '.' + cents);
}																// end function moneyFormat()

// following three functions mimic VBScript's built-in functions...
function Left(str, ilen) {
	return str.substr(0, ilen);
}
function Right(str, ilen) {
	return str.substr(str.length - ilen);
}
function Mid(str, ipos, ilen) {				// note the different indexing implementation here versus JScript's similar substr function...
	return str.substr(ipos-1, ilen);
}

function calcTax(theshipstate,taxableAmount) {

	// possible values for TAX are (1)unknown, (2)SALES_TAX (see config above), (3)0.00%
	
	if (theshipstate == '') {  
		return '??';
	}
	else
	 if (theshipstate == 'CA') {
		return moneyFormat(SALES_TAX * taxableAmount);
	}
	else {
		return '0.00';
	}
}

function itm_calc() {

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// this function recalculates the individual item costs (qty*price) as well as the order summary.
	// call this function via the onChange event of any/all form inputs which would affect this display.
	// first, each item with a "quantity selector" is iterated through, tallying discounts, subtotals, etc, for each item.
	// After all items have been iterated through (and all counters/subtotals are up-to-date),
	// we then apply final calculations on the whole order such as discounts, shipping, and tax, etc....
	
	// set form object references
	var f = document.forms[0];
	var ord_quantity = f.elements['ord_quantity'];
	var ord_quantity_Flat = f.elements['ord_quantity_Flat'];
	var ord_quantity_Grid = f.elements['ord_quantity_Grid'];
	var ord_subtotal = f.elements['ord_subtotal'];
	var ord_discount = f.elements['ord_discount'];
	var ord_taxadded = f.elements['ord_taxadded'];
	//var ord_shipping = f.elements['ord_shipping'];
	var ord_grandtot = f.elements['ord_grandtot'];
	
	// declare local vars
	var theID;
	var theQuantity, theCost;
	var q, d, t, p, x, g;
	var shipg1, shipg2
	var units = 1;
	
	// what STATE are we SHIPPING to?
	//var theshipstate = f.elements['Shipping_State'].options[f.elements['Shipping_State'].selectedIndex].value + '';

	// intialize order summary
	ord_quantity.value = 0;
	ord_quantity_Flat.value = 0;
	ord_quantity_Grid.value = 0;	
	ord_subtotal.value = 0;
	ord_discount.value = 0;
	ord_taxadded.value = 0;
	//ord_shipping.value = 0;
	ord_grandtot.value = 0;
	shipg1 = 0;
	shipg2 = 0;
	for (var j=0; j<arrDiscounts.length; j++) {
		arrDiscounts[j][3] = 0;			// reset GROUP QUANTITY counter
		arrDiscounts[j][4] = 0;			// reset GROUP SUBTOTAL counter
	}
	//////////////////////////////////////////////////////
	// Change Anual Tasting Program to match state		//
	// **** SPECIFIC TO HAFNER *****
	/*	
	if (theshipstate != '') {
		if (theshipstate == "CA") {
		f.elements['ATPLabel'].value="Within California: $124.00 plus tax / Program";
		f.elements['itm_ATP_q'].disabled = false;
		f.elements['itm_ATP_p'].value='124.00';
		}
		if (theshipstate == 'CO' || theshipstate == 'IA' || theshipstate == 'ID' || theshipstate == 'IL' || theshipstate == 'MO' || theshipstate == 'NE' || theshipstate == 'NM' || theshipstate == 'OR' || theshipstate == 'WA' || theshipstate == 'WI') {
		f.elements['ATPLabel'].value="To CO, IA, ID, IL, MO, NE, NM, OR, WA & WI: $133.00 / Program";
		f.elements['itm_ATP_q'].disabled = false;
		f.elements['itm_ATP_p'].value='133.00';
		}
		if (theshipstate == 'AK' || theshipstate == 'AL' || theshipstate == 'AR' || theshipstate == 'AZ' || theshipstate == 'CT' || theshipstate == 'DC' || theshipstate == 'DE' || theshipstate == 'FL' || theshipstate == 'GA' || theshipstate == 'HI' || theshipstate == 'IN' || theshipstate == 'KS' || theshipstate == 'KY' || theshipstate == 'LA' || theshipstate == 'MA' || theshipstate == 'MD' || theshipstate == 'ME' || theshipstate == 'MI' || theshipstate == 'MN' || theshipstate == 'MS' || theshipstate == 'MT' || theshipstate == 'NC' || theshipstate == 'ND' || theshipstate == 'NH' || theshipstate == 'NJ' || theshipstate == 'NV' || theshipstate == 'NY' || theshipstate == 'OH' || theshipstate == 'OK' || theshipstate == 'PA' || theshipstate == 'RI' || theshipstate == 'SC' || theshipstate == 'SD' || theshipstate == 'TN' || theshipstate == 'TX' || theshipstate == 'UT' || theshipstate == 'VA' || theshipstate == 'VT' || theshipstate == 'WV' || theshipstate == 'WY' ) {
		f.elements['ATPLabel'].value="To many other states: $154.00 / Program";
		f.elements['itm_ATP_q'].disabled = false;
		f.elements['itm_ATP_p'].value='154.00';
		}
		//f.elements['itm_ATP_d'].value = f.elements['ATPLabel'].value;
		f.elements['itm_ATP_d'].value = 'Annual Tasting Program for 2005';
		
	}
	*/
	//////////////////////////////////////////////////////
	// Change Price of each item based on quantity - 01CS0		//
	// **** SPECIFIC TO HAFNER *****
	/*	
	if (f.elements['itm_01CS0_q'].value < 12) f.elements['itm_01CS0_p'].value = 32.00;
	if ((f.elements['itm_01CS0_q'].value >= 12)&&(f.elements['itm_01CS0_q'].value < 24)) f.elements['itm_01CS0_p'].value = 29.00;
	if (f.elements['itm_01CS0_q'].value >= 24) f.elements['itm_01CS0_p'].value = 26.00;
	*/
	//////////////////////////////////////////////////////
	// Change Price of each item based on quantity		//
	// **** SPECIFIC TO HAFNER *****	
	/*
	if (f.elements['itm_01CHR2_q'].value < 12) f.elements['itm_01CHR2_p'].value = 25.00;
	if ((f.elements['itm_01CHR2_q'].value >= 12)&&(f.elements['itm_01CHR2_q'].value < 24)) f.elements['itm_01CHR2_p'].value = 23.00;
	if (f.elements['itm_01CHR2_q'].value >= 24) f.elements['itm_01CHR2_p'].value = 21.00;	
	*/
	////////////////////////////////////////////////////////
	// PER-ITEM CALCULATIONS
	// iterate through all form elements, looking for item ("itm_") quantity selector ("_q") elements only
	// calculate, update, and tally up item costs, quantities, and discounts
	
	for (i=0; i<f.length; i++) {
		q=f.elements[i];	
		if ( (Left(q.name,4) == 'itm_') && (Right(q.name,2) == '_q') ) {		// only proceed if this is an ITEM QUANTITY selector

			// identify and set references to related form elements for this "ITEM ID"
			theID = Mid(q.name, 5, (q.name.length-6));		// the "middle" of the form field name, identifying the item
			d = f.elements['itm_' + theID + '_d'];			// the description. not used in calculations at all, just for testing.
			s = f.elements['itm_' + theID + '_s'];			// Flag to indicate an 'other' item.
			p = f.elements['itm_' + theID + '_p'];			// the price
			x = f.elements['itm_' + theID + '_x'];			// the item-subtotal "tally" cost, i.e., Quantity * Price
			g = f.elements['itm_' + theID + '_g'];			// the discount group. NOTE this field is optional
			u = f.elements['itm_' + theID + '_u'];			// the number of units per selection. ie: 1 case = 12 bottles. Set whatever_u = 12. Defaults to 1.
    		// simple programmer's error checking?
			if (!d) { alert('Script Error: Description field not found for item \'' + theID + '\''); return false; }
			if (!p) { alert('Script Error: Price field not found for item \'' + theID + '\''); return false; }
			if (!x) { alert('Script Error: Item Subtotal \'x\' field not found for item \'' + theID + '\''); return false; }
			if (!s) { alert('Script Error: Shipping Type \'s\' field not found for item \'' + theID + '\''); return false; }

			if (u) units = u.value;
			// note we rely on the "selectedIndex" of the quantity selector to be the same as its value, i.e., idx[0] == 0; idx[1] == 1; etc...	
			if (q.options) {			
				theQuantity = q.selectedIndex*units;  // note we rely on the "selectedIndex" of the quantity selector to be the same as its value, i.e., idx[0] == 0; idx[1] == 1; etc...
			}
			else {
				if (q.checked==true) theQuantity = units;
				else theQuantity = 0;
			}
			theCost = p.value * theQuantity;
			// set line-item subtotal (the cost multiplier "_x" field) based on (quantity * price)...
			if (theCost == 0)
				x.value = '';
			else
				x.value = moneyFormat(theCost);			
			// update and increment these order summaries as we go
			ord_quantity.value = (ord_quantity.value - 0) + (theQuantity-0);			// the "minus zero" casts the value from a string to a number.
			if ((s.value)=='Flat')
				ord_quantity_Flat.value = (ord_quantity_Flat.value - 0) + (theQuantity-0);
			if ((s.value)=='Grid')
				ord_quantity_Grid.value = (ord_quantity_Grid.value - 0) + (theQuantity-0);
			ord_subtotal.value = moneyFormat(MakeInt(ord_subtotal.value) + theCost);
		
			// increment the arrDiscount's GROUP QUANTITY COUNTERS that this item belongs to, if any...
			// currently, an item is only able to belong to one discount GROUP at a time. this may or may not need to change...
			if (g) {												// does the "group" hidden field exist? (it is optional.)
				for (var j=0; j<arrDiscounts.length; j++) {			// then loop through defined discount groups
					if (arrDiscounts[j][0] == g.value) {			// is the array group the same as the item group?
						arrDiscounts[j][3] = arrDiscounts[j][3] + (MakeInt(theQuantity));		// update quantity counter in this discount group
						arrDiscounts[j][4] = arrDiscounts[j][4] + (MakeInt(theCost));			// update subtotal counter in this discount group
					}
				}
			}										// end if -- end if the discount "group" field exists in the form for this item

			/////////////////////////////////////////////////////////////////////////////////////////////
			// we are finished with calculations pertaining to this individual quantity selector.
			/////////////////////////////////////////////////////////////////////////////////////////////

		}											// end if -- end if this form element is a quantity selector
	}												// end for -- end looping through all form elements
	
	

	///////////////////////////////////////////////////////////////////////////////////////////////////
	// FINAL ORDER CALCULATIONS
	// all items have been iterated through and parsed, so all relevant counters should be up-to-date.
	// calculate remaining order summary items now, such as shipping, discounts, and tax...
	//
	// CALCULATE DISCOUNT
	for (d=0; d<arrDiscounts.length; d++) {											// loop through DISCOUNT GROUPS
		// does this discount meet minimum requirements to be applied?
		if ( arrDiscounts[d][3]>0 && arrDiscounts[d][3]>=arrDiscounts[d][1] ) {		// were enough items in this GROUP ordered (the "minimum") to apply for this discount?
			// apply discount to items in this GROUP... NOTE THAT WE SUBTRACT!! the DISCOUNT will be a negative number.
			ord_discount.value = (ord_discount.value - 0) - (arrDiscounts[d][2] * arrDiscounts[d][4]);
		}
	}																				//  end for -- done looping through arrDiscounts
	ord_discount.value = moneyFormat(ord_discount.value);							// make it pretty
	
	// CALCULATE TAX			-- based on STATE!
	// calcTax(state,taxableAmount)
	//ord_taxadded.value = calcTax(theshipstate,(MakeInt(ord_subtotal.value)+MakeInt(ord_discount.value)));
	ord_taxadded.value = 0;
	
	// CALCULATE SHIPPING		-- based on STATE!
	// calcshipping(state, quanity)
//	if (theshipstate == '') {
//		ord_shipping.value = "??";
//		}
//	else {
//	shipg1=calcShippingFlat(theshipstate, MakeInt(ord_quantity_Flat.value));
//	shipg2=calcShippingGrid(theshipstate, MakeInt(ord_quantity_Grid.value));
//	ord_shipping.value = moneyFormat(MakeInt(shipg1)+MakeInt(shipg2));
	shipg1=0;
	shipg2=0;
	//ord_shipping.value = 0;
//	}	
	
	// CALCULATE GRAND TOTAL
	// we can supply a final figure ONLY if we already have both the TAX and SHIPPING values... otherwise append '??' to the field
	ord_grandtot.value = moneyFormat(MakeInt(ord_subtotal.value) + MakeInt(ord_discount.value));
	
	if (ord_taxadded.value != '??' ) {
		// add in shipping and tax
		ord_grandtot.value = moneyFormat(MakeInt(ord_grandtot.value) + MakeInt(ord_taxadded.value) );
	}
	else {
		// don't add in shipping and tax
		ord_grandtot.value = ord_grandtot.value + ' ??';
	}
	
	
	///////////////////////////////////////////////////////////////////////////////////////////////////
	// ALL DONE!
	///////////////////////////////////////////////////////////////////////////////////////////////////

	
}																				// end function itm_calc()




function calcShippingFlat(theshipstate,theQuantity) {

	// Shipping charges are based first upon the destination state (theshipstate), then upon the quantity
	// of items purchased (theQuantity)... If theshipstate is not set, '??' is returned.
	//
	// NOT SETUP FOR WILLIAMSON WINES

	var theShipping = 0;

	if (theQuantity == 0) {
		return moneyFormat(0);
	}

		//  1  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if (theshipstate == 'CA') {

			theShipping = theShipping + 0.00;			 				// $0/item flat rate
		}
		//  2  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
		if (theshipstate == 'CO' || theshipstate == 'IA' || theshipstate == 'ID' || theshipstate == 'IL' || theshipstate == 'MO' || theshipstate == 'NE' || theshipstate == 'NM' || theshipstate == 'OR' || theshipstate == 'WA' || theshipstate == 'WI') {						
			theShipping = theShipping + (theQuantity*3.00);				// $3/item flat rate
					
		}	
		//  3  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if (theshipstate == 'AK' || theshipstate == 'AL' || theshipstate == 'AR' || theshipstate == 'AZ' || theshipstate == 'CT' || theshipstate == 'DC' || theshipstate == 'DE' || theshipstate == 'FL' || theshipstate == 'GA' || theshipstate == 'HI' || theshipstate == 'IN' || theshipstate == 'KS' || theshipstate == 'KY' || theshipstate == 'LA' || theshipstate == 'MA' || theshipstate == 'MD' || theshipstate == 'ME' || theshipstate == 'MI' || theshipstate == 'MN' || theshipstate == 'MS' || theshipstate == 'MT' || theshipstate == 'NC' || theshipstate == 'ND' || theshipstate == 'NH' || theshipstate == 'NJ' || theshipstate == 'NV' || theshipstate == 'NY' || theshipstate == 'OH' || theshipstate == 'OK' || theshipstate == 'PA' || theshipstate == 'RI' || theshipstate == 'SC' || theshipstate == 'SD' || theshipstate == 'TN' || theshipstate == 'TX' || theshipstate == 'UT' || theshipstate == 'VA' || theshipstate == 'VT' || theshipstate == 'WV' || theshipstate == 'WY' ) {
		
			theShipping = theShipping + (theQuantity*10.00);				// $10/item flat rate
					
		}		

		return (theShipping);						// return what we've calculated in a pretty money format
	
}																// end function calcShipping1()

function calcShippingGrid(theshipstate,theQuantity) {

	// Shipping charges are based first upon the destination state (theshipstate), then upon the quantity
	// of items purchased (theQuantity)... If theshipstate is not set, '??' is returned.

	var theShipping = 0;

	if (theQuantity == 0) {
		return moneyFormat(0);
	}
		//  1  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//		if (theshipstate == 'CA' || theshipstate == 'CO' || theshipstate == 'HI' || theshipstate == 'IA' || theshipstate == 'ID' || theshipstate == 'IL' || theshipstate == 'MN' || theshipstate == 'MO' || theshipstate == 'NE' || theshipstate == 'NH' || theshipstate == 'NM' || theshipstate == 'NV' || theshipstate == 'OR' || theshipstate == 'WA' || theshipstate == 'WI' || theshipstate == 'WV') {

/*
			if (theQuantity >= 60) {
				theShipping = theShipping + 0;				// No charge on shipping >= 5 cases.
			}
			else
*/		
			if (theQuantity >= 36) {
				while (theQuantity > 12) {							// GT, not GTOET, to not let quantity hit 0
					theShipping = theShipping + 22.00;
					theQuantity = theQuantity - 12;
				}
				if (theQuantity > 6) {
					theShipping = theShipping + 22.00;					
				}
				else {
					if (theQuantity > 0) {
						theShipping = theShipping + 16.00;
					}
				}
			}
			else if (theQuantity >= 12) {
				while (theQuantity > 12) {							// GT, not GTOET, to not let quantity hit 0
					theShipping = theShipping + 29.00;
					theQuantity = theQuantity - 12;
				}
				if (theQuantity > 6) {
					theShipping = theShipping + 29.00;						
				}
				else {
					if (theQuantity > 0) {
						theShipping = theShipping + 16.00;
					}
				}			
			}
			else {
				if (theQuantity > 6) {
					theShipping = theShipping + 29.00;
				}
				else {
					if (theQuantity > 0) {
						theShipping = theShipping + 16.00;
					}
				}					
			}			
//		}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//	else {														// used when shipping over x is free
		return moneyFormat(theShipping);						// return what we've calculated in a pretty money format
//	}															// used when shipping over x is free
	
}																// end function calcShipping3()


