//09/23/03	
//HomeBrewery Checkout & Shopping Cart - Copied from mycheckout.js:
//alert("homebrewerycheckout.js");
/*
Control names:
T1 Name
T2 
T3 Address
T4 City
T5, T5Other State (ddl, textbox)
T6 Zip
T7 Phone
T8 Email
T9M, T9Y CC Expiration Date 
T10 CC#
T11 Card Holder name
T12 Country (ddl)
D1 Payment Method (ddl)
D36 Shipping Method (ddl)
C1 Product (checkbox)
C2 Outside US shipping (checkbox)
*/

///////////////////////////////////////////
//Set up variables:
showID=true;
///////////////////////////////////////////

//Shopping Cart:
var itemArray="";
var myItemID="0";
var itemID="0";
var itemDesc="itemDescription";
var itemQty="2";
var itemPrice="$0.00";
var itemTotal ="$00.00";
var subTotal="$0";
var tax = "$0";
var total="$0";

//Checkout:
var stateTaxing="MO";
var stateTaxRate=6.6;			//Wisconsin - looked it up
var zipOrigin="53189";			//Waukesha

//Baker, Howland and Jarvis Islands not included because of the commas!
var USTerritories="GUAM,PUERTORICO,USVIRGINISLANDS,AMERICANSAMOA,NORTHERNMARIANAISLANDS,MIDWAYISLANDS,WAKEISLAND,JOHNSTONATOLL,KINGMANREEF,NAVASSAISLAND,PALMYRAATOLL";
isUSTerritory=false;

//var myForm=document.Form1;  //Putting this here doesn't work for onLoad(). And there is some other problem, somewhere. ABDFI!

var cntItems=0;
var totPrice=0;
var totWeight=0;
var totQty=0;
//var shipping=0;
var orderNumber=0;				// See fnGetOrderNumber()
var indexUSA=0;
var indexCanada=0;
PayByCC=true;
var orderMethod=0;

var merchantFax="111-111-1111";
var merchantCheckPayable="Some Company Name";
var merchantMailAddress="P.O. Box 123 Somewhere, XX 12345";

//Shipping variables:
var wPackagingSmall=6;			//oz
var wPackagingLarge=10;			//oz
var wPackageSmallLimit=6;			//oz Greater weight use wPackagingLarge
var wPackagingUse=0;				//Either small or large depending on weight
var weightToShip=0;					//Weight of products + packaging in POUNDSSSSSS


function fnOnLoad()
{
	//alert("fnOnload mycheckout");
	fnGetCookie("ordered");
	BuildShoppingCart();
	
	//Get index values for Canada, USA from country ddl. In case someone adds, removes options!
	var myForm=document.Form1;
	//alert("on Load count = " + ddl.options.length);
	//myForm.T12.selectedIndex=27;		//Canada
	//myForm.T12.selectedIndex=169;		//USA
	for (i=0;i<myForm.T12.options.length;i++)
	{
		var country=myForm.T12.options[i].value;
		if (country=="Canada") { indexCanada=i;}
		if (country=="USA") { indexUSA=i;}
	}	
	//alert("indexCanada = " + indexCanada);
	//alert("indexUSA = " + indexUSA);

	document.getElementById("MerchantFax").innerHTML = "<font size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;to " + merchantFax;
	document.getElementById("MerchantCheckPayable").innerHTML = "<font size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;card payment or check or money order payable to <i>" + merchantCheckPayable + "</i>.";
	document.getElementById("MerchantMailAddress").innerHTML = "<font size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mail to <i>" + merchantMailAddress + ".</i>";
	
	//Need to put try/catch across this:
	var sTax="";
	if (stateTaxing!="")
	{
		sTax= "&nbsp;State Tax for " + stateTaxing + " (" + stateTaxRate + "%)"
	}
	document.getElementById("STax").innerHTML = sTax;
}


////////////////////////////////////////////////////////////////////////
///////////////////////// Shopping Cart //////////////////////////////
////////////////////////////////////////////////////////////////////////
function BuildShoppingCart()
{
	//alert("BuildShoppingCart itemArray = " + itemArray);
	var itemID="0";
	var itemDesc="";
	var itemWeight="0";
	var itemPrice="$0.00";
	var itemQty="0";
	
	var totItemPrice=0;
	var totWeight=0;
	totQty=0;
	var subTotalPrice=0;
	
	//Loop thru and see if the totQty>0:
	for (var i=0;i<itemArray.length/5;i++)
	{
		itemQty=itemArray[5*i+4];
		if (isNaN(parseInt(itemQty)))
		{
			//!!!!!
		}
		else
		{
			totQty+=parseInt(itemQty);
		}
	}
	//alert("totQty = " + totQty);
	////////////////////////////////////////
	//Check for empty Shopping Cart (look at cookie 'ordered'):
	if ((totQty==0) || (isNaN(parseInt(totQty))) ) 
	{
		//DON'T BREAK THESE LINES!
		document.getElementById("ShoppingCart").innerHTML= "<table><tr><td><b>Shopping Cart is empty!</b></td></tr><tr><td align='center'><INPUT id='Button1' type='button' value='Continue Shopping' name='Button1' onclick='history.go(-1);'></td></tr></table>";
		document.getElementById("TotalWeight").innerHTML="0";
		document.getElementById("TotalQty").innerHTML="0";
		document.Form1.B1.disabled=true;
		return;
	}
	document.Form1.B1.disabled=false;
	////////////////////////////////////////

	var header="<TABLE width='100%' border='1'><!------------- Headings -----------><tr bgColor='green'>";
	header+= ((showID==true)?"<td width=8%><font color='white' size='2'><b>ID</b></font></td>":"");
	header+="<td><font color='white' size='2'><b>Description</b></td>";
	header+="<td width='12%' align='center'><font color='white' size='2'><b>Price</b></font></td>";
	header+="<td width='7%' align='center'><font color='white' size='2'><b>Qty</b></font></td>";
	header+="<td width='15%' align='center'><font color='white' size='2'><b>Total</b></font></td>";
	header+="</tr><!------------- Items ------------>";
	//alert(header);
	
	var footer="<!---------- Subtotal ------------><tr bgColor='linen'>";
	//<FORM><INPUT TYPE="Button" VALUE="Back" onClick="history.go(-1)"></FORM>
	//footer+="<td colSpan='" + ((showID==true)?2:1) + "' align='center'><INPUT id='Button1' type='button' value='Continue Shopping' name='Button1' onclick='javascript:self.close();'>";
	footer+="<td colSpan='" + ((showID==true)?2:1) + "' align='center'><INPUT id='Button1' type='button' value='Continue Shopping' name='Button1' onClick='history.go(-1);'>";
	footer+="<td colSpan='2'><font size='2'><b>&nbsp;Subtotal</b></font></td>";
	footer+="<td align='right'><INPUT id='SubTotalPrice' type='text' size='10'  readonly class='NoBorderR' name='SubTotalPrice'></td>";
	//alert(footer);

	footer+="</TABLE>";
	
	lines="";
	//alert("itemArray = " + itemArray);

	for (var i=0;i<itemArray.length/5;i++)
	{
		itemQty=itemArray[5*i+4];
		if (itemQty>0)
		{
			itemID=itemArray[5*i+0];
			itemDesc=itemArray[5*i+1].substr(0,50);  //a bit of a guess!
			//itemDesc=fnReplace(itemDesc,"<B>","");
			//itemDesc=fnReplace(itemDesc,"</B>","");
			//itemDesc=fnTrim(itemDesc);
			//alert("itemDesc = " + itemDesc);
			itemWeight=itemArray[5*i+2];
			itemPrice=itemArray[5*i+3];
			
			var line="<!------------- Line Item  ------------><tr bgColor='Gainsboro'>";
			
			line+=((showID==true)?"<td><INPUT id='ItemID_" + i + "' readonly class='NoBorder' size='5' name='ItemID_" + i + "' value= '" + itemID +"'></td>":"");
			line+="<td><INPUT id='ItemDesc_" + i + "' readonly class='NoBorder' size='40' name='ItemDesc_" + i + "' value= '" + itemDesc +"'></td>";		
			line+="<td align='right'><INPUT id='ItemPrice_" + i + "' readonly class='NoBorderR' size=6 name=ItemPrice_" + i + "' value= '" + itemPrice +"'></td>";
			line+="<td align='right'><INPUT id='" + i + "' type='text' size='2' class='FontFamilySize' name='ItemQty_" + i + "' onkeyup='UpdateArray(this.id);'></td>";
			line+="<td align='right'><INPUT id='ItemTotal_" + i + "' type='text' readonly class='NoBorderR' size=10 name='ItemTotal_" + i + "'></td>";
			line+="</tr>";
			//alert(line);
			lines+=line;
		}
	}
	
	
	//Insert values:
	var totalItems=0;
	document.getElementById("ShoppingCart").innerHTML= header + lines + footer + "<CENTER><EM><FONT face='Verdana' size='2'>Shipping, Tax calculated below</FONT></EM></CENTER><br>";
	//alert("itemArray.length/5 = " + itemArray.length/5);
	for (var i=0;i<itemArray.length/5;i++)
	{
		itemQty=itemArray[5*i+4];		
		//alert("itemQty = " + itemQty);
		if (itemQty>0)
		{
			itemWeight=itemArray[5*i+2];	
			itemPrice=fnConvertToDecimal(itemArray[5*i+3]);
			itemQty=itemArray[5*i+4];												

			totWeight+=fnMyRound(itemWeight * itemQty,2);
			totItemPrice=fnMyRound(itemPrice * itemQty,2);
			totQty+=parseInt(itemQty);

			//document.getElementById("itemWeight_" + i).innerHTML=itemWeight;
			//alert("itemQty " + i + " = " + itemQty);	
			document.getElementById(i).value=itemQty;

			document.getElementById("ItemTotal_" + i).value=fnConvertToCurrency(totItemPrice);
			subTotalPrice+=totItemPrice;
		}		
	}
	//alert("totWeight = " + totWeight + "\nsubTotalPrice = " + subTotalPrice + "\ntotQty = " + totQty);
	document.getElementById("TotalWeight").innerHTML=totWeight;
	document.getElementById("TotalQty").innerHTML=totQty;
	document.getElementById("SubTotalPrice").value=fnConvertToCurrency(subTotalPrice);
	/////////////////////////
	fnCalcShipTaxTotal();
	/////////////////////////

}


function fnGetCookie(name)
{
	//Same as fnGetCookie() in a1petsupply.js except array is itemArray instead of aryCookie()
	//alert("fnGetCookie name = " + name);
	var myCookie = " " + document.cookie + ";";
	var searchName= " " + name + "=";
	//alert("Cookie name = " + name + "\nsearchName = " + searchName);
	var startOfCookie=myCookie.indexOf(searchName);
	var endOfCookie;
	//alert("startOfCookie = " + startOfCookie);
	if (startOfCookie > -1)
	{
		startOfCookie += searchName.length;
		endOfCookie=myCookie.indexOf(";",startOfCookie);
		result=unescape(myCookie.substring(startOfCookie,endOfCookie));
		//alert("result = " + result);
		
		//Turn sCookie into Array:
		itemArray=result.split("~");						
	}
	//alert("itemArray fnGetCookie() = " + itemArray);	
}


function NSRemoveTags(val)
{
	//Fix for Netscape only. In some cases, innerHTML returns <font>123.45</font>
	//Happens when retrieving totWeight and totQty. So ....
	var pos1=val.indexOf(">",0);
	var pos2=val.indexOf("</",pos1);
	//alert("pos1 = " + pos1 + "\npos2 = " + pos2);
	var Return=val.substring(pos1+1,pos2);
	//alert("Return = " + Return);
	return Return;
}

function UpdateArray(line)
{
	alert("UpdateArray line = " + line);
	alert("document.getElementById(" + line + ").value = " + document.getElementById(line).value);
	itemArray[5*line +4]= document.getElementById(line).value;
	
	//////////////////////////////////
	BuildShoppingCart();
	fnSetCookie("ordered");
	/////////////////////////////////
}


function fnSetCookie(name)
{
	//Same as a1petsupply.fnSetCookie() except array name is itemArray instead of aryCookie:
	//alert("fnSetCookie name = " + name + ", itemArray = " + itemArray);
	//alert("mycheckout.fnSetCookie  itemArray = " +  itemArray);
	//1. Turn array value into string sCookie:
	sCookie="";
	//alert("fnSetCookie itemArray.length = " + itemArray.length);
	for (var i=0;i<itemArray.length;i++)
	{
		//alert("aryCookie[" + i + "]=" + itemArray[i]);
		sCookie += ((sCookie=="")?"":"~") + itemArray[i];
		//alert("sCookie = " + sCookie);
	}
	//alert("sCookie = " + sCookie);
	//alert("sCookie value to store in cookie " + name + "= " + sCookie);
	if (itemArray.length>0)
	{
		//alert(name + "=" + escape(sCookie));
		document.cookie = name + "=" + escape(sCookie);
	}
}


/////////////////////////////////////////////////////////////////////////////
///////////////////////////////  Check Out  ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////
function fnCalcShipping()
{
	shipping=0;
	//alert("fnCalcShipping()");
	if (document.Form1.PayShipping.selectedIndex==0)
	{
		var index=document.Form1.D36.selectedIndex;
		//alert("index 1 = " + index);
		var shipper=document.Form1.D36.options[index].text;
		//alert("shipper 2 = " + shipper);
		//var shipping=10.01;
		shipper=shipper.replace(/ /g,"").toUpperCase();    //Remove white spaces: (RegExp)
		//alert("shipper (fnCalcShipping) = " + shipper);
		var cntItems=document.getElementById("TotalWeight").innerHTML;
		var totWeight=document.getElementById("TotalQty").innerHTML;
		var browser=navigator.appName;
		//alert("browser = " + browser);
		if (browser=="Netscape")
		{
			cntItems=NSRemoveTags(cntItems);
			totWeight=NSRemoveTags(totWeight);
		}
		//alert("cntItems shipping xxx = " + cntItems);
		//alert("shipping totWeight shipping xxx = " + totWeight);
		//alert("shipper (before call) = " + shipper);
		if (totWeight>0)
		{
			if (shipper.substr(0,4)=="USPS") {shipping=fnCalcShippingUSPS(cntItems,totWeight); }
			//Use Fedex calcs for UPS - for now:
			if (shipper.substr(0,3)=="UPS") {shipping=fnCalcShippingFedex(shipper, cntItems,totWeight); }
			if (shipper.substr(0,5)=="FEDEX") {shipping=fnCalcShippingFedex(shipper, cntItems,totWeight); }
		}
	}
	
	//alert("shipping end fnCalcShipping()) = " + shipping);
	return shipping;
}


function fnCalcShippingUPS(shipper, cntItems,totWeight)
{	
	alert("shipper fnCalcShippingUPS = " + shipper)
	return 0;
}


function fnCalcShippingFedex(shipper, cntItems, totWeight)
{
	//alert("shipper fnCalcShippingFedex = " + shipper)
	var shipping=0;
	var wPackagingUse=(cntItems>5)?wPackagingLarge:wPackagingSmall;
	//alert("wPackagingUse = " + wPackagingUse);
	//alert("weightToShip oz = " + (parseFloat(totWeight)+wPackagingUse));
	var weightToShip=0.0625*(parseFloat(totWeight)+wPackagingUse);                     //lb
	//alert("weightToShip lb = " + weightToShip);
	//var baseIndex=(weightToShip<10)?0:parseInt(weightToShip/10);
	var baseIndex=parseInt(weightToShip/10);
	//alert("baseIndex = " + baseIndex);
	
	var zip=document.Form1.T6.value;
	//alert("zip = " + zip);
	var indexShippingMethod = document.Form1.D36.selectedIndex;
	var indexCountry = document.Form1.T12.selectedIndex;
	if ((indexShippingMethod==0) || ((indexCountry!=indexUSA) && (indexCountry!=indexCanada)) || (zip==""))
	{	
		//alert("USA, Canada only for now")
		return shipping;
	}
	
	////////////////////////////////////////////////////
	var fedexZone=fnGetFedexZone(zip);
	//alert("fedexZone = " + fedexZone);
	if (fedexZone=="NA") 
	{
		alert("Shipping cannot be calculated: No shipping zone for " + zip);
		//What to do?
		return shipping;
	}		
	///////////////////////////////////////////////////
		
	var FedexZone=new Array();

	if (shipper.indexOf("GROUND",0)>0)
	{
		//UPS Ground Jan 2003 from Fedex website.
		//alert("Fedex Ground");
		switch (fedexZone)
		{
			case 2:	
				var FedexGroundZone2= new Array("3.39","4.56","5.75","7.21","8.58","9.62","10.53","11.40","33.39","38.31","42.84","46.81");
				FedexZone=FedexGroundZone2;
				break;
			case 3:
				var FedexGroundZone3= new Array("3.50","4.79","6.53","8.41","10.34","12.09","13.23","14.23","35.38","40.15","44.44","48.44");
				FedexZone=FedexGroundZone3;
				break;
			case 4:
				var FedexGroundZone4= new Array("3.74","5.29","6.81","9.23","11.67","13.83","15.42","16.56","35.82","40.61","44.89","48.99");
				FedexZone=FedexGroundZone4;
				break;
			case 5:
				var FedexGroundZone5= new Array("3.82","5.73","7.96","10.99","14.09","17.04","19.14","20.44","37.03","41.58","46.14","50.09");
				FedexZone=FedexGroundZone5;
				break;
			case 6:
				var FedexGroundZone6= new Array("4.02","6.28","10.03","14.23","18.20","21.43","23.93","25.56","39.81","44.41","48.91","53.20");
				FedexZone=FedexGroundZone6;
				break;
			case 7:
				var FedexGroundZone7= new Array("4.07","7.07","12.06","16.90","22.01","26.72","29.00","30.70","41.23","45.83","50.36","54.86");
				FedexZone=FedexGroundZone7;
				break;
			case 8:
				var FedexGroundZone8= new Array("4.18","8.04","14.18","20.31","26.37","31.73","34.58","36.88","44.05","48.58","53.18","57.68");
				FedexZone=FedexGroundZone8;
				break;
			case 9:
				var FedexGroundZone9= new Array("12.84","26.69","41.48","55.76","69.11","83.56","97.58","114.07","129.03","144.33","158.87","174.08");
				FedexZone=FedexGroundZone9;
				break;
			case 10:
				var FedexGroundZone10= new Array("12.84","26.69","41.48","55.76","69.11","83.56","97.58","114.07","129.03","144.33","158.87","174.08");
				FedexZone=FedexGroundZone10;
				break;
			case 11:
				var FedexGroundZone11= new Array("3.43","4.08","4.58","5.04","5.51","6.36","7.56","8.76","28.71","33.36","36.92","40.37");
				FedexZone=FedexGroundZone11;
				break;
			case 12:
				var FedexGroundZone12= new Array("12.84","26.69","41.48","55.76","69.11","83.56","97.58","114.07","129.03","144.33","158.87","174.08");
				FedexZone=FedexGroundZone12;
				break;
			case 13:
				var FedexGroundZone13= new Array("8.05","13.80","19.80","25.95","31.75","37.25","42.25","45.85","49.05","52.05","55.05","60.25");
				FedexZone=FedexGroundZone13;
				break;
			case 14:
				var FedexGroundZone14= new Array("13.00","19.70","27.95","36.75","44.80","52.30","57.80","63.30","69.80","78.50","87.50","98.25");
				FedexZone=FedexGroundZone14;
				break;
			case 15:
				var FedexGroundZone15= new Array("5.58","14.63","24.51","33.11","40.29","46.73","51.75","56.09","61.11","66.62","72.11","77.62");
				FedexZone=FedexGroundZone15;
				break;
			case 16:
				var FedexGroundZone16= new Array("5.74","15.50","26.81","37.53","45.37","53.27","59.67","64.86","70.05","75.23","80.42","85.61");
				FedexZone=FedexGroundZone16;
				break;
			case 17:
				var FedexGroundZone17= new Array("3.39","4.56","5.75","7.21","8.58","9.62","10.53","11.40","33.39","38.31","42.84","46.81");
				FedexZone=FedexGroundZone17;
				break;
			case 18:
				var FedexGroundZone18= new Array("5.64","14.55","23.42","31.87","38.78","44.98","49.81","53.98","58.82","64.12","69.40","74.71");
				FedexZone=FedexGroundZone18;
				break;
			case 19:
				var FedexGroundZone19= new Array("5.80","15.44","26.32","36.12","43.67","51.27","57.43","62.43","67.42","72.41","77.40","82.40");
				FedexZone=FedexGroundZone19;
				break;
		}
	}
	else
	{
		//alert("2ndDay");
		switch (fedexZone)
		{
			case 2:
				var Fedex2ndDayZone2= new Array("8.00","11.30","17.00","22.80","28.50","34.30","39.80","46.00","52.30","58.30","65.00","71.50");
				FedexZone=Fedex2ndDayZone2;
				break;
			case 3:
				var Fedex2ndDayZone3= new Array("8.30","13.30","19.80","26.80","33.80","40.80","47.30","54.50","61.80","69.00","76.00","83.60");
				FedexZone=Fedex2ndDayZone3;
				break;
			case 4:
				var Fedex2ndDayZone4= new Array("8.50","16.50","25.30","34.00","43.00","51.00","59.80","68.50","78.30","87.00","96.00","105.60");
				FedexZone=Fedex2ndDayZone4;
				break;
			case 5:
				var Fedex2ndDayZone5= new Array("8.90","20.40","32.50","44.10","55.50","65.30","76.90","89.80","103.00","115.10","127.00","139.70");
				FedexZone=Fedex2ndDayZone5;
				break;
			case 6:
				var Fedex2ndDayZone6= new Array("9.60","25.80","42.90","58.80","75.60","91.10","106.50","123.30","140.00","156.30","173.00","190.30");
				FedexZone=Fedex2ndDayZone6;
				break;
			case 7:
				var Fedex2ndDayZone7= new Array("10.10","27.40","45.50","62.60","80.90","98.50","115.60","133.90","151.80","169.10","186.00","204.60");
				FedexZone=Fedex2ndDayZone7;
				break;
			case 8:
				var Fedex2ndDayZone8= new Array("10.40","28.50","46.60","65.00","83.30","100.90","117.90","137.70","156.30","174.70","193.00","212.30");
				FedexZone=Fedex2ndDayZone8;
				break;
			case 9:
				var Fedex2ndDayZone9= new Array("16.60","32.40","47.40","66.10","84.60","102.50","119.80","139.90","158.80","177.50","197.00","216.70");
				FedexZone=Fedex2ndDayZone9;
				break;
			case 10:
				var Fedex2ndDayZone10= new Array("22.80","34.20","51.30","71.50","91.70","111.90","132.60","153.80","175.30","196.60","218.00","239.80");
				FedexZone=Fedex2ndDayZone10;
				break;
			case 11:
				var Fedex2ndDayZone11= new Array("10.60","24.60","35.50","47.90","59.30","71.20","82.60","95.10","107.70","120.40","133.00","146.30");
				FedexZone=Fedex2ndDayZone11;
				break;
		}	
	}
	
	//alert("FedexZone.length = " + FedexZone.length);
	//alert("FedexZone[" + baseIndex + "] = " + FedexZone[baseIndex]);
	//alert("FedexZone[" + (baseIndex +1) + "] = " + FedexZone[(baseIndex+1)]);
	var baseCharge=parseFloat(FedexZone[baseIndex]);
	var topCharge=parseFloat(FedexZone[(baseIndex+1)]);
	shipping=baseCharge + (topCharge-baseCharge)/10*(weightToShip-(baseIndex*10));
	//alert("Fedex Shipping = " + shipping);
		
	return shipping;
}


function fnCalcShippingUSPS(cntItems, totWeight)
{
	//alert("fnCalcShippingUSPS");
	
	///////////////////////////////////////////////////////////////////////
	/*
	Basis for calculating shipping: USPS info 9/27/03
	Wgt (lb)									1			2			3			4		Rate/lb calc'd
	US PP**					    		  3.75      4.49	   	6.32		 7.87			1.34
	US Priority**				 		  3.85		  5.75		 8.55		10.35			2.17
	Canada Airmail Parcel Post		13.25		13.25		14.25		15.50			0.75
	England Airmail Parcel Post		16.00		20.00		24.00		28.00			4.00
	Australia Airmail Parcel Post	14.50		18.75		23.25		26.75		
	** Figures for 6 x 6 x 6 package CA to FL.
	Averaged rate/lb over 1lb to 4lb for US PP and Priority. Some gain, some loose
	Used England for overseas postage since it has a higher rate than Australia!
	*/				
	///////////////////////////////////////////////////////////////////////
	var myForm=document.Form1;
	
	var shippingMethodOK=true;		// Priority in USA only
	
	var SAndH=1.0;							//$ Add a constant amount
	var baseUSA_PP=3.75;					//$ Parcel Post USA for 1lb, for 6in x 6in x 6in 
	var baseUSA_Priority=3.85;			//$ Priority USA for 1lb, for 6in x 6in x 6in 
	var baseCanada_PP=13.25;			//$ Parcel Post Canada for 1lb
	var baseForeign_PP=16.00;			//$ Parcel Post Foreign (England) for 1lb
	
	var RatePerPoundUSA_PP=1.34;			//$
	var RatePerPoundUSA_Priority=2.17;	//$
	var RatePerPoundCanada_PP=0.75;		//$
	var RatePerPoundForeign_PP=4.0;		//$

	var shipping=0;
	//Shipping:
	//alert("cntItems shipping = " + cntItems);
	//alert("shipping totWeight shipping = " + totWeight);
	//As per email 19/01/03 5 items or less use smaller packaging
	var wPackagingUse=(cntItems>5)?wPackagingLarge:wPackagingSmall;
	//alert("weightToShip oz = " + (totWeight+wPackagingUse));
	var weightToShip=0.0625*(totWeight+wPackagingUse);                     //lb
	alert("weightToShip lbs = " + weightToShip);
	if (weightToShip<1) {weightToShip=1;}
	//alert("weightToShip shipping = " + weightToShip);
	
	//Shipping Method - ddl D36:
	var indexShippingMethod = document.Form1.D36.selectedIndex;
	//alert("indexShippingMethod = " + indexShippingMethod);
	var shippingMethod=document.Form1.D36.options[indexShippingMethod].value;
	var indexCountry = document.Form1.T12.selectedIndex;
	var country=document.Form1.T12.options[indexCountry].value;
	/////////////////////////////////////
	//indexShippingMethod=1;
	//indexCountry=1;
	//shippingMethod="Priority";
	//country="USA";
	////////////////////////////////////
	if ((indexShippingMethod>0) & (indexCountry>0) & (totWeight>0))
	{	
		
		//alert("shipping method = " + shippingMethod + "\ncountry = " + country);			
		if ((shippingMethod=="Priority") & (country !="USA") & (!isUSTerritory) )
		{
			alert("Priority shipping is not available to " + country);
			document.Form1.D36.selectedIndex=1;							//Set to Parcel Post
			//shippingMethodOK=false;
		}

		//alert("shipping method = " + shippingMethod + "\ncountry = " + country + "\nisUSTerritory = " + isUSTerritory);		
		if ((country=="USA") || (isUSTerritory))
		{
			//alert("USA");
			if (shippingMethod=="PP")
			{
				//shipping=fnMyRound(SAndH + baseUSA_PP+((weightToShip-1)*RatePerPoundUSA_PP),2)   ;
				//alert("shipping USA PP = $" + shipping + "\nS&H = $" + SAndH + "\ntotWeight (lb) = " + 0.0625*totWeight + "\nwPackagingUse (lb) = " + 0.0625*wPackagingUse + "\nweightToShip (lb) = " +  weightToShip + "\nbaseUSA_PP =  $" + baseUSA_PP + "\nRatePerPoundUSA_PP = $" + RatePerPoundUSA_PP);
				if (weightToShip<=1.00) {shipping=(3.75 + SAndH);}
				if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(4.49 + SAndH);}
				if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(6.32 + SAndH);}
				if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(7.87 + SAndH);}
				if (weightToShip>4.00) 
				{
					//alert("fnMyRound( ((" + weightToShip + "-4)*" + RatePerPoundUSA_PP + "),2)= " + fnMyRound( ((weightToShip-4)*RatePerPoundUSA_PP),2));
					shipping=SAndH + 7.87 +  ((weightToShip-4)*RatePerPoundUSA_PP);
				}
			}
			
			else
			{
				//Priority:
				//shipping=fnMyRound(SAndH + baseUSA_Priority+((weightToShip-1)*RatePerPoundUSA_Priority),2);
				//alert("shipping USA Priority = $" + shipping + "\nS&H = $" + SAndH + "\ntotWeight (lb) = " + 0.0625*totWeight +"\nwPackagingUse (lb) = " + 0.0625*wPackagingUse + "\nweightToShip (lb) = " + weightToShip + "\nbaseUSA_Priority = $" + baseUSA_Priority + "\nRatePerPoundUSA_Priority = $" + RatePerPoundUSA_Priority);
			
				if (weightToShip<=1.00) {shipping=(3.85 + SAndH);}
				if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(5.75 + SAndH);}
				if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(8.55 + SAndH);}
				if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(10.35 + SAndH);}
				if (weightToShip>4.00) { shipping=SAndH + 10.35 + ((weightToShip-4)*RatePerPoundUSA_Priority);}
			}
		}
		else
		{
			switch (country)
			{
				case "Canada":
					//alert("Canada");
					//alert("SAndH = " + SAndH);
					if (weightToShip<=1.00) {shipping=(3.75 + SAndH);}
					if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(6.35 + SAndH);}
					if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(8.95 + SAndH);}
					if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(11.75 + SAndH);}
					if (weightToShip>4.00) {shipping=SAndH + 11.75 + ((weightToShip-4)*2.80);}
					break;
				case "United Kingdom":
					//alert("UK");
					if (weightToShip<=1.00) {shipping=(8.70 + SAndH);}
					if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(13.30 + SAndH);}
					if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(18.10 + SAndH);}
					if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(23.10 + SAndH);}
					if (weightToShip>4.00) {shipping=SAndH + 23.10 + ((weightToShip-4)*5.00);}
					break;
				case "Australia":
					//alert("Australia");
					if (weightToShip<=1.00) {shipping=(9.70 + SAndH);}
					if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(14.90 + SAndH);}
					if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(20.30 + SAndH);}
					if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(25.90 + SAndH);}
					if (weightToShip>4.00) {shipping=SAndH + 25.90 + ((weightToShip-4)*5.60);}					
					break;
				case "Japan":
					//alert("Japan");
					if (weightToShip<=1.00) {shipping=(9.70 + SAndH);}
					if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(14.90 + SAndH);}
					if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(20.30 + SAndH);}
					if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(25.90 + SAndH);}
					if (weightToShip>4.00) {shipping=SAndH + 25.90 + ((weightToShip-4)*5.60);}
					break;
				case "Singapore":
					//alert("Singapore");
					if (weightToShip<=1.00) {shipping=(9.25 + SAndH);}
					if ((weightToShip>1.00) & (weightToShip<=2)) {shipping=(15.65 + SAndH);}
					if ((weightToShip>2.00) & (weightToShip<=3)) {shipping=(22.45 + SAndH);}
					if ((weightToShip>3.00) & (weightToShip<=4)) {shipping=(29.45 + SAndH);}
					if (weightToShip>4.00) {shipping=SAndH + 29.45 + (weightToShip-4)*7.00;}
					break;
				default:
					//Foreign:
					//alert("Foreign");
					shipping=fnMyRound(SAndH + baseForeign_PP+(0.0625*(weightToShip-1)*RatePerPoundForeign_PP),2);
					//alert("shipping Foreign = $" + shipping + "\nS&H = $" + SAndH + "\ntotWeight (lb) = " + 0.0625*totWeight +"\nwPackagingUse (lb) = " + 0.0625*wPackagingUse + "\nweightToShip (lb) = " + weightToShip + "\nbaseForeign_PP = $" + baseForeign_PP + "\nRatePerPoundForeign_PP = $" + RatePerPoundForeign_PP);
					break;
			}			
		}
	}
	else
	{	
		//Sort of a nuisance:
		//if ((indexShippingMethod>0) & (indexCountry==0)) {alert("Country required before shipping can be calculated");}
	}
	//For demo only. Calculates shippping just on packaging alone
	shipping=fnMyRound(shipping,2);
	if ((totWeight>0) & (shipping>0))
	{
		//alert("Shipping USPS = $" + shipping + "\nShipping weight = " + weightToShip + "lbs");
	}
	return shipping;
}


function fnCalcShipTaxTotal()
{
	//alert("fnCalcShipTaxTotal");
	var myForm=document.Form1;
	stateTax=0;
	var shipping=0;
	var subTotalPrice=0;
	
	
	// Shipping /////////////////////////////////////////////////////////
	if (myForm.PayShipping.selectedIndex==0)
	{
		//Merchant charges shipping:
		myForm.ShipAccount.value="";
		myForm.ShipAccount.disabled=true;
		shipping=fnMyRound(fnCalcShipping(),2);
		//alert("shipping returned from fnCalcShipping = " + shipping);
	}
	else
	{
		//Customer pays shipping:
		myForm.ShipAccount.disabled=false;
	}
	
	if (totQty>0) { subTotalPrice=parseFloat(fnConvertToDecimal(myForm.SubTotalPrice.value)); }
	//alert("subTotalPrice = " + subTotalPrice);
	//alert("shipping return = " + shipping);
	
	
	// State Tax //////////////////////////////////////////////////////
	//alert("subTotalPrice 1 = " + subTotalPrice);
	//alert("stateTaxRate 1 = " + stateTaxRate);
	var ddl=myForm.T5;
	var index=ddl.selectedIndex;
	if (ddl.options[index].value==stateTaxing)
	{
		//alert("subTotalPrice  = " + subTotalPrice + "\nshipping = " + shipping + "\nsubTotalPrice + shipping = " + (subTotalPrice + shipping));
		//alert("subTotalPrice + shipping = " + subTotalPrice + shipping);
		stateTax=(parseFloat(stateTaxRate)/100)*(subTotalPrice + shipping);
		//alert("stateTax Calc'd = " + stateTax);
		stateTax=fnMyRound(stateTax,2);
	}

	
	// Grand Total: ////////////////////////////////////////////////////
	//alert("totPrice GT = " + subTotalPrice);
	//alert("shipping GT = " + shipping);
	//alert("stateTax GT = " + stateTax);
	 
	//LOOK OUT: THESE DOCUMENT.WRITES UPSET document.Form1 (myFORM)!!!!!!!!!!!!! 
	//document.write("<br>totPrice GT = " + subTotalPrice);
	//document.write("<br>shipping GT = " + shipping);
	//document.write("<br>stateTax GT = " + stateTax);
	
	//Have to round the whole lot!
	grandTotal =fnMyRound((subTotalPrice + shipping + stateTax),2);
	//alert("grandTotal = " + grandTotal);
	//document.write("<br>grandTotal = " + grandTotal);

	myForm.Shipping.value=fnConvertToCurrency(shipping);
	myForm.StateTax.value=fnConvertToCurrency(stateTax);
	myForm.GrandTotal.value=fnConvertToCurrency(grandTotal);
}


function fnConvertToCurrency(Val)
{
	//Always to two decimal places:
	//alert("fnConvertToCurrency(" + Val + ")");
	
	pos=-1;	
	var newVal=Val.toString();
	pos= newVal.indexOf(".",0);
	if (pos>0)
	{
		newVal += "00";		
		newVal=newVal.substr(0,pos) + newVal.substr(pos,3);
		//alert("newVal = " + newVal);
	}
	else
	{
		newVal +=".00";
		//alert("newVal 3 = " + newVal);
	}
	//Add commas:
	var len=newVal.length;
	//alert("len = " + len);
	if (len>6)
	{
		//alert("newVal.substr(0,2) = "  + newVal.substr(0,2) + "\nnewVal.substr(2) = " + newVal.substr(2));
		if (len==7) {newVal=newVal.substr(0,1) + "," + newVal.substr(1);}
		if (len==8) {newVal=newVal.substr(0,2) + "," + newVal.substr(2);}
		if (len==9) {newVal=newVal.substr(0,3) + "," + newVal.substr(3);}
	}
	newVal = "$" + newVal;
	//alert("ConvertedToCurrency = " + newVal);
	return newVal;
}


function fnConvertToDecimal(val)
{
	//alert("fnConvertToDecimal val = " + val);
	if (val=="") {returnDecimal=0;}
	var returnDecimal=val;
	returnDecimal=fnReplace(returnDecimal,",","")
	if (returnDecimal.substr(0,1)=="$") {returnDecimal=returnDecimal.substr(1);}
	//alert("ConvertedToDecimal = " + returnDecimal);
	return returnDecimal;
}


function fnGetOrderMethod()
{
	//alert("fnGetOrderMethod()");
	var Return=0;
	var group=document.Form1.OrderMethod;
	//alert("group.length = " + group.length);
	for (var i=0;i<group.length;i++)
	{
		if (group[i].checked) {Return=i+1; break;}
	}
	//alert("Return (fnGetOrderMethod()) = " + Return);
	return Return;
}


function fnGetShippingCode(val)
{
	//alert("fnGetShippingCode val = " + val);
	var returnVal=0;
	var temp=val.toUpperCase();
	var searchFor="SHIPPINGCODE";
	//alert("temp = " + temp);
	temp=temp.replace(/ /g,"");   //Remove white spaces: (RegExp)
	//alert("temp replaced = " + temp);
	var pos=temp.indexOf(searchFor,0);
	//alert("pos = " + pos);
	if (pos>-1)
	{
		returnVal=temp.substr(pos+searchFor.length,1);
	}
	//alert("returnVal = " + returnVal);
	return returnVal;
}

	
function fnGetOrderNumber()
{
	//alert("GetOrderNumber");
	var now=new Date();	
	var nowYear=now.getFullYear().toString();
	nowMonth=(parseInt(now.getMonth()) + 1);
	var nowDate=now.getDate();
	var nowHours=now.getHours();
	var nowMinutes=now.getMinutes();
	var nowSeconds=now.getSeconds();
	nowYear=nowYear.substr(2,2);
	if (nowMonth < 10) {nowMonth="0"+nowMonth;}
	if (parseInt(nowDate) < 10) {nowDate="0"+nowDate;}
	if (parseInt(nowHours) < 10) {nowHours="0"+nowHours;}
	if (parseInt(nowMinutes) < 10) {nowMinutes="0"+nowMinutes;}
	if (parseInt(nowSeconds) < 10) {nowSeconds="0"+nowSeconds;}
	orderNumber=nowYear+nowMonth+nowDate+ "_" + nowHours+nowMinutes+nowSeconds
	//alert("orderNumber (fnGetOrderNumber)= " + orderNumber);
	return orderNumber;
}
		
	
function fnMyRound(val,dp)
{
	//alert("fnMyRound(" + val + ")");
	//Parameter dp: round out Val to dp decimal places:
	//Interesting situation: Always round up Ok with +ve numbers. -ve numbers happen when 
	//	decrementing Qty in which case number rounds down! So, if -ve number
	
	pos=-1;
	var newVal=val.toString();
	var newVal2=0;
	var roundUpDn=((val>0)?+1:-1);
	//alert("roundUpDn = " + roundUpDn);
	var dec=1;
	if (dp==1) {dec=10;}  
	if (dp==2) {dec=100;}  
	if (dp==3) {dec=1000;}  
	if (dp==4) {dec=10000;}  
	
	pos= newVal.indexOf(".",0);
	if (pos>0)
	{
		newVal += "000000";
		//alert("newVal round A1 = " + newVal);
		//newVal2=(parseFloat(newVal)*dec) + 0.5*roundUpDn;
		//alert("newVal2 round A3 = " + newVal2);
		newVal2=((parseFloat(newVal)*dec + (0.5*roundUpDn))/dec).toString();
		//alert("newVal2 round A4 = " + newVal2);
		newVal2=newVal2.substr(0,pos) + newVal2.substr(pos,dp+1);
		//alert("newVal2 rounded A5 = " + newVal2);
	}
	else
	{
		var pad=".000000";
		newVal2=newVal+pad.substr(0,dp+1);	
		//alert("newVal2 Round B1 = " + newVal2);
	}
	//alert("fnMyround rounded = " + newVal2);
	return parseFloat(newVal2);
}


function fnOnFocus(id)
{
	//OnFocus fires repeatedly. Only want to read/set cIdRef the first time
	var myId=id;
	//alert("fnOnFocus() myId 1 = " + myId + "\ncIdRef = " + cIdRef);
	if (myId!=cIdRef)
	{
		//First time for this id:
		cQty=parseInt(document.getElementById(id).value);
		cIdRef=id;
		//alert("fnOnFocus() id 2 = " + id + "\ncQty = " + cQty + "\ncIdRef = " + cIdRef);		
	}
} 


function fnOrderMethod(val)
{
	//alert("orderMethod val = " + val);
	//val: 1 - online, 2 - Fax, 3 - Mail
	var orderMethod=val;
	var sOrderMsg="";
	var myForm=document.Form1;
	
	if (orderMethod=="1")
	{
		//On Line:
		myForm.Submit1.value="Submit Order";
		//sOrderMsg="<P align='center'><font color='#ff0000' size='2'><b>Submitting Your Order: </b></font><font size='2'>Click the <EM>Submit Order</EM> button immediately below to send your order.<br>You will receive confirmation of your order in a few seconds.<br>If you have included your e-mail address (above), the processing of your order will be confirmed<br>on the next business day after your order is received, with an anticipated delivery date.<br>Print a copy of this page for your records</font></P>";
		sOrderMsg="<P align=center><FONT color=#ff0000 size=2><B>Send Your Order</B></FONT><FONT size=2> by clicking the button below.<BR>You will receive confirmation of your order in a few seconds.<br>Print a copy of this page for your records</FONT></P>";
	}
	if (orderMethod=="2")
	{
		//Fax:
		myForm.Submit1.value="Check Order";
		sOrderMsg="<P align='center'><font color='#ff0000' size='2'><b>Check Your Order </b></font><font size='2'> by clicking the button below.<br>Print a copy of this page for your records</font></P>";
	}
	if (orderMethod=="3")
	{
		//Mail:
		myForm.Submit1.value="Check Order";
		sOrderMsg="<P align='center'><font color='#ff0000' size='2'><b>Check Your Order </b></font><font size='2'> by clicking the button below.<br>Print a copy of this page for your records</font></P>";
	}
	//alert(sOrderMsg);
	//OrderMsg.innerText works with IS but document.Form1.OrderMsg does not!. So ....
	document.getElementById("OrderMsg").innerHTML=sOrderMsg;
	
	//alert("orderMethod = " + orderMethod);
	fnSetCCFields(orderMethod);
}


function fnReplace(val, what, withWhat)
{
	//Called from fnConvertToDecimal:
	//what string to replace - looks like it will handle strings of more than 1 char,
	//withWhat  string to replace 'what' with.
	//alert("fnReplace val = " + val + "\nwhat = " + what + "\nwithWhat = " + withWhat);
	var temp = "" + val; // temporary holder
	while (temp.indexOf(what)>-1) 
	{
		pos= temp.indexOf(what);
		temp = "" + (temp.substring(0, pos) + withWhat + temp.substring((pos + what.length), temp.length));
	}
	//alert("fnReplace Replaced = " + temp);
	return temp;
}


function fnReset()
{
	//alert("fnReset");
	document.getElementById("OrderNumberHTML").innerHTML="";
	document.Form1.Submit1.disabled=false;
}


function fnSetCCFields(val)
{
	//D1
	//alert("fnSetCCFields() val = " + val);	
	var myForm=document.Form1;
	var index =myForm.D1.selectedIndex;
	//alert("index = " + index);
	var paymentMethod=myForm.D1.options[index].value.toUpperCase();
	//alert("paymentMethod = " + paymentMethod);
	
	if (index>0)
	{
		var methods="MONEYORDER/CHECK";
		var pos=methods.indexOf(paymentMethod,0);
		//alert("pos = " + pos);
		
		//if val=0, called from HTML ddl D1. Then need to find out what order method has been chosen
		var orderMethod=(val>0)?val:fnGetOrderMethod();
		//alert("orderMethod = " + orderMethod);
		
		if (orderMethod>0)
		{
			if ( (pos>-1) & (orderMethod<3)) 
			{ 
				if (val==0)
				{ 
					myForm.D1.focus();
				}
				else
				{
					location.href="#ParkOrderMethod";
				}
				alert("Order has to be sent by mail if paying with a check or money order");
				return false;
			}
		}
	
		if (pos==-1)
		{
			//Pay by CC.:
			myForm.T9M.disabled=false;
			myForm.T9Y.disabled=false;
			myForm.T10.disabled=false;
			myForm.T11.disabled=false;
			myForm.T13.value="";
			//myForm.T13.disabled=true;
			PayByCC=true;		
			
			if (myForm.T10.value!="")
			{
				//Now that AmEx has different number of digits, need to recheck the card number length (T10):
				if (fnValNumber("xxx", 2)!=true) { return false;}
			}
		}
		else
		{
			//Pay by check/money order. Has to be orderMethod 3 (mail):
			myForm.T9M.disabled=true;
			myForm.T9Y.disabled=true;
			myForm.T10.disabled=true;
			myForm.T11.disabled=true;
			myForm.T9M.selectedIndex=0;
			myForm.T9Y.selectedIndex=0;
			myForm.T10.value="";
			myForm.T11.value="";
			myForm.T13.disabled=false;
			PayByCC=false;
		}
	}
	return true;
}


function fnSetStateCountry(val)
{
	//Cannot use disable because then the value does not show up in sent form:
	//T5: States USA, Canada
	//T5Other: State for another country
	//T12: Country 
	//State index:
	var source=val;
	//alert("fnSetStateCountry()");
	//alert("source = " + source);
	
	var myForm=document.Form1;
	var indexStateUSACanada = myForm.T5.selectedIndex;
	var stateUSACanada=document.Form1.T5.options[indexStateUSACanada].value;
	var stateOther=myForm.T5Other.value;
	var indexCountry=myForm.T12.selectedIndex;
	var country=myForm.T12.options[indexCountry].value
	var zip=myForm.T6.value;
	
	//alert("val = " + val + "\nindexStateUSACanada = " + indexStateUSACanada + "\nstateUSACanada = " + stateUSACanada + "\nstateOther = " + stateOther + "\nindexCountry = " + indexCountry + "\nzip = " + zip); 
	
	if (val=="T5") 
	{
		myForm.T5Other.value="";

		if (indexStateUSACanada>0)
		{
			if (stateUSACanada.length>2)
			{
				document.Form1.T12.selectedIndex=indexCanada;	
			}
			else
			{
				//USA
				document.Form1.T12.selectedIndex=indexUSA;	
				//Check zip:
				//alert("zip = " + zip);
				if ((zip!="") && (fnValNumber("xxx",3)!=true))
				{
					document.Form1.T6.value="";
				}	
			}
		}
		else
		{
			//Other than USA or Canada (T5 not set)
			document.Form1.T12.selectedIndex=0;
		} 
	}
	
	if (val=="T5Other")
	{
		myForm.T5.selectedIndex=0;
		if ((indexCountry==indexUSA) || (indexCountry==indexCanada))
		{
			document.Form1.T12.selectedIndex=0;
		}
	}
	
	if (val=="T12")
	{
		//Country:		
		if ((indexCountry==indexUSA) || (indexCountry==indexCanada))		//USA or Canada
		{
			//USA or Canada:
			//alert("document.Form1.T5Other.value = " + document.Form1.T5Other.value);
			if (stateOther!="") {alert("Select US states and Canadian provinces, don't type them in");}
			document.Form1.T5Other.value="";
			if ((indexCountry==indexUSA) & (stateUSACanada.length>2))
			{
				//Was Canadian state - Reset
				document.Form1.T5.selectedIndex=0;
				//Check zip:
				//alert("zip = " + zip);
				if ((zip!="") && (fnValNumber("xxx",3)!=true))
				{
					document.Form1.T6.value="";
				}
			}
		}
		else
		{
			//alert("Country");
			//Other country (including US Terrorities):
			//////////////////////////////////////////////
			//Test for US Territory:
			var testCountry=country.toUpperCase();
			//alert("testCountry 1 = " + testCountry);
			testCountry=testCountry.replace(/ /g,"");   //Remove white spaces: (RegExp)
			//alert("testCountry 2 = " + testCountry);
			var pos=USTerritories.indexOf(testCountry,0);
			//alert("pos = " + pos);
			isUSTerritory=(pos>-1)?true:false;			//Result thereof!
			//alert("isUSTerritory = " + isUSTerritory);
			//////////////////////////////////////////////
			document.Form1.T5.selectedIndex=0;
		}		
	}	
	
	////////////////////////	
	fnCalcShipTaxTotal();   //This is at the end of fnSetStateCountry()
	////////////////////////		
}
	

function fnUpdateCreditCardHolder()
{
	//Default Card holder name to First, Last Name - only when name on card=""
	if (document.Form1.T11.value=="") {document.Form1.T11.value=document.Form1.T1.value;} 
}

function fnValExpirationDate()
{
	//alert("Exp Date");
	expMonth=parseInt(document.Form1.T9M.value);
	expYear=parseInt(document.Form1.T9Y.value);
	
	if ((expMonth>0) & (expYear>0))
	{
		var now=new Date();
		nowMonth=parseInt(now.getMonth());
		nowYear=parseInt(now.getFullYear());
		//alert("nowMonth = " + nowMonth + "\nnowYear = " + nowYear);
		if (expYear<nowYear) 
		{
			alert("Credit Card has expired"); 
			return false;
		}
		if (expYear==nowYear)
		{
			if (expMonth<(nowMonth+1))
			{
				alert("Credit Card has expired"); 
				return false;
			}
		}
	}
	return true;	
}


function fnValEmail()
{
	//alert("fnValEmail");
	//Decide to always allow it because the email cold be valid 
	var Email=document.Form1.T8.value;
	if (Email!="")
	{
		//This RegEx pattern does not work properly!
		//var myRegExp=/[a-z0-9-.]{1,30}@[a-z0-9-]{1,65}.(com|net|org|info|biz|([a-z]{2,3}.[a-z]{2}))/;
		//if (myRegExp.test(Email)!=true)
		//{
		//	document.Form1.T8.focus();
		//	alert("Does not appear to be a valid Email address");
		//}
		
		var posAt=Email.indexOf("@",0);
		var posDot=Email.lastIndexOf(".",Email.length);
		//alert("posAt = " + posAt);
		//alert("posDot = " + posDot);
		if ((posAt==-1) | (posDot==-1) | (posDot<posAt))
		{
			document.Form1.T8.focus();
			alert("Does not appear to be a valid Email address");
			return true;                       //Allow it because the email could be valid 		
		}
		
	}
	return true;
}


function fnValNumber(what, how)
{
	//alert("What = " + what);
	//Use for phone, cc#s, zips (US only):
	//NOTE: Characters in place of digits are not allowed and will be rejected.
	//what - pass the value of this. (redundant):
	//how =1: Accept (- phone numbers:
	//how =2: Accept - <spaces> credit card #s:
	//how =3: Accept - <spaces> US zips 5 or 5-4:
	
	var i=0;
	var Char="";
	var CharCode=-1;
	var OK=1;
	var CCCompany="";
	var indexCompany=0;
	if (how=="2")
	{
		var indexCompany = document.Form1.D1.selectedIndex;
		CCCompany=document.Form1.D1.options[indexCompany].value.toUpperCase();
	}
	var CCLength=0;
	var whatNow=document.Form1.T7.value;
	if (how=="2") {whatNow=document.Form1.T10.value;}
	if (how=="3") {whatNow=document.Form1.T6.value;}
	if ((whatNow!="") & (whatNow!=null))
	{
		var Match="- ";
		var newWhat="";
		if (how=="1") {Match+="()";}				//Phone numbers
		var Len=whatNow.length;
		
		//1. Normalize entry:
		for (i=0;i<Len;i++)
		{
			Char=whatNow.charAt(i);
			CharCode=whatNow.charCodeAt(i);
			
			//alert("Char, Code = " + Char + ", " + CharCode);
			{
				if (Match.indexOf(Char,0)>-1) 
				{ 
					//separator:
				}
				else
				{
					if  ((CharCode>47) & (CharCode<58))
					{
						//Digit:
						newWhat+=Char;
						//alert("Build newWhat = " + newWhat);
					}
					else
					{
						OK=-1;
						break;
					}
				}	
			}
		}
		//After loop:	
		if (OK==1)
		{
			OK=0;
			Len=newWhat.length;
			if (how=="1")
			{
				//Phone:
				if ((Len==10) || ((Len==11) & (newWhat.charAt(0)=="1")))
				{
					//Length OK:
					OK=1;
					if (Len==10)
					{
						newWhat=newWhat.substr(0,3) + "-" + newWhat.substr(3,3) + "-" + newWhat.substr(6,4);
					}
					else
					{
						newWhat=newWhat.substr(0,1) + "-" + newWhat.substr(1,3) + "-" + newWhat.substr(4,3) + "-" + newWhat.substr(7,4);
					}
				}	
			}
			
			if (how=="2")
			{
				//CC - All CCs have 16 digits except for AmEx which has 15:
				if (CCCompany=="")
				{
					alert("Select the credit card name (i.e. Visa, Master Card) before entering the number");
					document.Form1.D1.focus();
					return false; 
				}
				CCCompany=CCCompany.replace(/ /g,"");   //Remove white spaces: (RegExp)
				//alert("CCCompany = " + CCCompany);
				CCLength=(CCCompany=="AMERICANEXPRESS")?15:16;
				CCCompany=document.Form1.D1.options[indexCompany].text;
				//alert("CCLength = " + CCLength);
				if (Len==CCLength)
				{
					//Length OK:
					OK=1;
					if (CCLength==16)
					{
						newWhat=newWhat.substr(0,4) + " " + newWhat.substr(4,4)+ " " + newWhat.substr(8,4)+ " " + newWhat.substr(12,4)
					}
					else
					{
						//AmEx: 3727 929445 11007
						newWhat=newWhat.substr(0,4) + " " + newWhat.substr(4,6)+ " " + newWhat.substr(10,5)
					}				
				}				
			}
			
			if (how=="3")
			{
				//US zips:
				if ((Len==5) || (Len==9))		
				{
					//Length OK:
					OK=1;
					if (Len==5)
					{
						newWhat=newWhat;
					}
					else
					{
						newWhat=newWhat.substr(0,5) + "-" + newWhat.substr(5,4);
					}
				}
			}
		}
		
		//Write back to control:
		if (OK==1)
		{
			if (how=="1")
			{
				document.Form1.T7.value=newWhat;
			}
			if (how=="2")
			{
				document.Form1.T10.value=newWhat;
			}
			if (how=="3")
			{
				document.Form1.T6.value=newWhat;
			}
			return true;
		}
		else
		{
			if (OK==0) 
			{
				if (how=="1")
				{
					document.Form1.T7.focus();
					alert("Phone numbers have 10 digits (" + Len + " entered)");				
				}
				if (how=="2")
				{
					document.Form1.T10.focus();
					alert(CCCompany + " credit cards have " +  CCLength + " digits (" + Len + " entered)");	
				}	
				if (how=="3")
				{
					//US Zips"
					document.Form1.T6.focus();
					alert("US Zip codes have 5 or 5+4 digits (" + Len + " entered)");	
				}	
			}
			else
			{
				var Var=(how=="1")?"Phone number":((how=="2")?"Credit card number":"US Zip code");
				alert(Var + " has illegal charcters");
			}
			return false;
		}
	}
}


function fnValidateOrder(val)
{
	//alert("fnValidateOrder(" + val + ")");
	var myForm=document.Form1;
	var success=0;
	var Var="";
	var Var2="";

	//1. Products Ordered
	
	//2. OrderMethod:
	//alert("orderMethod 2 = " + orderMethod);
	if (fnGetOrderMethod()==0) 
	{
		location.href="#ParkOrderMethod";
		alert("Select an ordering method - online, fax, mail");
		return false;
	}
	else
	{
		if (fnSetCCFields(0) != true) {return false;}
	}

	//3. Name:
	Var=myForm.T1.value;
	if (Var=="")
	{
		myForm.T1.focus();
		alert("First, Last Name required");
		return false;
	}
	
	//4. Address:
	//alert("orderMethod 4 = " + orderMethod);
	Var=myForm.T3.value;
	if (Var=="")
	{
		myForm.T3.focus();
		alert("Address required");
		return false;
	}
	
	//5. City:
	Var=myForm.T4.value;
	if (Var=="")
	{
		myForm.T4.focus();
		alert("City required");
		return false;
	}
	
	//6. State:
	//alert("orderMethod 6 = " + orderMethod);
	if ((myForm.T5.selectedIndex==0) && (myForm.T5Other.value==""))
	{
		myForm.T5.focus();
		alert("State/Province required");
		return false;
	}
	
	//7. Zip:
	Var=myForm.T6.value;
	if (Var=="")
	{
		myForm.T6.focus();
		alert("Zip Code required");
		return false;
	}
	else
	{
		if (fnValZip() !=true) {return false;}
	}
			
	//8. Country:
	select=myForm.T12;
	if (select.selectedIndex==0)
	{
		alert("Country required");
		myForm.T12.focus();
		return false;
	}

	//9. Phone, Email:
	Var=myForm.T7.value;				//Phone:
	Var2=myForm.T8.value;				//Email:	
	if ((Var2=="") & (Var==""))
	{
		myForm.T7.focus();
		alert("Should we need to contact you,\nplease provide either email address or phone number.");
		return false;
	}
	else
	{	//Let email address go thru
		if (Var!="")
		{
			//Validate phone:
			if (fnValNumber("xxx",1)!=true)
			{
				return false;						
			}
		}
	}
	
	//10. Shipping Method:
	select=myForm.D36.selectedIndex;
	if (select==0)
	{
		myForm.D36.focus();
		alert("Shipping Method required");
		return false;
	}
	
	//11. Ship Account:
	if ((myForm.PayShipping.selectedIndex==1) & (myForm.ShipAccount.value==""))
	{
		myForm.ShipAccount.focus()
		alert("Seeing you have elected to pay for shipping yourself, Shipping Account required");
		return false;
	}
	
	//9. Payment Method:
	Var=myForm.D1.selectedIndex;
	if (Var<1)
	{
		myForm.D1.focus();
		alert("Select a Payment Method");
		return false;
	}

	//////////////////////////////////////////////////////////////
	//Required for CC payments only - online or fax
	//alert("orderMethod 11 = " + orderMethod);
	if ((orderMethod==1) || (orderMethod==2))
	{
		//10. Credit Card Number:
		Var=myForm.T10.selectedIndex;
		if (myForm.T10.value=="")
		{
			myForm.T10.focus();
			alert("Credit card number required");
			return false;
		}
		else
		{
			//Validate CC#:
			if (fnValNumber("xxx","2")!=true)
			{
				myForm.T10.focus();
				return false;
			}
		}
		
		
		//11. Expiration Date:
		Var=myForm.T9M.selectedIndex;
		Var2=myForm.T9Y.selectedIndex;
		if ((Var<1) || (Var2<1))
		{
			if (Var<1)
			{
				myForm.T9M.focus();
				alert("Card Expiration required");
				return false;
			}
			else
			{
				myForm.T9Y.focus();
				alert("Card Expiration required");
				return false;
			}
		}
		else
		{
			//Check exp date is in the future:
			if (fnValExpirationDate()!=true) 
			{
				myForm.T9M.focus();
				return false;
			}
		}
		
		
		//12. CardHolder Name:
		Var=myForm.T11.value;
		if (Var=="")
		{
			myForm.T11.focus();
			alert("Card Holder Name required");
			return false;
		}
	}
	
	//////////////////////////////////////////////////////////////
	//Finish:
	//Will only get here if all the above validates OK:
	//Add order number to: <div id="OrderNumberHTML"></div>
	if (orderNumber==0) 
	{
		fnGetOrderNumber();
		//alert("orderNumber = " + orderNumber);
		document.Form1.OrderNumber.value=orderNumber;
		document.getElementById("OrderNumberHTML").innerHTML="Your order number is " + orderNumber;
	}
	if (orderMethod==1)
	{
		//On line ordering:
		myForm.Submit1.disabled=true;
		
		alert("Your order has been successfully completed.\n\nTo send your order on its way, click OK.\nFor your records, print this page\n"); 		
		//return true;
		return false;   //For TEST
	}
	else
	{
		//Fax or mail - orderMethod=2,3
		myForm.Submit1.disabled=false;
		if (orderMethod==2)
		{	
			//Fax:
			alert("Your order has been successfully completed.\n\nFor your records, print this page\n"); 		
			return false;
		}
		else
		{
			//Mail:
			alert("Your order has been successfully completed.\nPlease remember to enclose check or money order.\n\nFor your records, print this page\n"); 	
			return false;
		}
	}
}


function fnValZip()
{
	//alert("Zip");
	var myForm=document.Form1;
	var zip=myForm.T6.value;
	var index=myForm.T12.selectedIndex;
	if ((zip!="") & (index==indexUSA))
	{
		zip=zip.replace(/ /g,"");   //Remove white spaces: (RegExp)
		if (fnValNumber("xxx", 3)==true)
		{
			fnCalcShipTaxTotal();
		}
	}

}


function fnGetFedexZone(zip)
{
	//alert("fnGetFedexZone zip = " + zip);
	var aryFedexZoneWI=new Array("000-003 NA","004-005 5","010-129 5","130-132 4","133-135 5","136-174 4",   "175-176 5","177-179 4","180-214 5","215 4","216 4","217 4",  "218-225 5","226 4","227 5","228-229 4","230-239 5","240-268 4",  "269 NA","270-286 5","287-289 4","290-306 5","307 4","308-326 5",  "327-342 6","343 NA","344 5","345 NA","346-349 6","350-355 5",  "356-358 4","359-369 5","400-409 4","410 3",  "411-423 4","433-436 3","437-447 4","448-455 3","456-457 4","458-462 3","463-466 2","467-470 3","471 4","472-475 3","476-477 4","478-487 3","488-491 2","492 3","493-496 2","497-499 3","500-503 4","504 3",  "505 4","506-507 3","508-516 4","517-519 NA","520 2","521-528 3",  "529 NA","530-539 2","540 3","541-544 2","545-548 3","549 2",  "550-555 3","556-558 4","559 3","560-574 4","575-577 5","578-579 NA",  "580-582 4","583 5","584 4","585-588 5","589 NA","590-591 6","592-593 5","594-599 6","600-611 2","612 3","613 2","614-619 3",  "620-622 4","623-628 3","629-633 4","634 3","635-669 4","670-672 5",  "673-674 4","675-679 5","680-689 4","690-722 5","723-727 4","728-732 5",  "733 6","734-742 5","743 4","744-768 5","769 6","770-778 5",  "779-789 6","790-796 5","800-810 5","811 6","812 5",  "813-816 6","817-819 NA","820 5","821 6","822-824 5","825 6",  "828-828 5","929-834 6","835-838 7","839 NA","840-847 6","848-849 NA",  "850-854 7","855 6","856-858 7","859-860 6","861-862 NA","863-864 7",  "865-883 6","885 5","886-888 NA","889-930 7","931 8",  "932-933 7","934 8","935-938 7","939-941 8","942 7","943-951 8",  "952-953 7","954-955 8","956-961 7","962-966 8","970-986 7","987 8");
	var aryFedexZoneAKHIPR=new Array("006-007 0^10","008 NA^NA","009 0^10","96700 12^9","96701 10^9","96702-96705 12^9",  "96706-96707 10^9","97608 10^9","96709 10^9","96710 12^9","96713-96716 10^9",  "96717 10^9","96718-96729 12^9","96730-99733 12^9","96734 10^9","96735-96743 12^9","96744 10^9","96745-86757 12^9","96758-96759 10^9","96760-96761 12^9","96762 10^9","96763-96774 12^9",  "96775 10^9","96776-96781 12^9","96782 10^9","96783-96785 12^9","96786 10^9","96787-96788 12^9",  "96789 10^9","96790 12^9","996791-96792 10^9","96793 12^9","96794-96795 10^9","96796 12^9",  "96797 10^9","96798-96800 12^9","96801-96863 10^9","96864-96899 12^9","969 NA^NA","99500 11^17","99501-99524 9^17","99525-99539 11^17","99540 9^17","99541-99566 11^17","99567 9^17","99568-99576 11^17",  "99577 9^17", "99578-99999 11^17");
	//alert("aryFedexZoneWI.length = " + aryFedexZoneWI.length);
	//alert("aryFedexZoneAKHIPR.length = " + aryFedexZoneAKHIPR.length);
	
	var zipStub=zip.substr(0,3);
	//alert("zipStub = " + zipStub);
	var zipZone="";
	var pos1=-1;
	var pos2=-1;
	var lowerZip="";
	var upperZip="";
	var fedexZone=0;
	
	for (var i=0;i<aryFedexZoneWI.length;i++)
	{
		zipZone=aryFedexZoneWI[i];
		//alert("zipZone = " + zipZone);
		pos2 = zipZone.indexOf(" ",0);				//Look for a space
		//alert("pos2 = " + pos2);
		if (pos2>-1)
		{
			pos1=zipZone.indexOf("-",0);    
			//alert("pos1 = " + pos1);         
			if (pos1>-1)									//There is a lower and upper zip range
			{
				lowerZip=zipZone.substr(0,pos1);
				//alert("lowerZip range = " + lowerZip);
				upperZip=zipZone.substr(pos1+1,pos2-pos1-1);  //There should always be a Zone value
				//alert("upperZip range = " + upperZip);
			}
			else
			{	
				//Only a single zip value
				lowerZip=zipZone.substr(0,pos2);
				upperZip=lowerZip;
				//alert("lowerZip single value = " + lowerZip);
			}
		}
		else
		{
			alert("There is an error in the array!");
		}
		//alert("zipstub = " + zipStub + ", lowerZip = " + lowerZip + ", upperZip = " + upperZip);
		if (parseInt(upperZip)<parseInt(zipStub))
		{
			//Try again:
		}
		else
		{
			if (parseInt(lowerZip)<=parseInt(zipStub))
			{
				fedexZone=zipZone.substr(pos2+1,zipZone.length-pos2-1);
				//alert("Found zipstub = " + zipStub + ", lowerZip = " + lowerZip + ", upperZip = " + upperZip + "\nfedexZone = " + fedexZone);
				if (fedexZone!="NA") 
				{
					fedexZone=parseInt(fedexZone);
				}
				else
				{
					//fedexZone=-1;
				}
				break;
			}
		}
		//if (i>5) break;
	}
	return fedexZone;
}


		
		

