//=====================================================================||
//               NOP Design JavaScript Shopping Cart                   ||
//                                                                     ||
// For more information on SmartSystems, or how NOPDesign can help you ||
// Please visit us on the WWW at http://www.nopdesign.com              ||
//                                                                     ||
// Javascript portions of this shopping cart software are available as ||
// freeware from NOP Design.  You must keep this comment unchanged in  ||
// your code.  For more information contact FreeCart@NopDesign.com.    ||
//                                                                     ||
// JavaScript Shop Module, V.4.4.0                                     ||
//=====================================================================||

//---------------------------------------------------------------------||
//                       Global Options                                ||
//                      ----------------                               ||
// Shopping Cart Options, you can modify these options to change the   ||
// the way the cart functions.                                         ||
//                                                                     ||
// Language Packs                                                      ||
// ==============                                                      ||
// You may include any language pack before nopcart.js in your HTML    ||
// pages to change the language.  Simply include a language pack with  ||
// a script src BEFORE the <SCRIPT SRC="nopcart.js">... line.          ||
//  For example: <SCRIPT SRC="language-en.js"></SCRIPT>                ||
//                                                                     ||
// Options For Everyone:                                               ||
// =====================                                               ||
// * MonetarySymbol: string, the symbol which represents dollars/euro, ||
//   in your locale.                                                   ||
// * DisplayNotice: true/false, controls whether the user is provided  ||
//   with a popup letting them know their product is added to the cart ||
// * DisplayShippingColumn: true/false, controls whether the managecart||
//   and checkout pages display shipping cost column.                  ||
// * DisplayShippingRow: true/false, controls whether the managecart   ||
//   and checkout pages display shipping cost total row.               ||
// * DisplayTaxRow: true/false, controls whether the managecart        ||
//   and checkout pages display tax cost total row.                    ||
// * TaxRate: number, your area's current tax rate, ie: if your tax    ||
//   rate was 7.5%, you would set TaxRate = 0.075                      ||
// * TaxByRegion: true/false, when set to true, the user is prompted   ||
//   with TaxablePrompt to determine if they should be charged tax.    ||
//   In the USA, this is useful to charge tax to those people who live ||
//   in a particular state, but no one else.                           ||
// * TaxPrompt: string, popup message if user has not selected either  ||
//   taxable or nontaxable when TaxByRegion is set to true.            ||
// * TaxablePrompt: string, the message the user is prompted with to   ||
//   select if they are taxable.  If TaxByRegion is set to false, this ||
//   has no effect. Example: 'Arizona Residents'                       ||
// * NonTaxablePrompt: string, same as above, but the choice for non-  ||
//   taxable people.  Example: 'Other States'                          ||
// * MinimumOrder: number, the minium dollar amount that must be       ||
//   purchased before a user is allowed to checkout.  Set to 0.00      ||
//   to disable.                                                       ||
// * MinimumOrderPrompt: string, Message to prompt users with when     ||
//   they have not met the minimum order amount.                       ||
//                                                                     ||
// Payment Processor Options:                                          ||
// ==========================                                          ||
// * PaymentProcessor: string, the two digit payment processor code    ||
//   for support payment processor gateways.  Setting this field to    ||
//   anything other than an empty string will override your OutputItem ||
//   settings -- so please be careful when receiving any form data.    ||
//   Support payment processor gateways are:                           ||
//    * Authorize.net (an)                                             ||
//    * Worldpay      (wp)                                             ||
//    * LinkPoint     (lp)
//                                                                     ||
// Options For Programmers:                                            ||
// ========================                                            ||
// * OutputItem<..>: string, the name of the pair value passed at      ||
//   checkouttime.  Change these only if you are connecting to a CGI   ||
//   script and need other field names, or are using a secure service  ||
//   that requires specific field names.                               ||
// * AppendItemNumToOutput: true/false, if set to true, the number of  ||
//   each ordered item will be appended to the output string.  For     ||
//   example if OutputItemId is 'ID_' and this is set to true, the     ||
//   output field name will be 'ID_1', 'ID_2' ... for each item.       ||
// * HiddenFieldsToCheckout: true/false, if set to true, hidden fields ||
//   for the cart items will be passed TO the checkout page, from the  ||
//   ManageCart page.  This is set to true for CGI/PHP/Script based    ||
//   checkout pages, but should be left false if you are using an      ||
//   HTML/Javascript Checkout Page. Hidden fields will ALWAYS be       ||
//   passed FROM the checkout page to the Checkout CGI/PHP/ASP/Script  ||
//---------------------------------------------------------------------||

//Options for Everyone:
MonetarySymbol        = '$';
DisplayNotice         = false;
DisplayShippingColumn = false;
DisplayShippingRow    = true;
DisplayTaxRow         = true;
TaxByRegion           = true;
TaxPrompt             = 'For tax purposes, please select if you are a California resident before continuing';
TaxablePrompt         = '</b>California residents<b>';
NonTaxablePrompt      = '</b>Other states<b>';
MinimumOrder          = 0.00;
MinimumOrderPrompt    = 'Your order is below our minimum order, please order more before checking out.';
kCATaxRate			  = 0.0825 ;
kSFTaxRate			  = 0.095 ;


//Payment Processor Options:
PaymentProcessor      = '';

//Options for Programmers:
OutputItemId          = 'ID_';
OutputItemQuantity    = 'QUANTITY_';
OutputItemPrice       = 'PRICE_';
OutputItemName        = 'NAME_';
OutputItemShipping    = 'SHIPPING_';
OutputItemAddtlInfo   = 'ADDTLINFO_';
OutputOrderSubtotal   = 'SUBTOTAL';
OutputOrderShipping   = 'SHIPPING';
OutputOrderTax        = 'TAX';
OutputOrderTotal      = 'TOTAL';
AppendItemNumToOutput = true;
HiddenFieldsToCheckout = false;

// some globals
var g_TotalCost = 0;
var g_Subtotal = 0 ;
var g_Taxable = 0 ;
var g_Tax = 0 ;
var g_TotalItems = 0 ;
var g_WholesaleDiscAmt = 0 ;
var iNumberOrdered = 0 ;
var	discounts = new Array ;
var	discountTotal = 0 ;
var giftCerts = new Array ;
var numGiftCerts = 0 ;
var retailerID ;

// some constants
var kWholesaleMinTotal = 800 ;
var kWholesaleMinItems = 15 ;
var kWholesaleRate = 0.6 ;

//=====================================================================||
//---------------------------------------------------------------------||
//    YOU DO NOT NEED TO MAKE ANY MODIFICATIONS BELOW THIS LINE        ||
//---------------------------------------------------------------------||
//=====================================================================||


//---------------------------------------------------------------------||
//                      Language Strings                               ||
//                     ------------------                              ||
// These strings will not be used unless you have not included a       ||
// language pack already.  You should NOT modify these, but instead    ||
// modify the strings in language-**.js where ** is the language pack  ||
// you are using.                                                      ||
//---------------------------------------------------------------------||
if ( !bLanguageDefined ) {
   strSorry  = "I'm Sorry, your cart is full, please proceed to checkout.";
   strAdded  = " added to your shopping cart.";
   strRemove = "Click 'Ok' to remove this product from your shopping cart.";
   strILabel = "Product Id";
   strDLabel = "Product Name/Description";
   strQLabel = "Quantity";
   strPLabel = "Price";
   strSLabel = "Shipping";
   strRLabel = "Remove From Cart";
   strRButton= "Remove";
   strSUB    = "SUBTOTAL";
   strSHIP   = "SHIPPING";
   strTAX    = "TAX";
   strTOT    = "TOTAL";
   strErrQty = "Invalid Quantity.";
   strNewQty = 'Please enter new quantity:';
   bLanguageDefined = true;
}


ilanioInit() ;


//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {
   var strNewQuantity = "";

   for ( i = 0; i < checkString.length; i++ ) {
      ch = checkString.substring(i, i+1);
      if ( (ch >= "0" && ch <= "9") || (ch == '.') )
         strNewQuantity += ch;
   }

   if ( strNewQuantity.length < 1 )
      strNewQuantity = "1";

   return(strNewQuantity);
}



function cartItem()
{
	this.id = this.name = this.itemURL = this.imgURL = "" ;
	this.opts = new Array() ;
	this.price = this.qty = 0 ;
}


function getItemFromDB(dbStr)
{
	var	strings = new Array ;
	var theItem = new cartItem() ;
	var i, n ;

	if ((!dbStr) || (dbStr == ''))
		return (null) ;

	for (i = n = 0 ; i < 10 ; n = n1 + 1, ++i)
	{
		n1 = dbStr.indexOf("|", n) ;
		if (n1 < 0)
			n1 = dbStr.length ;
		strings[i] = dbStr.substring(n, n1) ;
	}

	theItem.id = strings[0] ;
	theItem.qty = parseInt(strings[1]) ;
	theItem.price = strings[2] ;
	theItem.name = strings[3] ;
	theItem.itemURL = strings[4] ;
	theItem.imgURL = strings[5] ;

	for (i = 0 ; (i < 4) && (strings[i + 6] != '') ; ++i)
		theItem.opts[i] = strings[i + 6] ;

	return (theItem) ;
}



function getDBFromItem(theItem)
{
	var s, i ;

	s = theItem.id + "|" + theItem.qty + "|" + theItem.price + "|" + theItem.name + "|" + theItem.itemURL + "|" + theItem.imgURL ;
	for (i = 0 ; i < 4 ; ++i)
		s += '|' + ((i < theItem.opts.length) ? theItem.opts[i] : '') ;

	return (s) ;
}



function itemcmp(item1, item2)		// returns 0 if items are the same
{
	if ((item1.id == item2.id) && (item1.price == item2.price) && (item1.name == item2.name) && (item1.opts.length == item2.opts.length))
	{
		for (var i = 0 ; i < item1.opts.length ; ++i)
			if (item1.opts[i] != item2.opts[i])
				break ;
		if (i == item1.opts.length)
			return (0) ;
	}
	return (1) ;
}



function itemOptStr(theItem, delim)
{
	var s = "" ;

	for (var i = 0 ; i < theItem.opts.length ; ++i)
		s += theItem.opts[i] + ((i < theItem.opts.length - 1) ? delim : "") ;

	return (s) ;
}

function getItemFromForm(theForm)
{
	var newItem = new cartItem() ;

	newItem.id = theForm.ID_NUM.value ;
	newItem.qty = parseInt(theForm.QUANTITY.value) ;
	newItem.price = parseFloat(theForm.PRICE.value) ;
	newItem.name = theForm.NAME.value;
	newItem.itemURL = theForm.ITEMURL.value ;
	newItem.imgURL = theForm.IMGURL.value ;

	if ( theForm.ADDITIONALINFO != null )
	{
		newItem.opts[0] = theForm.ADDITIONALINFO.options[theForm.ADDITIONALINFO.selectedIndex].text ;
		if ( theForm.ADDITIONALINFO2 != null )
		{
			newItem.opts[1] = theForm.ADDITIONALINFO2.options[theForm.ADDITIONALINFO2.selectedIndex].text;
			if ( theForm.ADDITIONALINFO3 != null )
			{
				newItem.opts[2] = theForm.ADDITIONALINFO3.options[theForm.ADDITIONALINFO3.selectedIndex].text;
				if ( theForm.ADDITIONALINFO4 != null )
					newItem.opts[3] = theForm.ADDITIONALINFO4.options[theForm.ADDITIONALINFO4.selectedIndex].text;
			}
		}
	}

	return (newItem) ;
}


//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {
   var bAlreadyInCart = false;
   var notice = "";
   var prevItem ;
   var newItem ;

   getCartLenFromCookie() ;

   newItem = getItemFromForm(thisForm) ;

	// make sure it is in stock
	invResult = getInventory(newItem.id, itemOptStr(newItem, ', ')) ;
	if ((invResult != 'in stock') && (invResult != 'not found'))
	{
		var s = invResult.split('/') ;

		doOutOfStock(document.getElementById('yesiwantit'), newItem, s[0], (s[1] == 'alt styles avail') ? true : false) ;
		return (false) ;
	}

   //Is this product already in the cart?  If so, increment quantity instead of adding another.
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);

		anItem = getItemFromDB(database) ;
		if (anItem == null)
		{
			fixCart() ;
			return (true) ;
		}

      if (0 == itemcmp(anItem, newItem))
	  {
         bAlreadyInCart = true;
		 anItem.qty += parseInt(newItem.qty) ;
         dbUpdatedOrder = getDBFromItem(anItem) ;
         strNewOrder = "Order." + i;
         DeleteCookie(strNewOrder, "/");
         SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
         notice = newItem.qty + " " + newItem.name + strAdded;
         break;
      }
   }


   if ( !bAlreadyInCart ) {
      iNumberOrdered++;

	 dbUpdatedOrder = getDBFromItem(newItem) ;
	 strNewOrder = "Order." + iNumberOrdered;
	 SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
	 SetCookie("NumberOrdered", iNumberOrdered, null, "/");
	 notice = newItem.qty + " " + newItem.name + strAdded;
   }

   return (true) ;
}


//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
   var base = new Date(0);
   var skew = base.getTime();

   date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie(name)
{
	var re = new RegExp('(^' + name + '=)|(; ' + name + '=)') ;

	if (-1 == (pos = document.cookie.search(re)))
		return (null) ;

	return (unescape(document.cookie.slice(pos).replace(/^[^=]*=/, '').replace(/;.*$/, ''))) ;
}


//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, security   		   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,secure)
{
	var expDate = new Date() ;

	if (!expires)
	{
		expDate.setTime(expDate.getTime() + (1000 * 60 * 60 * 24 * 7)) ;		// default: expires 1 week from now
		expires = expDate ;
	}

	document.cookie = name + "=" + escape (value) +
                     "; expires=" + expires.toGMTString() +
                     ((path) ? "; path=" + path : "") +
                     ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ) {
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}



function deleteAllCookies()
{
	var cookieNames = document.cookie.split(' ') ;
	var	name ;

	for (var i = 0 ; i < cookieNames.length ; ++i)
		if ((name = cookieNames[i].replace(/=.*/, '')) != 'origRef')					// don't delete referer cookie
			DeleteCookie(name, "/", null) ;
}



//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
	
	var i = Math.round(input * 1000) ;
	var s ;

	if (i % 10 > 4)
		i += 10 ;
	s = Math.floor(i / 1000) + '.' ;
	i = Math.floor(i / 10) % 100 ;
	s += (i < 10) ? ('0' + i) : i ;
	return (s) ;
}


//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
   if (1)//( confirm( strRemove ) )
   {
      NumberOrdered = GetCookie("NumberOrdered");
      for ( i=RemOrder; i < NumberOrdered; i++ ) {
         NewOrder1 = "Order." + (i+1);
         NewOrder2 = "Order." + (i);
         database = GetCookie(NewOrder1);
         SetCookie (NewOrder2, database, null, "/");
      }
      NewOrder = "Order." + NumberOrdered;
      SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
      DeleteCookie(NewOrder, "/");
      location.href=location.href;
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    ChangeQuantity                                         ||
// PARAMETERS:  Order Number to Change Quantity                        ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Changes quantity of an item in the shopping cart       ||
//---------------------------------------------------------------------||
function ChangeQuantity(OrderItem,NewQuantity) {

	var	tgtItem ;

	if (isNaN(NewQuantity) || (NewQuantity < 0))
		alert( strErrQty );
	else if (NewQuantity == 0)
		RemoveFromCart(OrderItem) ;
	else
	{
		NewOrder = "Order." + OrderItem;
		database = "";
		database = GetCookie(NewOrder);
		  
		tgtItem = getItemFromDB(database) ;
		g_Subtotal -= tgtItem.qty * tgtItem.price ;
		tgtItem.qty = parseInt(NewQuantity) ;
		g_Subtotal += tgtItem.qty * tgtItem.price ;
		dbUpdatedOrder = getDBFromItem(tgtItem) ;

		strNewOrder = "Order." + OrderItem;
		DeleteCookie(strNewOrder, "/");
		SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
		location.href = location.href ;
	}
}


//---------------------------------------------------------------------||
// FUNCTION:    RadioChecked                                           ||
// PARAMETERS:  Radio button to check                                  ||
// RETURNS:     True if a radio has been checked                       ||
// PURPOSE:     Form fillin validation                                 ||
//---------------------------------------------------------------------||
function RadioChecked( radiobutton ) {
   var bChecked = false;
   var rlen = radiobutton.length;
   for ( i=0; i < rlen; i++ ) {
      if ( radiobutton[i].checked )
         bChecked = true;
   }    
   return bChecked;
} 


//---------------------------------------------------------------------||
// FUNCTION:    QueryString                                            ||
// PARAMETERS:  Key to read                                            ||
// RETURNS:     value of key                                           ||
// PURPOSE:     Read data passed in via GET mode                       ||
//---------------------------------------------------------------------||
QueryString.keys = new Array();
QueryString.values = new Array();
function QueryString(key) {
   var value = null;
   for (var i=0;i<QueryString.keys.length;i++) {
      if (QueryString.keys[i]==key) {
         value = QueryString.values[i];
         break;
      }
   }
   return value;
} 

//---------------------------------------------------------------------||
// FUNCTION:    QueryString_Parse                                      ||
// PARAMETERS:  (URL string)                                           ||
// RETURNS:     null                                                   ||
// PURPOSE:     Parses query string data, must be called before Q.S.   ||
//---------------------------------------------------------------------||
function QueryString_Parse() {
   var query = window.location.search.substring(1);
   var pairs = query.split("&"); for (var i=0;i<pairs.length;i++) {
      var pos = pairs[i].indexOf('=');
      if (pos >= 0) {
         var argname = pairs[i].substring(0,pos);
         var value = pairs[i].substring(pos+1);
         QueryString.keys[QueryString.keys.length] = argname;
         QueryString.values[QueryString.values.length] = value;
      }
   }
}



function getCartLenFromCookie()
{
	if ((null == (iNumberOrdered = GetCookie("NumberOrdered"))) || ('' == iNumberOrdered))
		iNumberOrdered = 0 ;
	return (iNumberOrdered) ;
}



function cartIsEmpty()		// meaning, no items and no gift certificates in cart
{
	return ((iNumberOrdered == 0) && (numGiftCerts == 0)) ;
}



function fixCart()
{
	 // in case cart gets screwed up, delete everything
	 iNumberOrdered = 0 ;
	 SetCookie("NumberOrdered", iNumberOrdered, null, "/");
	 location.href = location.href ;
}



function checkWholesale()
{
	retailerID = GetCookie("retailerID") ;
	if ((retailerID == null) || (retailerID == ''))
	{
		retailerID = null ;
		return (false) ;
	}

	retailerEnforceMins = GetCookie("enforceMins") ;
	retailerBillAddr = GetCookie("retailerBillAddr") ;
	retailerShipAddr = GetCookie("retailerShipAddr") ;

	return (true) ;
}

function meetsWholesaleMins(subtotal, numItems)
{
	if ('true' != retailerEnforceMins)
		return (true) ;
	return (((subtotal < kWholesaleMinTotal) && (numItems < kWholesaleMinItems)) ? false : true) ;
}



function addDiscount(qty, amt, name)
{
	p = new Object ;
	p.qty = qty ;
	p.amount = amt ;
	p.name = name ;
	discounts[discounts.length] = p ;
	discountTotal += qty * amt ;
}



function calcDiscounts()
{
	var anItem ;
	var	qty ;

	// D-VF/S-FL discount
	var	num_D_VF = 0 ;
	var	num_S_FL = 0 ;

	// D-LB/S-TR discount
	var	num_D_LB = 0 ;
	var	num_S_TR = 0 ;

	// PT-TR/S-SL discount
	var	num_PT_TR = 0 ;
	var	num_S_SL = 0 ;

	discounts.length = 0 ;
	discountTotal = 0 ;

	if (getCartLenFromCookie() == 0)
		return ;

	// count various relevant items in cart
	for (var i = 1 ; i <= iNumberOrdered ; ++i)
	{
		if (null == (anItem = getItemFromDB(GetCookie("Order." + i))))
		{
			fixCart() ;
			return ;
		}

		// D-VF/S-FL discount
		if (anItem.id == 'D-VF')
			num_D_VF += anItem.qty ;
		else if (anItem.id == 'S-FL')
			num_S_FL += anItem.qty ;

		// D-LB/S-TR discount
		if (anItem.id == 'D-LB')
			num_D_LB += anItem.qty ;
		else if (anItem.id == 'S-TR')
			num_S_TR += anItem.qty ;

		// PT-TR/S-SL discount
		if (anItem.id == 'PT-TR')
			num_PT_TR += anItem.qty ;
		else if (anItem.id == 'S-SL')
			num_S_SL += anItem.qty ;
	}

	// D-VF/S-FL discount
	if ((qty = Math.min(num_D_VF, num_S_FL)) > 0)
		addDiscount(qty, 9, '"Venus In Furs" / "Fl&uuml;f" combo discount') ;

	// D-LB/S-TR discount
	if ((qty = Math.min(num_D_LB, num_S_TR)) > 0)
		addDiscount(qty, 9, '"Lite Brite" / "Tracer" combo discount') ;

	// PT-TR/S-SL discount
	if ((qty = Math.min(num_PT_TR, num_S_SL)) > 0)
		addDiscount(qty, 10, '"Trixster" / "Slither" combo discount') ;
}


function displayCart(whichScreen)
{
   var fTotal         = 0;    //Total cost of order
   var fTax           = 0;    //Tax amount
   var fShipping      = 0;    //Shipping amount
   var strTotal       = "";   //Total cost formatted as money
   var strTax         = "";   //Total tax formatted as money
   var strShipping    = "";   //Total shipping formatted as money
   var strOutput      = "";   //String to be written to page

   var showGCTaxNote = 0 ;		// flag: show asterisk near each gc price and notice that gc's aren't taxable, only if there is some sales tax

   var anItem ;

   var allowUpdate = (whichScreen == 'viewcart') ? 1 : 0 ;

   g_TotalItems = 0 ;
   g_Taxable = 0 ;

	getGCListFromCookies() ;
	getCartLenFromCookie() ;

	if (cartIsEmpty())
	{
		if (whichScreen != 'viewcart')
			self.location = makeURL('/cart/view.html', false) ;
		return ;
	}

	strOutput = "<TABLE id='cart_tbl' CLASS=\"nopcart\" style='" + ((whichScreen == 'viewcart') ? "margin-left: 60px; " : "") + "float: left'><TR>" ;
	if (whichScreen != 'viewcart')
		strOutput += "<tr><td></td><td width=250 style='width: 250px'></td><td colspan=4></td></tr>" ;

   for ( i = 1; i <= iNumberOrdered; i++ )
   {
		var s ;

		NewOrder = "Order." + i;
		database = "";
		database = GetCookie(NewOrder);
		if (null == (anItem = getItemFromDB(database)))
		{
			fixCart() ;
			return ;
		}

		g_TotalItems += anItem.qty ;

		fTotal += anItem.price * anItem.qty ;

		strOutput += "<TR" + ((whichScreen != 'viewcart') ? " valign=top" : "") + "><TD class=nopentry align=center'>" ;
		if ((anItem.imgURL != "") && (whichScreen == 'viewcart'))
			strOutput += "<a href='" + anItem.itemURL + "'><img src='"  + anItem.imgURL + "'></a>" ;
		else
			strOutput += "<div style='width: 40px'>&nbsp;</div>" ;
		strOutput += "</td>" ;

		s = anItem.name + ((anItem.opts.length > 0) ? (" - <I>" + itemOptStr(anItem, " / ") + "</I>") : "") ;
		if (whichScreen == 'viewcart')
		{
			s = "<a style='color: #777' href='" + anItem.itemURL + "'>" + s + "</a>" ;
			strOutput += "<TD align=center CLASS=\"nopentry\">" + s + "</td>" ;
		}
		else
			strOutput += "<TD style='min-width: 200px' align=right CLASS=\"nopentry\">" + s + "</td>" ;

		strOutput += "<TD CLASS=\"nopentry\">" ;
		if (allowUpdate)
			strOutput += "<INPUT TYPE=TEXT NAME=Q SIZE=2 VALUE=\"" + anItem.qty + "\" onChange=\"ChangeQuantity("+i+", this.value);\">" ;
		else
			strOutput += anItem.qty ;
		strOutput += "</TD>";
		strOutput += "<TD nowrap CLASS=\"nopentry\">"+ MonetarySymbol + moneyFormat(anItem.price) + "/ea</TD>";

		strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER>" ;
		if (allowUpdate)
			strOutput += "<input type=button value=\" "+strRButton+" \" onClick=\"RemoveFromCart("+i+")\">" ;
		strOutput += "</TD></TR>";

		if ( AppendItemNumToOutput ) {
			strFooter = i;
		} else {
			strFooter = "";
		}
	}
	g_Taxable = fTotal ;

	// perhaps list gift certs being purchased
	if ((g_Taxable > 0) && (getTaxRate() > 0) && (whichScreen == 'payment'))
		showGCTaxNote = 1 ;
	for (var i = 0 ; i < numGiftCerts ; ++i)
	{
		var s = '' ;

		strOutput += "<tr valign=top>" ;
		if (allowUpdate)
			strOutput += "<td><a href='/giftcerts.html'><img src='/jpg/i/gift_cart.jpg' width=100 height=98></a></td>" ;
		else
			strOutput += "<td><div style='width: 40px'>&nbsp;</div></td>" ;

		strOutput += "<td class=nopentry align=right>" ;

		strOutput += "Gift certificate to " + (('' != giftCerts[i].recipName) ? giftCerts[i].recipName : giftCerts[i].recipEmail) ;
		if (allowUpdate)
			strOutput += "<br><a href='/giftcerts.html?edit=" + i + "'><span class='tiny'>view / edit</span></a>"

		strOutput += "</td> <td></td> <td class=nopentry>$" + moneyFormat(giftCerts[i].amount) + " " + (showGCTaxNote ? '*' : '') + "</td>" ;

		strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER>" ;
		if (allowUpdate)
			strOutput += "<input type=button value=' " + strRButton + " ' onClick='removeGC(" + i + ")'>" ;
		strOutput += "</TD></TR>";

		fTotal += parseFloat(giftCerts[i].amount) ;
	}

	// perhaps list discounts
	if (checkWholesale())			// no other discounts if this is a wholesale order
	{
		if (meetsWholesaleMins(fTotal, g_TotalItems))
		{
			g_WholesaleDiscAmt = fTotal * (1 - kWholesaleRate) ;
			if (whichScreen == 'viewcart')
				strOutput += '<tr valign=top><td><div style="height: 40px"></div></td><td class=nopentry align=right>' ;
			else
				strOutput += '<tr valign=top><td></td><td class=nopentry align=right>' ;
			strOutput += 'wholesale discount <td> <td class=nopentry>-$' + moneyFormat(g_WholesaleDiscAmt) + '</td><td></td></tr>' ;
			fTotal -= g_WholesaleDiscAmt ;
		}
	}
	else
	{
		calcDiscounts() ;
		for (var i = 0 ; i < discounts.length ; ++i)
		{
			if (whichScreen == 'viewcart')
				strOutput += '<tr valign=top><td><div style="height: 40px"></div></td><td class=nopentry align=center>' ;
			else
				strOutput += '<tr valign=top><td></td><td class=nopentry align=right>' ;
			strOutput += discounts[i].name + '</td><td class=nopentry align=center>' + discounts[i].qty + '</td>' ;
			strOutput += '<td class=nopentry>-$' + moneyFormat(discounts[i].amount) + '/ea</td><td></td></tr>' ;
		}
		fTotal -= discountTotal ;
		g_Taxable -= discountTotal ;
	}

	strTax = moneyFormat(fTax = getTaxRate() * g_Taxable) ;
	strTotal = moneyFormat(fTotal);

	if ((whichScreen == 'viewcart') || (whichScreen == 'checkout'))
		fTax = fShipping = 0 ;
	else
	{
		strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=2 align=right><B>"+strSUB+"</B></TD><td></td>";
		strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2><B>" + MonetarySymbol + strTotal + "</B></TD>";
		strOutput += "</TR>";

		if ( DisplayShippingRow ) {
			strShipping = ((fShipping = getShipCost()) >= 0) ? moneyFormat(fShipping) : '??.??' ;
			strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=2 align=right><B>"+strSHIP+"</B></TD><td></td>";
			strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2><B><span id=shipSpan>" + MonetarySymbol + strShipping + "</span></B></TD>";
			strOutput += "</TR>";
		}

		if (retailerID == null)
		{
			strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=2 align=right><B>"+strTAX+"</B></TD><td></td>";
			strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2><B>";
			strOutput += MonetarySymbol + strTax ;
			strOutput += "</B></TD>";
			strOutput += "</TR>";
		}
	}

	// insert another row if this is the payment screen, so we can use it to perhaps display a credit for a gift cert applied
	if (whichScreen == 'payment')
	{
		strOutput += "<tr id='cartGC_tr' style='display: none'><td class=noptotal colspan=2 align=right><b>gift cert.</b></td><td></td>" ;
		strOutput += "<td class=noptotal colspan=2><b><span id='giftCert_span'></span></b></td></tr>" ;
	}

	strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=2 align=right><B>"+strTOT+"</B></TD><td></td>";
	strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2><B><span id=totalSpan>" ;
	strOutput += MonetarySymbol + ((fShipping < 0) ? '??.??' : moneyFormat(fTotal + fShipping + fTax)) ;
	strOutput += "</span></B></TD></TR>";

	if (numGiftCerts && showGCTaxNote)
		strOutput += "<tr><td colspan=4 class=noptotal align=right><br>&nbsp;<span class='tiny'>* gift certificates are non-taxable</span></td><td></td></tr>" ;
	else if ((whichScreen != 'payment') && retailerID && (g_WholesaleDiscAmt == 0) && !meetsWholesaleMins(fTotal, g_TotalItems))
		strOutput += "<tr><td colspan=5 class=noptotal align=right><br>&nbsp;Add <b>" + (kWholesaleMinItems - g_TotalItems) +
						"</b> items or <b>$" + moneyFormat(kWholesaleMinTotal - fTotal) + "</b> to your cart to receive the wholesale discount.</tr>" ;

	strOutput += "</TABLE>";

	g_Subtotal = fTotal ;
	g_Tax = fTax ;
	g_TotalCost = (fTotal + fShipping + fTax);

	if (whichScreen != "justCalculate")
	{
		document.write(strOutput);
		document.close();
	}
}

//---------------------------------------------------------------------||
//---------------------------------------------------------------------||
// FUNCTION:    ManageCart                                             ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//---------------------------------------------------------------------||
function ManageCart( ) {
	displayCart('viewcart') ;
}

function writeCartGreeting()
{
	var s = '' ;

	getGCListFromCookies() ;
	getCartLenFromCookie() ;

	if (!cartIsEmpty())
		return ;
	s += "There's nothing in your cart. So there's lots of room to buy all kinds<br>of <a href='garb/index.html'>great IlanioWear</a>!" ;
	s += "<br>&nbsp;<br>" ;
	s += "To continue browsing, you can click the <b>Back</b> button on your browser." ;
	document.write(s) ;
}


//=====================================================================||
//               END NOP Design SmartPost Shopping Cart                ||
//=====================================================================||


var addrFieldNames	= new Array("country", "first", "last", "addr", "addr2", "city", "state", "zip", "phone", "fax", "email") ;

var	usStateCodes	= new Array("AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY") ;

//var countryCodes	  = new Array("AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "AG", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "TC", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CK", "CR", "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "TP", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "WF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "BA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "SJ", "JP", "JO", "KZ", "KE", "KI", "KR", "KP", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "HM", "MX", "FM", "PM", "MD", "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN", "NT", "KN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "ST", "PR", "QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "GS", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "VC", "TT", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UY", "UM", "UZ", "VU", "VA", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "YU", "ZR", "ZW") ;
//var countryNames	  = new Array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Barbuda", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Trty.", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Caicos Islands", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Cook Islands", "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Futuna Islands", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard", "Herzegovina", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Jan Mayen Islands", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea", "Korea (Democratic)", "Kuwait", "Kyrgystan", "Lao", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mc Donald Islands", "Mexico", "Micronesia", "Miquelon", "Moldova", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "Neutral Zone", "Nevis", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Principe", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Kitts", "Saint Lucia", "Saint Pierre", "Saint Vincent", "Samoa", "San Marino", "Sao Tome", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia", "South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Grenadines", "Tobago", "Togo", "Tokelau", "Tonga", "Trinidad", "Tunisia", "Turkey", "Turkmenistan", "Turks Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "US Minor Outlying Islands", "Uzbekistan", "Vanuatu", "Vatican City State", "Venezuela", "Viet Nam", "Virgin Islands (British)", "Virgin Islands (US)", "Wallis", "Western Sahara", "Yemen", "Yugoslavia", "Zaire", "Zimbabwe") ;

// note: when we add countries below, we also need to add them to cgi-bin/getShipCosts.sh
var countryCodes	= new Array("AU", "AT", "BS", "BE", "BR", "CA", "DK", "FI", "FR", "DE", "GR", "GL", "IS", "IE", "IT", "JP", "LU", "MX", "NL", "NZ", "NO", "PL", "PT", "PR", "ES", "SE", "CH", "GB", "US") ;
var countryNames	= new Array("Australia", "Austria", "Bahamas", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Greece", "Greenland", "Iceland", "Ireland", "Italy", "Japan", "Luxembourg", "Mexico", "Netherlands", "New Zealand", "Norway", "Poland", "Portugal", "Puerto Rico", "Spain", "Sweden", "Switzerland", "United Kingdom", "United States") ;

var gcFieldNames	= new Array("amount", "recipName", "recipEmail", "msg", "senderName") ;

var formErrMsg			= "Sorry... some fields are missing or invalid. Please correct the fields marked in red." ;
var gotFormErr			= false ;



function ilanioInit()
{
	var rollover = new Image() ;

	// preload any rollover images
	rollover.src = '/i/yesiwantit_black.jpg' ;
}



function handleKeypress(evt)
{
	var target ;
	var charCode ;
	
	if (evt && evt.which)
	{
		charCode = evt.which ;
		target = evt.target ;
	}
	else
	{
		charCode = event.keyCode ;
		target = evt.srcElement ;
	}
		
	if (target.nodeType == 3)			// defeat Safari bug
		target = target.parentNode ;

	return (((charCode == 13) && ((target.type == 'text') || (target.type == 'select-one') || (target.type == 'select-multiple'))) ? false : true) ;
}


function displayCartButtons()
{
	// return ;		// no checkout buttons while store is closed

	if (cartIsEmpty())
		return ;
	document.write('<INPUT TYPE=submit value="update cart" onClick="recalculate(); return false;">') ;
	document.write('&nbsp;&nbsp;&nbsp;<input type=submit value=checkout onClick="self.location = makeURL(\'/cart/checkout.html\', true) ; return false ;">') ;
	document.close() ;
}



function displayCountryMenu(tgtCountry)
{
	if ((tgtCountry == null) || (tgtCountry == ''))
		tgtCountry = "US" ;
	if (countryNames.length != countryCodes.length)
		alert("System error: different number of country names and code") ;
	for (i = 0 ; i < countryNames.length ; ++i)
		document.write("<option value='" + countryCodes[i] + "'" + ((countryCodes[i] == tgtCountry) ? " selected>" : ">") + countryNames[i] + "</option>") ;
	document.close() ;
}



function getShipCost()
{
	var x ;

	if ((null != (x = GetCookie("shipMethod"))) && (x != ''))
		return (parseFloat(x.replace(/^[^\/]*\//, ''))) ;
	return (-1) ;
}



function getTaxRate()
{
	var theAddr = getAddrFromCookie("s") ;

	if (retailerID != null)
		return (0) ;

	if (theAddr.empty)
		theAddr = getAddrFromCookie("b") ;
	if ((theAddr.country == "US") && (theAddr.state == "CA"))
		return ((theAddr.city.search(/San *Francisco/i) >= 0) ? kSFTaxRate : kCATaxRate) ;

	return (0) ;
}



function recalculate()
{
	self.location = self.location ;
}



function shipMethod(name, isDomestic, time, baseOrder, baseCost, addlOrderPct)
{
	this.name = name ;
	this.isDomestic = isDomestic ;
	this.time = time ;
	this.baseOrder = baseOrder ;
	this.baseCost = baseCost ;
	this.addlOrderPct = addlOrderPct ;
}



function address()
{
	this.first = this.last = this.addr = this.addr2 = this.city = this.state = this.zip = this.phone = this.fax = this.email = "" ;
	this.country = "US" ;
	this.prefix = "" ;
	this.error = false ;
	this.form = null ;
	this.empty = true ;
}



function getAddrFromForm(theForm, prefix)
{
	var theAddr = new address() ;
	
	theAddr.prefix = prefix ;
	theAddr.form = theForm ;
	theAddr.empty = true ;

	for (var i = 0 ; i < addrFieldNames.length ; ++i)
	{
		inputValue = eval('theForm.' + prefix + '_' + addrFieldNames[i] + '.value') ;
		eval('theAddr.' + addrFieldNames[i] + ' = inputValue ;') ;
		if ((inputValue != null) && (inputValue != "") && (addrFieldNames[i] != 'country'))
			theAddr.empty = false ;
	}

	cleanUpAddr(theAddr) ;

	return (theAddr) ;
}



function setFormFromAddr(theForm, theAddr)
{
	// set the country first to set the menu before filling in all the other form fields
	eval('theForm.' + theAddr.prefix + '_country.value = theAddr.country ;') ;
	if (theAddr.country != "US")
		changedCountry(eval('theForm.' + theAddr.prefix + "_country")) ;

	for (var i = 0 ; i < addrFieldNames.length ; ++i)
	{
		name = addrFieldNames[i] ;
		eval('theForm.' + theAddr.prefix + '_' + name + '.value = theAddr.' + name + ' ;') ;
	}
}



function stripPipeChar(str)
{
	return (str.replace(/\|/g, '')) ;
}



function saveAddrInCookie(theAddr)
{
	cookieName = theAddr.prefix + "_addr" ;
	cookieStr = "" ;
	for (var i = 0 ; i < addrFieldNames.length ; ++i)
		cookieStr += stripPipeChar(eval('theAddr.' + addrFieldNames[i])) + '|' ;

	SetCookie(cookieName, cookieStr, null, "/", true) ;
}



function getAddrFromCookie(prefix)
{
	var theAddr = new address() ;
	var	fields = new Array() ;

	theAddr.prefix = prefix ;
	cookieStr = GetCookie(prefix + "_addr") ;
	if (cookieStr && (cookieStr != ""))
	{
		fields = cookieStr.split('|') ;
		for (var i = 0 ; i < addrFieldNames.length ; ++i)
		{
			eval('theAddr.' + addrFieldNames[i] + ' = fields[i] ;') ;
			if ((fields[i] != null) && (fields[i] != "") && (addrFieldNames[i] != 'country'))
				theAddr.empty = false ;
		}
	}

	return (theAddr) ;
}



function getAddrHTMLStr(theAddr)
{
	var s = "" ;

	s += '<span style="font-size: 15px; letter-spacing: 0em">' + theAddr.first + ' ' + theAddr.last + '<br>' + theAddr.email + '<br>' ;
	if (theAddr.country == 'US')
		s += niceUSPhoneNumberStr(theAddr.phone) + '<br>' ;
	else
		s += theAddr.phone + '<br>' ;
	s += theAddr.addr + '<br>' ;
	if (theAddr.addr2.length)
		s += theAddr.addr2 + '<br>' ;
	s += theAddr.city + ', ' + theAddr.state + ' ' + theAddr.zip ;
	if (theAddr.country != 'US')
		for (var i = 0 ; i < countryCodes.length ; ++i)
			if (countryCodes[i] == theAddr.country)
			{
				s += '<br>' + countryNames[i] ;
				break ;
			}
	s += '</span>' ;

	return (s) ;
}



function displayAddrInfo(whichScreen)
{
	var theComment = GetCookie("comment") ;
	var s = '' ;

	billAddr = getAddrFromCookie("b") ;
	shipAddr = getAddrFromCookie("s") ;

	if (shipAddr.empty)
		s += '<tr valign=top><td colspan=2><span class="greetext">Bill & ship to:</span><p>' + getAddrHTMLStr(billAddr) + '</td></tr>' ;
	else
	{
		s += '<tr valign=top><td><span class="greetext">Bill to:</span><p>'  + getAddrHTMLStr(billAddr) + '</td>' ;
		s += '<td><span class="greetext">Ship to:</span><p>'  + getAddrHTMLStr(shipAddr) + '</td></tr>' ;
	}

	// comments field
	if ((theComment != null) && (theComment != '') && (theComment != '\n'))
		s += '<tr><td colspan=2><br>' + theComment + '<td></tr>' ;

	document.write(s) ;
	document.close() ;
}



function reportAddrErr(theAddr, fieldName, isError)
{
	if ((fieldName == "first") || (fieldName == "last"))
		fieldName = "name" ;
	errID = theAddr.prefix + "_" + fieldName ;

	document.getElementById(errID).style.color = isError ? 'red' : '#777' ;

	if (isError)
	{
		if (!theAddr.error)
		{
			theDiv = document.getElementById("checkoutErrors") ;
			while (theDiv.childNodes.length > 0)
				theDiv.removeChild(theDiv.childNodes[0]) ;
			theP = document.createElement("P") ;
			theDiv.appendChild(theP) ;
			setInnerHTML(theP, formErrMsg) ;
		}
		theAddr.error = true ;
	}
}



function validateCheckout(theForm)
{
	billAddr = getAddrFromForm(theForm, "b") ;
	saveAddrInCookie(billAddr) ;

	shipAddr = getAddrFromForm(theForm, "s") ;
	saveAddrInCookie(shipAddr) ;

	if (validateAddr(billAddr) && (shipAddr.empty || validateAddr(shipAddr)))
		self.location = '/cart/payment.html' ;

	return (false) ;
}



function capitalize(str)
{
	return (str.length ? (str.charAt(0).toUpperCase() + str.slice(1)) : str) ;
}



function niceUSPhoneNumberStr(str)
{
	var s = str.replace(/[^0-9]*/g, '') ;
	var retval = '' ;

	s = s.replace(/^1/, '') ;

	retval += '(' + s.slice(0, 3) + ') ' + s.slice(3, 6) + '-' + s.slice(6, 10) ;
	if (s.length > 10)
		retval += ' x' + s.slice(10) ;

	return (retval) ;
}



function cleanUpAddr(theAddr)
{
	if (theAddr.empty)
		return ;
	//theAddr.first = capitalize(theAddr.first) ;
	//theAddr.last = capitalize(theAddr.last) ;
	//theAddr.addr = capitalize(theAddr.addr) ;
	//theAddr.addr2 = capitalize(theAddr.addr2) ;
	//theAddr.city = capitalize(theAddr.city) ;
	if (theAddr.country == 'US')
		theAddr.state = theAddr.state.toUpperCase() ;
	//else
		//theAddr.state = capitalize(theAddr.state) ;
}



function isGoodUSPhoneNumber(str)
{
	var s = str.replace(/[^0-9]*/g, '') ;
	s = s.replace(/^1/, '') ;
	return (s.length >= 10) ;
}



function validateAddr(theAddr)
{
	var reqFieldNames = new Array("country", "first", "last", "addr", "city", "state", "zip", "phone", "email") ;
	var	foundErr = false ;

	// clear to noerr first
	for (i = 0 ; i < addrFieldNames.length ; ++i)
		reportAddrErr(theAddr, addrFieldNames[i], false) ;
		
	for (i = 0 ; i < reqFieldNames.length ; ++i)
		if ("" == (theField = eval("theAddr." + reqFieldNames[i])))
			if ((theAddr.country == "US") || ((reqFieldNames[i] != "state") && (reqFieldNames[i] != "zip")))	// state, zip not reqd for intl addresses
				reportAddrErr(theAddr, reqFieldNames[i], true) ;

	s = theAddr.email.split('@') ;
	if ((s.length < 2) || (s[1].split('.').length < 2))
		reportAddrErr(theAddr, "email", true) ;

	if (theAddr.country == 'US')
	{
		if (!isGoodUSPhoneNumber(theAddr.phone))
			reportAddrErr(theAddr, "phone", true) ;
		if ((theAddr.fax.length > 0) && !isGoodUSPhoneNumber(theAddr.fax))
			reportAddrErr(theAddr, "fax", true) ;
		for (i = 0 ; i < usStateCodes.length ; ++i)
			if (theAddr.state == usStateCodes[i])
				break ;
		if (i == usStateCodes.length)
			reportAddrErr(theAddr, "state", true) ;
		if (theAddr.zip.search(/[^-0-9 ]/) >= 0)
			reportAddrErr(theAddr, "zip", true) ;
		else
		{
			var s = theAddr.zip.replace(/[^0-9]*/g, '') ;
			if ((s.length != 5) && (s.length != 9))
				reportAddrErr(theAddr, "zip", true) ;
		}
	}

		

	return (!theAddr.error) ;
}



function giftCertificate(amount, recipName, recipEmail, message, senderName)
{
	this.amount = amount ;
	this.recipName = recipName ;
	this.recipEmail = recipEmail ;
	this.msg = message ;
	this.senderName = senderName ;
}



function saveGCInCookie(theGC, index)
{
	cookieName = "giftCert_" + index ;
	cookieStr = "" ;
	for (var i = 0 ; i < gcFieldNames.length ; ++i)
		cookieStr += stripPipeChar(eval('theGC.' + gcFieldNames[i])) + '|' ;

	SetCookie(cookieName, cookieStr, null, "/", false) ;
}



function getGCFromCookie(index)
{
	var theGC = new giftCertificate() ;
	var	fields = new Array() ;

	cookieStr = GetCookie("giftCert_" + index) ;
	if (cookieStr && (cookieStr != ""))
	{
		fields = cookieStr.split('|') ;
		for (var i = 0 ; i < gcFieldNames.length ; ++i)
			eval('theGC.' + gcFieldNames[i] + ' = fields[i] ;') ;
		return (theGC) ;
	}

	return (null) ;
}



function saveGCListInCookies()
{
	for (var i = 0 ; i < numGiftCerts ; ++i)
		saveGCInCookie(giftCerts[i], i) ;
	SetCookie("numGiftCerts", numGiftCerts, null, "/", false) ;
}



function getGCListFromCookies()
{
	var	x ;

	numGiftCerts = 0 ;
	if ((null != (x = GetCookie("numGiftCerts"))) && (x != ''))
	{
		numGiftCerts = parseInt(x) ;
		for (var i = 0 ; i < numGiftCerts ; ++i)
			if (null == (giftCerts[i] = getGCFromCookie(i)))
				break ;
		numGiftCerts = i ;
	}

	// if logged in as a retailer, delete all gift certs
	if (checkWholesale() && (numGiftCerts > 0))
	{
		numGiftCerts = 0 ;
		saveGCListInCookies() ;
	}
}



function addGCToCart(theForm)
{
	var theGC = new giftCertificate() ;
	var	x ;

	getGCListFromCookies() ;

	theGC.amount = theForm.amount.value ;
	theGC.recipName = theForm.recipientName.value ;
	theGC.recipEmail = theForm.recipientEmail.value ;
	theGC.msg = theForm.message.value.replace(/[<>]/g, '') ;		// strip any html in message
	theGC.senderName = theForm.senderName.value ;

	if ('' != (x = theForm.origGCIndex.value))		// if we're updating an existing gift cert
		giftCerts[parseInt(x)] = theGC ;
	else											// if we're adding a new one
		giftCerts[numGiftCerts++] = theGC ;

	saveGCListInCookies() ;

	return (true) ;
}



function removeGC(index)
{
	if (index >= numGiftCerts)
		return ;
	giftCerts.splice(index, 1) ;
	--numGiftCerts ;
	saveGCListInCookies() ;
	self.location.href = self.location.href ;
}



function initCheckoutForm(theForm)
{
	var theComment = GetCookie("comment") ;
	var refererType = GetCookie("refererType") ;
	var newsEmail = GetCookie("newsEmail") ;
	var usedBoxOK = GetCookie("usedBoxOK") ;

	setFormFromAddr(theForm, getAddrFromCookie("b")) ;
	setFormFromAddr(theForm, getAddrFromCookie("s")) ;

	theForm.comment.value = (theComment ? theComment : "") ;
	if (newsEmail && (newsEmail != ''))
	{
		theForm.wantsNews.checked = true ;
		theForm.newsEmail.value = newsEmail ;
	}

	if (usedBoxOK == 'true')
		theForm.usedBoxOK.checked = true ;

	theSel = theForm.refererType ;
	if (refererType && (refererType != ''))
	{
		for (var i = 0 ; i < theSel.options.length ; ++i)
			if (theSel.options[i].text == refererType)
				theSel.selectedIndex = i ;
	}
	else
		theSel.selectedIndex = 0 ;
}



function saveCheckoutInfo(theForm)
{
	saveAddrInCookie(getAddrFromForm(theForm, "b")) ;
	saveAddrInCookie(getAddrFromForm(theForm, "s")) ;
	SetCookie("comment", theForm.comment.value, null, "/", true) ;
	SetCookie("newsEmail", theForm.newsEmail.value, null, "/", true) ;
	SetCookie("usedBoxOK", theForm.usedBoxOK.checked, null, "/", true) ;

	theSel = theForm.refererType ;
	SetCookie("refererType", theSel.options[theSel.selectedIndex].text, null, "/", true) ;
}



function clearShipAddr(theForm)
{
	saveCheckoutInfo(theForm)
	DeleteCookie("s_addr", "/") ;
	initCheckoutForm(theForm) ;
}



function disableShipFields(theForm)		// not currently used
{
	for (var i = 0 ; i < addrFieldNames.length ; ++i)
	{
		name = addrFieldNames[i] ;
		eval('theForm.s_' + name + '.disabled = true ;') ;
	}
	theForm.clearBtn.disabled = true ;
	theForm.usedBoxOK.disabled = true ;
}



function changedCountry(theSel)
{
	intl = (theSel.value == 'US') ? 0 : 1 ;
	prefix = theSel.name.charAt(0) ;

	stateTD = document.getElementById(prefix + "_state") ;
	stateInput = document.getElementById(prefix + "_state_input") ;
	stateExpl = document.getElementById(prefix + "_state_expl") ;
	zipTD = document.getElementById(prefix + "_zip") ;

	if (intl)
	{
		setInnerHTML(stateTD, "state/province:") ;
		stateInput.size = 20 ;
		stateInput.maxLength = 20 ;
		setInnerHTML(zipTD, "postal code:") ;
		explStr = "" ;
	}
	else
	{
		setInnerHTML(stateTD, "state:") ;
		stateInput.size = 2 ;
		stateInput.maxLength = 2 ;
		setInnerHTML(zipTD, "zip:") ;
		explStr = " (use 2-letter state code)" ;
	}

	delObjChildren(parTD = stateInput.parentNode) ;
	parTD.appendChild(stateInput) ;
	setInnerHTML(stateExpl, explStr) ;
	parTD.appendChild(stateExpl) ;
}



function getShipParamStr(theAddr, totalValue, numItems)
{
	var value = '' + totalValue ;
	var	s, styleID ;
	var anItem ;

	s = theAddr.country + '+' + theAddr.zip.replace(/ /g, '_') + '+' + theAddr.city.replace(/ /g, '_') + '+' + value.replace(/\..*/, '')
			+ '+' + numItems ;

	if (0 == getCartLenFromCookie())
		return (s) ;

	// list all items and quantities
	for (var i = 1 ; i <= iNumberOrdered ; ++i)
		if (null != (anItem = getItemFromDB(GetCookie("Order." + i))))
			if (null != (styleID = getStyleIDForItem(anItem)))
				s += '+' + styleID + '/' + anItem.qty ;

	return (s) ;
}



function reportPaytErr(fieldName, isError)
{
	document.getElementById(fieldName).style.color = isError ? 'red' : '#777' ;

	if (isError)
	{
		gotFormErr = true ;
		theDiv = document.getElementById("paymentErrors") ;
		if (theDiv.childNodes.length == 0)
			setInnerHTML(theDiv, formErrMsg) ;
	}
}



function mod10Check(number)
{
	var i, j, sum ;

	for (i = number.length - 1, sum = 0 ; i >= 0 ; i -= 2)
	{
		sum += parseInt(number.charAt(i)) ;
		if (i > 0)
		{
			j = parseInt(number.charAt(i - 1)) ;
			sum += ((j * 2 >= 10) ? (j * 2 - 9) : (j * 2)) ;
		}
	}
	return (sum % 10 == 0) ;
}



function checkCCNo(ccNum, ccType)
{
	if ((ccNum.search(/[^0-9]/gi) >= 0) || (!mod10Check(ccNum)))         // must be all digits
		return (false) ;

	if (ccType == 'amex')
	{
		if ((ccNum.length != 15) || (((s = ccNum.substr(0, 2)) != '34') && (s != '37')))
			return (false) ;
	}
	else if (ccType == 'visa')
	{
		if (((ccNum.length != 13) && (ccNum.length != 16)) || (ccNum.charAt(0) != '4'))
			return (false) ;
	}
	else if (ccType == 'mastercard')
	{
		if ((ccNum.length != 16) || ((i = parseInt(ccNum.substr(0, 2))) < 51) || (i > 55))
			return (false) ;
	}
	else
		return (false) ;				// should really never get here

	return (true) ;
}



function validatePayment(theForm)
{
	var s ;
	var i ;

	// first get info from form
	var ccType = document.paymentForm.paymentMethod.value ;
	var ccNo = document.paymentForm.ccNumber.value.replace(/[- ]/gi, '') ;				// delete spaces & dashes
	var ccMonth = parseInt(document.paymentForm.ccMonth.value.replace(/^0/, '')) ;		// remove leading 0
	var ccYear = parseInt(document.paymentForm.ccYear.value.replace(/^0/, '')) ;		// remove leading 0
	var ccCVV = document.paymentForm.ccCVV.value.replace(/[- ]/gi, '') ;				// delete spaces & dashes

	// clear any preexisting errors
	gotFormErr = false ;
	reportPaytErr('cardNumber', false) ;
	reportPaytErr('expDate', false) ;
	reportPaytErr('cvvCode', false) ;

	// check exp date
	var curDate = new Date() ;
	var curYear = curDate.getFullYear() ;
	var curMonth = 1 + curDate.getMonth() ;
	if (ccYear < 100)
		ccYear += 2000 ;
	if (isNaN(ccMonth) || isNaN(ccYear) || (ccMonth < 1) || (ccMonth > 12) || (ccYear < curYear) || (ccYear > 2030)
			|| ((ccYear == curYear) && (ccMonth < curMonth)))
		reportPaytErr('expDate', true) ;

	// check cvv code
	if ((ccCVV.search(/[^0-9]/gi) >= 0)			// must be all digits
			|| (ccCVV.length != ((ccType == 'amex') ? 4 : 3)))
		reportPaytErr('cvvCode', true) ;

	// check cc no
	if (!checkCCNo(ccNo, ccType))
		reportPaytErr('cardNumber', true) ;
	
	if (gotFormErr)
		return (false) ;

	// reset form values to processed ones before submitting
	document.paymentForm.ccNumber.value = ccNo ;
	document.paymentForm.ccMonth.value = ccMonth ;
	document.paymentForm.ccYear.value = ccYear ;
	document.paymentForm.ccCVV.value = ccCVV ;

	// erase error text
	delObjChildren(document.getElementById("paymentErrors")) ;

	return (true) ;
}



function hiddenHTML(name, value)
{
	if (!value)
		value = '' ;
	return ("<input type=hidden name='" + name + "' value='" + value.replace(/'/g, "&#39;") + "'>") ;
}



function cartDataHTML()
{
	var s = "" ;
	var numItems = GetCookie("NumberOrdered") ;
	var anItem ;

	for (var i = 0 ; i < numItems ; ++i)
	{
		database = GetCookie("Order." + i + 1) ;
		if (null == (anItem = getItemFromDB(database)))
			break ;

		s += hiddenHTML("item" + i + "id", anItem.id) ;
		s += hiddenHTML("item" + i + "name", anItem.name) ;
		s += hiddenHTML("item" + i + "price", anItem.price) ;
		s += hiddenHTML("item" + i + "qty", anItem.qty) ;
		for (var j = 0 ; j < anItem.opts.length ; ++j)
			s += hiddenHTML("item" + i + "opt" + j, anItem.opts[j]) ;
	}
	return (s) ;
}



function addrFormHTML(theAddr)
{
	var s = "" ;

	for (var i = 0 ; i < addrFieldNames.length ; ++i)
		s += hiddenHTML(theAddr.prefix + "_addr_" + addrFieldNames[i], eval('theAddr.' + addrFieldNames[i])) ;
	return (s) ;
}



function authFormDataHTML()
{
	var	s = "" ;

	s += cartDataHTML() ;
	s += addrFormHTML(getAddrFromCookie("b")) ;
	s += addrFormHTML(getAddrFromCookie("s")) ;
	s += hiddenHTML("comment", GetCookie("comment")) ;
	return (s) ;
}



//////////////////////////////////////
//                                  //
//      inventory management        //
//                                  //
//////////////////////////////////////

var invDiv ;
var	invDivPct = 0 ;
var	invCtrX, invCtrY ;
var invTgtCtrX, invTgtCtrY ;
var invDivFullWidth = 438 ;
var invDivFullHeight = 243 ;
var dontAnimate = 0 ;

function handleUnload()
{
	if (invDivPct > 0)			// out of stock alert div is open
		finishInvDivShrink() ;
}

function writeInventoryDiv()
{
	document.write("		<div id='inventory' style='position: absolute; top: 0px; z-index: 20; width: 440px; height: 243px; visibility: hidden'>") ;
	document.write("			<img id='inv_bkg' src='i/outofstock.gif' width=438 height=243 style='position: absolute; visibility: hidden'>") ;
	document.write("			<div id='inv_contents' style='position: absolute; top: -500px; left: -500px; z-index: 2; width: 360px; height: 223px; text-align: center; visibility: hidden'>") ;
	document.write("				<div style='height: 10px'></div>") ;
	document.write("				<b>Sorry!</b><br>") ;
	document.write("				<span class='text2'>") ;
	document.write("					<div id='outofstock_msg' style='position: relative; top: 8px'></div>") ;
	document.write("				</span>") ;
	document.write("				<div style='position: absolute; top: 140px; left: 70px'>") ;
	document.write("					<form name='invDivForm' onSubmit='submitInvForm(); return false;'>") ;
	document.write("						<span id='inv_notify_span' class='text2'><input type=checkbox name=ckbx>email me at: <input type=text size=18 name=notifyEmail></span>") ;
	document.write("						<div style='height: 10px'></div>") ;
	document.write("						<input type='submit' value='close'>") ;
	document.write("					</form>") ;
	document.write("				</div>") ;
	document.write("			</div>") ;
	document.write("		</div>") ;
}

function doOutOfStock(srcObj, theItem, invResult, altOptsAvail)
{
	var str = '' ;
	var theForm = document.orderForm ;
	var theSel ;

	// don't animate for firefox -- it's jittery for some reason
    var agt = navigator.userAgent.toLowerCase() ;
	dontAnimate = (agt.indexOf('firefox') > -1) ? 1 : 0 ;

	invDiv = document.getElementById('inventory') ;
	invDiv.style.visibility = 'visible' ;
	invSrcObj = srcObj ;

	// first set up the message we're going to display
	str += "The " + theItem.name ;
	if (theItem.opts.length)
		str += ' - ' + itemOptStr(theItem, " / ") ;
	str += ' is currently out of stock' ;
	if (invResult == 'gone forever')
	{
		str += ", and sadly, we can't make any more of them! " ;
		document.getElementById('inv_notify_span').style.visibility = 'hidden' ;
	}
	else
		str += ". " ;
	if (altOptsAvail)
		str += "(However, we do have it in other styles.) " ;
	if (invResult != 'gone forever')
		str += "If you like, we can notify you by email when it's available." ;
	setInnerHTML(document.getElementById('outofstock_msg'), str) ;

	// then try to fill in notification email
	var email = GetCookie('notifyEmail') ;
	document.invDivForm.ckbx.checked = false ;
	if (email && (email != ''))
	{
		document.invDivForm.notifyEmail.value = email ;
		document.invDivForm.ckbx.checked = true ;
	}

	// figure out where current center of element clicked on is
	xy = getEltPos(srcObj, false).split(',') ;
	invCtrX = parseInt(xy[0]) + srcObj.offsetWidth / 2 ;
	invCtrY = parseInt(xy[1]) + srcObj.offsetHeight / 2 ;

	// get visible rect of screen
	scrollRect = getScrollRect().split(',') ;

	// finally, get target center (eventual center of div when zoom is finished)
	invTgtCtrX = invCtrX, invTgtCtrY = invCtrY ;
	divLeft = invCtrX - invDivFullWidth / 2 ;
	if (0 > (x = divLeft - parseInt(scrollRect[0]) - 10))							// less than 0 if we need to move the center
		invTgtCtrX -= x ;
	divBottom = invCtrY + invDivFullHeight / 2 ;
	if (0 < (y = divBottom - parseInt(scrollRect[3]) + 10))							// greater than 0 if we need to move the center
		invTgtCtrY -= y ;
	//invTgtCtrY = invCtrY - parseInt(invDiv.style.height) / 2 ;					// uncomment to have div appear above src obj

	// if this is msie, hide any "selects"
	if (isMSIE)
		showHideSelects(false) ;

	animateInvDiv(1) ;
}

function showHideSelects(show)
{
	selectList = document.getElementsByTagName('SELECT') ;
	for (var i = 0 ; i < selectList.length ; ++i)
		selectList[i].style.visibility = (show ? 'visible' : 'hidden') ;
}

function finishInvDivBlowUp()
{
	obj = document.getElementById('inv_contents') ;
	obj.style.top = '13px' ;
	obj.style.left = '40px' ;
	obj.style.visibility = 'visible' ;

	invDivPct = 100 ;
}

function submitInvForm()
{
	var obj = document.getElementById('inv_contents') ;
	obj.style.visibility = 'hidden' ;
	obj.style.top = '-500px' ;
	obj.style.left = '-500px' ;

	var theForm = document.orderForm ;
	var email = document.invDivForm.notifyEmail.value ;
	var s = email.split('@') ;
	if ((s.length < 2) || (s[1].split('.').length < 2) || (!document.invDivForm.ckbx.checked))
		email = '' ;
	SetCookie('notifyEmail', email, null, '/') ;
	document.invDivForm.notifyEmail.value = email ;
	if (email != '')
	{
		var theItem = getItemFromForm(theForm) ;
		params = "email=" + escape(email) + "&itemID=" + escape(theItem.id) ;
		if (theItem.opts.length)
			params += "&opts=" + escape(itemOptStr(theItem, ", ")) ;
		doXMLReq("/cgi/addNotify.sh", "GET", params) ;
	}
	
	animateInvDiv(-1) ;
}

function finishInvDivShrink()
{
	var theImg = document.getElementById('inv_bkg') ;
	invDiv.style.visibility = 'hidden' ;
	invDiv.style.top = invDiv.style.left = '0px' ;
	theImg.style.visibility = 'hidden' ;

	// if this is msie, re-show any "selects"
	if (isMSIE)
		showHideSelects(true) ;

	invDivPct = 0 ;
}

function animateInvDiv(dir)
{
	var theImg = document.getElementById('inv_bkg') ;
	var ms ;

	// for firefox and slow machines, just jump to full size
	if (dontAnimate)
		invDivPct = ((dir > 0) ? 100 : 0) ;
	else
		invDivPct += 17 * dir ;

	if (invDivPct <= 0)
	{
		finishInvDivShrink() ;
		return ;
	}
	invDivPct = Math.min(invDivPct, 100) ;

	ms = (new Date()).getTime() ;

	theImg.width = invDivFullWidth * invDivPct / 100 ;
	theImg.height = invDivFullHeight * invDivPct / 100 ;
	invDiv.style.width = theImg.width + 'px' ;
	invDiv.style.height = theImg.height + 'px' ;
	invDiv.style.left = ((invCtrX + (invTgtCtrX - invCtrX) * invDivPct / 100) - theImg.width / 2) + 'px' ;
	invDiv.style.top = ((invCtrY + (invTgtCtrY - invCtrY) * invDivPct / 100) - theImg.height / 2) + 'px' ;
	theImg.style.visibility = 'visible' ;

	ms = (new Date()).getTime() - ms ;
	if (ms > 6)
		dontAnimate = 1 ;

	if (invDivPct >= 100)
		finishInvDivBlowUp() ;
	else
		setTimeout('animateInvDiv(' + dir + ')', (ms > 4) ? 0 : 30) ;
}




