// main javascript file for processing WAHOO Games order.
//
// Modification Text:
//
// m015 2010/02/28 Added support for Moonlight Creations boards.
// 
// m014 2006/12/23 Added code to better support PayPal payments.
// 
// m013 2006/08/19 Added KK boards with images.
//
// m012 2005/12/02 Changed ZIP processing to accept only 5 digits.
//
// m011 2005/11/09 Add Oden's wooden boards.
//
// m010 2005/11/02 Change for godaddy.com web hosting.
//
// m009 2002/06/02 Implemented changes for secure credit card page.
//
// m008 2001/12/20 Remove Pocket WAHOO references.
//               Implement Sales Tax code.
//               Remove external references for secure server. 
//
// m007 2000/12/07 Add small postage charge for accessories.
//               Round shipping charges up to nearest quarter.
//
// m006 2000/12/04 Add "Ship to:" fields and sales tax calculation.
//               Commented out sales tax code until later.
//
// m005 2000/11/03 Rewrote side frames to reduce table processing.
//               Also added focus control to total fields.
//
// m004 2000/10/30 Removed unused code.
//
// m003 2000/10/24 Changed text of alert to indicate "outside of 
//               contiguous 48 United States"
//  
// m002 2000/09/19 Added use of BFormMail.cgi for courtesy response to orders.
//
// m001 2000/09/15 Added code to verify 16 numeric digits in credit card.
//
// for help see the following
// http://www.teleport.com/~danal/Pages/making.html
// http://www.newbie.net/sharky/frames/intro.htm

function makeArray(n)
{
  this.length = n;

  for(var i = 1; i <= n; i++) 
  {
    this[i] = 0;
  }

  return this;

}
  
  var TGTCBoard = 1;
  var KKBoard = 2;  
  var MCBoard = 3;
  
  // count the number of boards for shipping calculation purposes
  var numTGTCWaHooBoards = 0;  // number of TGTC boards
  var numKKWaHooBoards = 0;    // number of KK boards
  var wgtKKWaHooBoards = 0;    // weight of KK boards
  
  var numMCWaHooBoards = 0;    // number of MC boards
  var wgtMCWaHooBoards = 0;    // weight of MC boards
  
  // make these global for all functions to see
  var salesTax = 0;
  var shipCost = 0;
  var grandTotal = 0;
  var orderNum = 0;                                             
  var order = new makeArray(100);                      
  var count;
  var formSave;
  var ccTotal;
  var salesTaxRate = 0.0775;
  // NOTE: THIS MUST BE EQUAL TO THE FIRST VALID ENTRY 
  // IN THE uspsTGTCShipping[1][0] ARRAY IN usps2008.js
  var uspsPriorityMailMinimum = 5.00;
  var orderNumberString;
  var USPSRateIncrease = 0.0;

function dispLink(link)
{  
  window.open(link);
}

function dispSplashScreen()
{
  tWin = parent.frames['catalog'].document;

  tWin.open();

  tWin.write("<HTML><HEAD><TITLE>Spash Screen</TITLE></HEAD>");

  tWin.write("<BODY BGCOLOR=ivory TEXT=#000000>");

  tWin.write("<H2>Making WA HOO<SUP><SMALL>&reg</SMALL></SUP> boards...<hr></H2>");

  tWin.write("If you are an experienced wood worker, live within reasonable driving distance of Denton, Texas, ");
  tWin.write("and would like to make extra money making and assembling WA HOO boards, please contact me."); 
  tWin.write("If you are not an experienced wood worker, but know someone who is, please let them know about this opportunity.");
  tWin.write("<p>Chuck Cox");
  tWin.write("<br>PO Box 605");   
  tWin.write("<br>Aledo, TX  76008");
  tWin.write("<br>817-582-0032");
  tWin.write("<br>chuck@wahoogames.com");

  tWin.write("</BODY></HTML>");

  tWin.close();
}

function searchCatalog(prodType)
{
  count = 0;

  var match = false;

  tWin = parent.frames['catalog'].document;

  tWin.open();

  tWin.write("<HTML><HEAD><TITLE>"+  prodType + " </TITLE></HEAD>");

  tWin.write("<BODY BGCOLOR=ivory TEXT=#000000>");

  for (var i = 1; i <= prodID.length; i++)
  {
    if (prodType == prodID[i].type)
    {
      prodID[i].show(tWin,i);

      match = true;

    }

  }

  tWin.write("</BODY></HTML>");

  tWin.close();

}


// This function is invoked in the javascript file database.js

function product (name,description,image,price,type,link,url,weight)
{
  this.name = name;
  this.description = description;
  this.image = image
  this.price = price;
  this.type = type;
  this.show = show;
  this.weight = weight;

  if (link != "")
  {
    this.link = "<CENTER><TABLE BORDER=0><TR><TD><A HREF='" + url + "'><Font face=arial size=-2>" + link + "</FONT></A></TD></TR></TABLE></CENTER>";
  } else
  {
    this.link = "";
  }

}

    
function show(w,prodIndexNum)
{  
  w.write("<CENTER><TABLE BORDER= 0 WIDTH=300><TR><TD BGCOLOR=#d5d5ff><FONT FACE='arial' COLOR=blue><b>"  + this.name + "</b></FONT></TD></TR></TABLE></CENTER>");

  if (this.image.length > 1)
  {
    w.write("<CENTER><TABLE BORDER=0 COLS=2 WIDTH=300 BGCOLOR=#FFCC00 ><TR BGCOLOR=#00CC00><TD><FONT FACE = 'Arial' SIZE = 2 >Image</FONT></TD><TD><FONT FACE = 'Arial' SIZE = 2 >Description</FONT></TD></TR><TR><TD><IMG SRC='" + this.image + "' ALT='" + this.name + "'></TD>");

    w.write("<TD><FONT FACE = 'Arial' SIZE = 2 >" + this.description + "</TD></TR></Table></CENTER>");

  }
  
  if (this.link != "")
  {
    w.write(this.link);
  }

  w.write("<FORM NAME=isaiah>");

  orderProd(this,w,prodIndexNum);

  w.write("</FORM><HR SIZE=1 NOSHADE WIDTH=90%><br>");
          
}


function orderProd(obj,win,index)
{

  win.write("<CENTER><TABLE BORDER=0 COLS=2 WIDTH=300 BGCOLOR=#CCCCCC><TR><TD><FONT FACE = 'arial' size=-1><b>Price Each: $</b>" + currency(obj.price) +"</font></CENTER>");

  win.write("<CENTER>&nbsp;&nbsp;<FONT FACE = 'arial' size=-1><b>Enter Quantity:</b></font>  " + "<INPUT TYPE = 'text' SIZE = 3 NAME = 'q' VALUE = '1' onBlur = parent.reTotal("+ parent.count + "," +  obj.price + ") onFocus = parent.reTotal("+ parent.count + "," +  obj.price + ")><br></CENTER>");

  win.write("<CENTER>&nbsp;&nbsp;<FONT FACE = 'arial' size=-1><b>Total:" + " $</b></font><INPUT TYPE = 'text' SIZE=7 NAME= subTotal VALUE =" + currency(obj.price) + ">&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;" + "<INPUT TYPE ='button' VALUE = 'SubTotal' onClick = parent.reTotal("+ parent.count + "," +  obj.price + ")></TR></TABLE></CENTER>");

  win.write("<CENTER><IMG SRC=images/pickit.gif ALIGN=TEXTTOP><A HREF=javascript:parent.add(" + parent.count + "," + index + ")><IMG SRC=images/addtocart.gif border=0></A></CENTER>");


   count++;

}



// This pops up a confirmation box. The first is (0,1), next (1,2)
function add(id, oIndex)
{
  var theForm =  parent.frames['catalog'].document.forms[id];

  productName = prodID[oIndex].name;

  totalSum = parent.frames['catalog'].document.forms[id].subTotal.value;

  totalQuantity =  parent.frames['catalog'].document.forms[id].q.value;

  if (totalQuantity == 0)
  {
    alert("You entered a quantity of 0!\n We cannot process this order");

    parent.frames['catalog'].document.forms[id].q.value = 1;

    reTotal(id,prodID[oIndex].price);

  } else
  {
    if (confirm("You are adding " + totalQuantity + " order/s of " + productName + " \n Subtotal: " + totalSum + " to your shopping cart."))
    {
      store(oIndex,totalSum,totalQuantity);
    } else
    {
      alert("\n\nThis order was not placed in your shopping cart.");
    }
  }
}


function store(o,ts,tq)
{
  orderNum++;

  order[orderNum] = new cartGoods(o,ts,tq);

  showTotal = 0;

  for(var i = 1; i <= orderNum;i++)
  {
    showTotal += parseFloat(order[i].totSum);                
  }

  parent.frames['cart'].document.forms[0].runningTotal.value = currency(showTotal);

}

function cartGoods(Indx, totSum, totQ)
{
  this.ID = Indx;                   // ccc
  this.Indx = prodID[Indx].name;
  this.totSum = totSum;

  this.totQ = totQ;
  
  this.weight = prodID[Indx].weight;
}


// *****************************************************************************
// Display the contents of the Shopping Cart.
// *****************************************************************************
function view()
{
  vWin = parent.frames['catalog'].document;
  vWin.open();
  vWin.write("<HTML><BODY BGCOLOR=ivory text=Black>");

  if (orderNum != 0)
  {
    vWin.write("<CENTER><H2>Your Shopping Cart Contents</H2></CENTER>");
    vWin.write("<FORM><TABLE WIDTH=100% BORDER=1>");
    vWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Quantity</FONT></TD>");
    vWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Product</FONT></TD>");
    vWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Price</FONT></TD>");
    vWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face='Arial' size=2 COLOR=WindowText></FONT></TD><TR>");
    for (var i = 1; i <= orderNum; i++)
    {
      vWin.write("<TD COLSPAN=1 align=center BGCOLOR=#D5D5FF><FONT COLOR=WindowText face='Arial' Size=3>"+order[i].totQ+"</FONT></TD>");
      vWin.write("<TD COLSPAN=1 BGCOLOR=#D5D5FF><FONT COLOR=WindowText face='Arial' Size=3>"+order[i].Indx+"</FONT></TD>");
      vWin.write("<TD COLSPAN=1 BGCOLOR=#D5D5FF><FONT COLOR=WindowText face='Arial' Size=3>"+order[i].totSum+"</FONT></TD>");
      vWin.write("<TD VAlign=TOP align=center BGCOLOR=white><input type='checkbox' Name=checkbox"+i+" onclick=parent.remove("+i+")></Font>");
      vWin.write("<FONT COLOR=WindowText face='Arial' Size=1><b>Check here to remove item</b></FONT></TD></TR>");
    }
    
    vWin.write("</TABLE></FONT></FORM><br>");

  } 
  else
  {
    vWin.write("<FONT SIZE = 5 FACE = 'arial'><br>" + "<br><IMG SRC=images/noitem.gif border=0 WIDTH=337 HEIGHT=18 ALT='no items in cart'></FONT>");

  }

  vWin.write("<TABLE BORDER=0 COLS=2 WIDTH=100% >");

  vWin.write("<TR><TD><A HREF = javascript:parent.checkOut(); return true;><font size=-2 face=arial>CheckOut</font></A></TD>");

  vWin.write("<TD><A HREF=catalog.htm><font size=-2 face=arial>Store Front</font></A></TD></TR>");
  
  vWin.write("</TABLE>");

  vWin.write("</BODY></HTML>");
  
  vWin.close();

}

// *****************************************************************************
// Remove an item from the Shopping Cart
// *****************************************************************************
function remove(item)
{
  var newSum = 0;
  for (var i = item+1; i <= orderNum; i++)
  {
    if (item == orderNum)
    {
	  order[i].ID=0;	
      order[i].Indx = "";
      order[i].totSum = 0 ;
      order[i].totQ = "";
      order[i].weight = 0;
      break;
          
    } else
    {
	  order[i-1].ID = order[i].ID;
      order[i-1].Indx = order[i].Indx;
      order[i-1].totSum = order[i].totSum;
      order[i-1].totQ = order[i].totQ;
      order[i-1].weight = order[i].weight;
    }
  }
  
  orderNum--;
  for(var i = 1; i <= orderNum; i++)
  {
    newSum += parseFloat(order[i].totSum);
  }
  
  parent.frames['cart'].document.forms[0].runningTotal.value = currency(newSum);

  view();

}


// *****************************************************************************
// Display the checkout page to the user and prepare to submit.
// *****************************************************************************
function checkOut()
{
  wgtKKWaHooBoards = 0; 
  numTGTCWaHooBoards = 0;
  numKKWaHooBoards = 0;
  numAccessories = 0;
  grandTotal = 0;
  
  numMCWaHooBoards = 0;
  wgtMCWaHooBoards = 0;

  dateObj = new Date();
  //date = dateObj.toString(); 
  date = dateObj.toLocaleString();
  tmpString = String(Number(dateObj));
  orderNumberString = tmpString.substring(tmpString.length-6, tmpString.length);

  if (orderNum != 0)
  {

    cWin = parent.frames['catalog'].document;
    cWin.open();
    cWin.write("<HTML><BODY TEXT=#000000 BGCOLOR=ivory>");
    cWin.write("<H2>Check Out Page</H2><Table border=1><tr>");

    cWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Quantity</FONT></TD>");
    cWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Product</FONT></TD>");
    cWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Price</FONT></TD>");
    cWin.write("<TD COLSPAN=1 BGCOLOR=#ffcc00><FONT face=arial COLOR=WindowText>Total Price</FONT></TD></TR>");
    for(var i = 1; i <= orderNum; i++)
    {
      cWin.write("<TD COLSPAN=1 align=center BGCOLOR=#d5d5ff><FONT COLOR=WindowText face='Arial' Size=2>"+order[i].totQ+"</FONT></TD>");
      cWin.write("<TD COLSPAN=1 align=center BGCOLOR=#d5d5ff><FONT COLOR=WindowText face='Arial' Size=2>"+order[i].Indx+"</FONT></TD>");
      cWin.write("<TD COLSPAN=1 align=center BGCOLOR=#d5d5ff><FONT COLOR=WindowText face='Arial' Size=2>"+parent.currency(order[i].totSum/order[i].totQ)+"</FONT></TD>");
      cWin.write("<TD COLSPAN=1 align=center BGCOLOR=#d5d5ff><FONT COLOR=WindowText face='Arial' Size=2>"+parent.currency(order[i].totSum)+"</FONT></TD></TR>");
      grandTotal += parseFloat(order[i].totSum); 

      // ccc --- count the number of boards ordered so we can calc USPS shipping later
      if ((order[i].ID == 1) ||(order[i].ID == 5))
      {

        // stupid method, but necessary, don't change, you'll be sorry
        numTGTCWaHooBoards += order[i].totSum / (order[i].totSum/order[i].totQ);
      }
      
      // m007 calculate number of accessories, but only charge for one
      if ((order[i].ID == 2) || (order[i].ID == 3) || (order[i].ID == 4) ||
          (order[i].ID == 6) || (order[i].ID == 30) || (order[i].ID == 37))
      {
      
        // stupid method, but necessary
        numAccessories += order[i].totSum / (order[i].totSum/order[i].totQ);
      }
      
      // m011 add Kathy's Korner board processing
      if ((order[i].ID >= 7) && (order[i].ID <= 37) && (order[i].ID != 30) && (order[i].ID != 37))
      {    
        
        
        // stupid method, but necessary        
        numKKWaHooBoards += order[i].totSum / (order[i].totSum/order[i].totQ);      
        
        wgtKKWaHooBoards += order[i].weight * order[i].totQ;
        
        // alert("wgtKKWaHooBoards = " + wgtKKWaHooBoards);
      }

      // m015 add Moonlight Creations board processing
      if ((order[i].ID >= 38) && (order[i].ID <= 48))
      {                
        // stupid method, but necessary        
        numMCWaHooBoards += order[i].totSum / (order[i].totSum/order[i].totQ);      
        
        wgtMCWaHooBoards += order[i].weight * order[i].totQ;

        // alert("numMCWahHooBoards = " + numMCWaHooBoards);        
        // alert("wgtMCWaHooBoards = " + wgtMCWaHooBoards);
      }
      // --- ccc     
    }
 
    finalSum = currency(grandTotal);

    cWin.write("<TD COLSPAN=3 ALIGN=CENTER bgcolor='#009933'><font face=arial COLOR=#ffcc00><b>Total:</b></font></TD>");
    cWin.write("<TD COLSPAN=1 ALIGN=CENTER bgcolor='#009933'><font face=arial COLOR=#ffcc00><b>$ " + finalSum + " </b><SMALL>(excluding taxes & shipping)</SMALL></font></TD></TR>");
    cWin.write("<TR><TD COLSPAN=4>");
    cWin.write("<FONT COLOR=RED SIZE=2>NOTE: MS Internet Explorer users should use the TAB key to move between fields. Using the ENTER key causes the incomplete form to be submitted. There is currently no fix for this. <br><br>Also, if you wish to DELETE items from your order, click the View Cart link at left.  Thanks. <br> Chuck</FONT>");
    cWin.write("</TD></TR></TABLE>");

    // =====================================================================================
    // the following lines are specific to BFormMail defined below.
    // use this one to invoke the script that sends various fields to multiple recipients

    cWin.write("<FORM NAME='orderform' OnSubmit='return false' METHOD='POST' ACTION='/cgi/BFormMailTGTC.cgi'>" );	
    cWin.write("<input type='hidden' name='courtesy_reply' value='yes'>");
    cWin.write("<input type='hidden' name='courtesy_reply_texta' value='This is an automated order confirmation. Thank you for your order. Feel free to contact us regarding questions about your order or suggestions for the web site.'>");
    cWin.write("<input type='hidden' name='courtesy_reply_textb' value='Please note:  If you did not specify a payment option, your order will not be processed.'>");
    cWin.write("<input type=hidden name='courtesy_who_we_are' value='Chuck Cox, President'>");
    cWin.write("<input type=hidden name='courtesy_who_we_are2' value='Traditional Game &amp; Toy Company'>");
    cWin.write("<input type=hidden name='courtesy_our_url' value='http://www.wahoogames.com'>");
    cWin.write("<input type=hidden name='courtesy_our_email' value='sales@wahoogames.com'>");
    // cWin.write("<input type=hidden name='bcc' value='coxcc@yahoo.com'>");
    cWin.write("<input type=hidden name='return_link_url' value='http://www.wahoogames.com'>");
    cWin.write("<input type=hidden name='return_link_title' value='http://www.wahoogames.com'>");
    // =====================================================================================

    cWin.write("<INPUT TYPE='hidden' NAME='recipient' VALUE='sales@wahoogames.com'>");

    cWin.write("<INPUT TYPE='hidden' NAME='title' VALUE='<center>WA HOO Games<br>Order Form & Payment Option</center>'>");

    cWin.write("<INPUT TYPE='hidden' NAME='subject' VALUE='WA HOO Order '>");
    cWin.write("<INPUT TYPE='hidden' NAME='ordernum' VALUE=''>");	
    cWin.write("<INPUT TYPE='hidden' NAME='required' VALUE='realname,email,address,city,state,zip'>");
    cWin.write("<INPUT TYPE='hidden' NAME='print_config' VALUE='orderNumberString,date,email,homephone,realname,address,city,state,zip,sh_name,sh_address,sh_city,sh_state,sh_zip,ccname,order,ccAmount'>");

    cWin.write("<table border='0' columns='6' cellspacing='0' cellpadding='0'>");
    cWin.write("<tr><td colspan='2'><strong>Order:&nbsp;&nbsp;"+orderNumberString+"</strong></td>");
    cWin.write("<td colspan='4'><strong>Date:&nbsp;&nbsp;"+date+"</strong></td></tr>");	
    cWin.write("<tr><td colspan='6'><hr></td></tr>");
    cWin.write("<tr><td colspan='6'><strong>Bill to:</strong></td></tr>");
    cWin.write("<tr><td><strong>Name:</strong></td><td><input type='text' name='realname' size='20'></td>");
    cWin.write("<td>&nbsp;&nbsp;<strong>Address:</strong>&nbsp;&nbsp;<input type='text' name='address' size='25'></td></tr>");
    cWin.write("<tr><td><strong>City:</strong></td><td><input type='text' name='city' size='20'></td>");
    cWin.write("<td>&nbsp;&nbsp;<strong>State:</strong>&nbsp;&nbsp;<input type='text' name='state' size='2'>&nbsp;&nbsp;<strong>Zip Code:</strong><input type='text' name='zip' size='5' onBlur = 'parent.uspsShipping(this.form); return true;'></td></tr>");
    cWin.write("<tr><td><strong>Phone:</strong></td><td colspan='5'><input type='text' name='homephone' size='15'>&nbsp;&nbsp;ex: 111-222-3333</td></tr>");
    // cWin.write("<td><strong>FAX:</strong></td><td><input type='text' name='faxnumber' size='15'></td></tr>");
    cWin.write("<tr><td><strong>E-Mail:</strong></td><td colspan='5'><input type='text' name='email' size='30'>&nbsp;&nbsp;(for order confirmation)</td></tr>");
    cWin.write("<tr><td colspan='6'><hr></td></tr>");
    cWin.write("<tr><td colspan='6'><strong>Ship to (only if different than billing address):</strong></td></tr>");
    cWin.write("<tr><td><strong>Name:</strong></td><td><input type='text' name='sh_name' size='20'></td>");
    cWin.write("<td>&nbsp;&nbsp;<strong>Address:</strong>&nbsp;&nbsp;<input type='text' name='sh_address' size='25'></td></tr>");
    cWin.write("<tr><td><strong>City:</strong></td><td><input type='text' name='sh_city' size='20'></td>");
    cWin.write("<td>&nbsp;&nbsp;<strong>State:</strong>&nbsp;&nbsp;<input type='text' name='sh_state' size='2'>&nbsp;&nbsp;<strong>Zip Code:</strong><input type='text' name='sh_zip' size='5' onBlur = 'parent.uspsShipping(this.form); return true;'></td></tr>");
   
    cWin.write("<tr><td colspan='6'><hr></td></tr>");   
    cWin.write("<tr><td colspan='6'>Shipping and taxes, if applicable, will be calculated automatically when ZIP code is entered.</td></tr>");

    cWin.write("<tr><td align='left'><strong>Sub-total:</strong></td>");
    cWin.write("<td align='left' colspan='4'><input type='text' name='field_subTotal' size='10' readonly=true onFocus='this.blur()'></td></tr>");
    cWin.write("<tr><td align='left'><strong>Sales Tax:</strong></td>");
    cWin.write("<td align='left' colspan='4'><input type='text' name='field_tax' size='10' readonly=true onFocus='this.blur()'>&nbsp;&nbsp;7.75% for Texas addresses only</td></tr>");
    cWin.write("<tr><td align='left'><strong>Shipping: ");
    cWin.write("<td align='left' colspan='4'><input type='text' name='field_shipping' size='10' readonly=true onFocus='this.blur()'>&nbsp;&nbsp;USPS Priority Mail *</td></tr>");
    cWin.write("<tr><td align='left'><strong>Total:");   
    cWin.write("<td align='left' colspan='4'><input type='text' name='field_Total' size='10' readonly=true onFocus='this.blur()'>&nbsp;&nbsp;(this is your payment amount)</td></tr>");
    cWin.write("<tr><td colspan='6'><hr></td></tr>");
    cWin.write("<tr><td colspan='6'><p>* WA HOO, WA HOO Deluxe, and Heirloom WA HOO games are shipped separately.  Postage charges for accessories may be less than indicated.</td></tr>");
    cWin.write("<tr><td colspan='6'><hr></td></tr>");

    cWin.write("<tr><td colspan='6'><center><INPUT TYPE = 'submit' VALUE = 'Click Here to Select Payment Option' onClick = 'parent.formData(this.form)'></center></td></tr><tr><td colspan='4'><hr></td></tr>");
    cWin.write("</table>");
   
    cWin.write("<INPUT TYPE='hidden' NAME='subtotal' VALUE=''>");
    cWin.write("<INPUT TYPE='hidden' NAME='tax' VALUE=''>");
    cWin.write("<INPUT TYPE='hidden' NAME='shipping' VALUE=''>");
    cWin.write("<INPUT TYPE='hidden' NAME='total' VALUE=''>");
    cWin.write("&nbsp;&nbsp;<INPUT TYPE = 'hidden' NAME='order'" + " VALUE = ''>");
    cWin.write("</FORM>");

    // prevent ENTER key from submitting form
    cWin.write("<FORM METHOD=GET><INPUT TYPE='hidden'></FORM>");

    cWin.write("</BODY></HTML>");
    cWin.close();

  } else
  {
    alert("\n\nYour shopping cart is empty!\n\n");
  }

}

function formData(form)
{
  var formElems = form.elements.length;
  formSave = new makeArray(formElems-3);
  for (var i = 1; i <= formElems; i++)
  {
    formSave[i] = form.elements[i-1].value;
  }

  for (var i = 1; i <= orderNum; i++)
  {
    form.elements['order'].value += "<br>Qty:" + order[i].totQ
    form.elements['order'].value += " " + order[i].Indx
    form.elements['order'].value += " at " + currency(order[i].totSum/order[i].totQ) + "\n "
  }

  form.elements['subtotal'].value = currency(grandTotal);

  form.elements['tax'].value = currency(salesTax);

  form.elements['shipping'].value = currency(shipCost);
  
  form.elements['total'].value = currency(ccTotal);
  
  form.elements['ordernum'].value = orderNumberString;
  
  form.elements['subject'].value = 'WA HOO Order '+ orderNumberString;
  
  form.submit();
  
}

// *****************************************************************************
// Recalculate the new sub-total sales amount and display in field c.
// *****************************************************************************
function reTotal(c,totalPrice)
{

  totalPrice = totalPrice * parent.frames['catalog'].document.forms[c].q.value;

  newTotal = currency(totalPrice); 

  parent.frames['catalog'].document.forms[c].subTotal.value = newTotal;    
}
 

// *****************************************************************************
// Display dialog box stating that the shopping cart is empty.
// *****************************************************************************
function empty()
{
  if (orderNum == 0)
  {
    alert("\n\nYour cart is already empty!\n\n");
  } else
  {
    orderNum = 0;
    alert("\nYour cart has been emptied!\n");
  }   
}


// *****************************************************************************
// Convert the value entered into dollars and cents and return the new value.
// *****************************************************************************
function currency(money)
{
  money = money + ""           

  var monLen = money.length;

  var digPos = money.indexOf(".");

  if(digPos == -1 & monLen < 1)
  {
    money = money.substring(0,digPos+ 1) + "00";
  } else if(digPos == -1 & monLen > 0)
  {
    money = money + ".00";
  }else
  {

    cents = money.substring(digPos + 1, monLen + 1);

    if(cents.length == 1)
    {
      money = money + "0";
    }else if(cents.length > 2)
    {
      roundVal = cents.charAt(2);

      if(roundVal  >= 5)
      {
        money = parseFloat(money) + .01;

        money = money + "";

        money = money.substring(0,digPos + 3)

      }else
      {
        money = money.substring(0,digPos + 3)
      }
    }
  }

  return money;
}


// *****************************************************************************
// Calculate the usps shipping charge and update the display with the new value.
// *****************************************************************************
function uspsShipping(form)
{              
  var tmpCost = 0;
  var cost = 0;
  var numTGTCCases = 0;
  var numTGTCBoards = 0;
  var numKKBoards = 0;
  var numMCBoards = 0;
  var bailout = 0;
  
  shipCost=0;
  
  // first, determine how many ORIGINAL WAHOO boards were ordered
  // next, determine the usps zone of the destination (first three digis of ZIP code)
  // then, apply the cost based on the zone to each board ordered

  if (form.elements.zip.value.length > 5 ||
      form.elements.sh_zip.value.length > 5)
    alert("Invalid ZIP code.  First five digits only please.");
  {  

    billZipCode = form.elements['zip'].value;
    shipZipCode = form.elements['sh_zip'].value;
  
    if (shipZipCode != 0)
      zipCode = shipZipCode;
    else 
      zipCode = billZipCode;

    // get the first three digits and guarantee they're in range  
    zipDigits = zipCode / 100;
  
    //  alert("zipCode: "+zipCode+" zipDigits: "+zipDigits);
   
    // valid ZIP codes begin with 001 through 999
    if (zipDigits < 1  || zipDigits > 999)
      alert("Invalid ZIP code. Please re-enter.");
    else
    {    
  
      // alert("numKKWaHooBoards = " + numKKWaHooBoards);
  
      // if there are ANY boards to be shipped from Midland, use the 797 table
      if (numKKWaHooBoards > 0)
      {
    
        // use the ZIP array for Midland, Texas  79701
        for (i = 146; i >=0 && zipDigits < usps797ZipArray[i]; i--)
          ;

        // extract the zone from the 797 zone table
        zone = usps797ZoneArray[i];         
      
        // the only valid USPS zones are 1-8
        if (zone < 1 || zone > 8)
        {
       
          alert("Invalid ZIP code. Please re-enter.");

          bailout = true;  
        }        
        else
        {
       
          // calculate final number of KK boards, not needed at this point 
          numKKBoards = Math.floor(numKKWaHooBoards % 12);

          // our USPS weight table only goes to 30 pounds
          if (wgtKKWaHooBoards <= 30)
          {
         
            // if less than or equal to 30 pounds...
            // calculate cost of single boards
            cost += costTable(KKBoard, wgtKKWaHooBoards, zone);                     
          }
          else // if greater than 30 pounds, bail out
          {
         
            alert("Your order weighs more than 30 pounds.  Please e-mail us for shipping options... sales@wahoogames.com.");
        
            bailout = true;
          }  
       
        }   // if zone is valid 
      
      }     // if numKKWaHooBoards > 0

      // alert("numTGTCWaHooBoards = " + numTGTCWaHooBoards);   
    
      // if there are ANY boards to be shipped from Aledo or Trophy Club, use the 760 table
      if (((numTGTCWaHooBoards > 0) || (numMCWaHooBoards > 0)) && (bailout != true))
      {
            
        // use the ZIP array for Aledo, Texas  76008    
        for (i = 162; i >=0 && zipDigits < usps760ZipArray[i]; i--)
          ;

        // extract the zone from the 760 zone table
        zone = usps760ZoneArray[i];

        // the only valid USPS zones are 1-8
        if (zone < 1 || zone > 8)
        {
      
          alert("Invalid ZIP code. Please re-enter.");
        
          bailout = true;
        }
        else
        {

          // calculate number of full cases
          numTGTCCases = Math.floor(numTGTCWaHooBoards / 12);

          // calculate final number of boards       
          numTGTCBoards = Math.floor(numTGTCWaHooBoards % 12);
            
          // calculate whole case cost first
          cost += numTGTCCases * costTable(TGTCBoard, 12, zone);

          // now calculate cost of single boards
          cost += costTable(TGTCBoard, numTGTCBoards, zone);

          // our USPS weight table only goes to 30 pounds
          if (wgtMCWaHooBoards <= 30)
          {
         
            // if less than or equal to 30 pounds...
            // calculate cost of single boards

            // calculate final number of boards, not needed at this point 
            numMCBoards = Math.floor(numMCWaHooBoards % 12);

            // now calculate cost of MC single boards 
            cost += costTable(MCBoard, wgtMCWaHooBoards, zone);                  

            // alert("shipping cost of MC boards = " + costTable(MCBoard, wgtMCWaHooBoards, zone));
          }
          else // if greater than 30 pounds, bail out
          {
         
            alert("Your order weighs more than 30 pounds.  Please e-mail us for shipping options... sales@wahoogames.com.");
        
            bailout = true;
          }  

      }   // if zone is valid
      
    }     // if numTGTCWaHooBoards > 0

    // if nothing failed above, continue...
    if (bailout != true)
    {
    
      // Add handling charge if any TGTC boards are ordered.
      if (numTGTCBoards > 0)
      {
        shipCost += 2.00;
      }  

      // Add handling charge if any KK boards are ordered.
      if (numKKBoards > 0) // with no case sales, we could use numKKWaHooBoards
      {
        shipCost += 2.00;
      }
      
      // Add handling charge if any MC boards are ordered.
      if (numMCBoards > 0)  // with no case sales, we could use numMCWaHooBoards
      {
        shipCost += 3.00;
      }
      
      // if the cost calculated thus far is greater than the minimum USPS Priority Mail charge...
      if (cost >= uspsPriorityMailMinimum)
      {
        // ... just add the handling charge
        shipCost += cost;
      }  
      else // if the cost is less than the minimum USPS Priority Mail charge...
      {
        // ... default to the minimum USPS Priority Mail charge.
        shipCost = uspsPriorityMailMinimum;
      }

      zipDigits = Math.floor(billZipCode / 1000);

      // Texarkana, Arkansas has ZIP code 75502
      if ((zipDigits >= 75 && zipDigits <= 79) && zipCode != 75502)
        salesTax = grandTotal * salesTaxRate;
      else
        salesTax = 0; 

      ccTotal = grandTotal + shipCost + salesTax;

      form.elements['field_tax'].value = currency(salesTax);

      form.elements['field_subTotal'].value = currency(grandTotal);
  
      form.elements['field_shipping'].value = currency(shipCost);
  
      form.elements['field_Total'].value = currency(ccTotal);  

      }  // if bailout is true
    
    }    // ZIP code is valid
    
  }      // ZIP code is not TOO long
  
}      // end function uspsShipping


// *****************************************************************************
// Return the shipping cost for each zone based upon the number of boards
// or the total weight of the order.
// *****************************************************************************
function costTable(board, detail, zone)
{
  // detail is either number of boards for TGTCBoard or weight for KKBoard

  // alert("board, detail, zone = " + board + " " + detail + " " + zone);

  if (board == TGTCBoard) 
  {
    switch(zone)
    {
      case 1:
        cost = uspsTGTCShipping[detail].zone1;
        break;
      case 2:
        cost = uspsTGTCShipping[detail].zone2;
        break;
      case 3:
        cost = uspsTGTCShipping[detail].zone3;        
        break;
      case 4:
        cost = uspsTGTCShipping[detail].zone4;        
        break;
      case 5:
        cost = uspsTGTCShipping[detail].zone5;        
        break;
      case 6:
        cost = uspsTGTCShipping[detail].zone6;        
        break;
      case 7:
        cost = uspsTGTCShipping[detail].zone7;        
        break;
      case 8:
        cost = uspsTGTCShipping[detail].zone8;       
        break;
      default:
        cost = 0;
        break;
    }
  }
  else if (board == KKBoard || board == MCBoard)
  {
    switch(zone)
    {
      case 1:
        cost = uspsPriorityMail[detail].zone1;
        break;
      case 2:
        cost = uspsPriorityMail[detail].zone2;
        break;
      case 3:
        cost = uspsPriorityMail[detail].zone3;        
        break;
      case 4:
        cost = uspsPriorityMail[detail].zone4;        
        break;
      case 5:
        cost = uspsPriorityMail[detail].zone5;        
        break;
      case 6:
        cost = uspsPriorityMail[detail].zone6;        
        break;
      case 7:
        cost = uspsPriorityMail[detail].zone7;        
        break;
      case 8:
        cost = uspsPriorityMail[detail].zone8;       
        break;
      default:
        cost = 0;
        break;
    }
  }

  // alert("cost = " + cost);
  
  cost += cost * USPSRateIncrease;

  cost = roundUp(cost);

  return cost;
}

function roundUp(currentCost)
{
  roundedCost = 0;

  if (currentCost > 0)
  {

    dollars = Math.floor(currentCost);
    cents   = currentCost - dollars;

    if (cents <= .25)
      value = 0.25;
    else if (cents <= .50)
      value = 0.50;
    else if (cents <= .75)
      value = 0.75;
    else 
      value = 1.00;

    roundedCost = value + dollars;
  }

  return roundedCost;
}

