/*
 Copyright (c) 2003, 2005 by Jon Roma.  All rights reserved.

 $URL: svn://zippy.cso.uiuc.edu/RMCA/trunk/new/store/meetreg.js $
 $Revision: 2805 $ $Date: 2005-09-18 16:46:43 -0500 (Sun, 18 Sep 2005) $
 */

var isDebug  = 0;                         // global debug flag
var isPayPal = 1;                         // handling PayPal or a mail-in form

/*
   PayPal fee details, assuming
      fee = (subtotal * fraction) + flat

   IMPORTANT: MUST be kept consistent with similar perl code
 */

var feeFraction   = 0.029;                // fractional portion of fee (2.9%)
var feeFlat       = 0.30;                 // flat portion of fee (30 cents)

function computePayPalFee(subtotal)
{
// this MUST be kept in sync with counterpart perl routine

if (! isPayPal || subtotal == 0)
   return 0.0;

return (feeFraction * ((subtotal + feeFlat) / (1 - feeFraction))) + feeFlat;
}

//

function recomputeCart()
{
var f = document.getElementById('form_local');

// compute item totals and subtotal

var i;
var st = 0;

for (i = 0; i < itemCount; i++)
   {
   var io = document.getElementById('subtotal_' + i);
   var it = (getItemValue(i, 'amount') * getItemValue(i, 'quantity'));

   st += it;                              // compute subtotal from item totals

// io.innerHTML = (it) ? ('$' + toMoney(it)) : '';
   io.innerHTML = '$' + toMoney(it);
   }

// find objects for updating totals

var ho = document.getElementById('handling');
var so = document.getElementById('subtotal');
var to = document.getElementById('total');

// compute PayPal fee and total

var ht = computePayPalFee(st);            // compute fee
var t  = st + ht;

if (isPayPal)
   {
   // so.innerHTML = (st) ? ('$' + toMoney(st)) : '';
   so.innerHTML = '$' + toMoney(st);

   // ho.innerHTML = (ht) ? ('$' + toMoney(ht)) : '';
   ho.innerHTML = '$' + toMoney(ht);
   }

// to.innerHTML = (t) ? ('$' + toMoney(t)) : '';
to.innerHTML = '$' + toMoney(t);

return 1;
}

// gets a numeric value from a numbered element inside form_local

function getItemValue(n, what)
{
var f = document.getElementById('form_local');

var pattern = /^([a-z]+)_([0-9]+)$/;

var i;

for (i = 0; i < f.elements.length; i++)
   {
   var e = f.elements[i];
   var r = pattern.exec(e.name);

   if (r != null && r.length == 3 && r[1] == what && r[2] == n)
      return (! e.value || isNaN(e.value)) ? 0 : e.value;
   }

return 0;                                 // fallback to zero value
}

//

function toMoney(v)
{
var c;

if (v == null || isNaN(v))
   return null;                           // undefined value specified

v = Math.round(v * 100);
c = (v % 100).toString();                 // separate fractional component

if (c < 10)
   c = '0' + c;
      
while (c.length < 2)                      // append trailing zeros to fill
   c += '0';
      
return Math.floor(v / 100) + '.' + c;     // return concatenated values
}

//

function paypalPrepare()
{
var dstForm = document.getElementById('form_paypal');
var srcForm = document.getElementById('form_local');
var tplForm = document.getElementById('form_template');

if (isDebug)
   alert("Preparing form for submission");

var st = 0;

// delete existing destination form and start fresh

if (dstForm)
   {
   // depends on form being immediate child of <body> element
   document.body.removeChild(dstForm);    
   }

dstForm = document.createElement('form');
dstForm.id = 'form_paypal';

// depends on form being immediate child of <body> element
document.body.appendChild(dstForm);

var srcIndex;                             // index into source or template form
var dstIndex = 0;                         // index into destination form

var totalAmount = 0.0;

for (srcIndex = 0; srcIndex < itemCount; srcIndex++)
   {
   var iAmount   = getItemValue(srcIndex, 'amount');
   var iQuantity = getItemValue(srcIndex, 'quantity');
   var iName     = eval('srcForm.item_name_'   + srcIndex + '.value');
   var iNumber   = eval('srcForm.item_number_' + srcIndex + '.value');

   if (iAmount == 0 || iQuantity == 0)
      continue;                           // skip zero quantity or zero price

   totalAmount += (iAmount * iQuantity);  // recompute total

   dstIndex++;                            // increment destination form index

   appendIndexedFormInput(dstForm, dstIndex, 'item_name',   iName);
   appendIndexedFormInput(dstForm, dstIndex, 'item_number', iNumber);
   appendIndexedFormInput(dstForm, dstIndex, 'amount',      toMoney(iAmount));
   appendIndexedFormInput(dstForm, dstIndex, 'quantity',    iQuantity);
   }

// return error if nothing selected

if (dstIndex == 0)
   {
   alert
      (
      "No items were selected." + "\n\n" +
      "Please select one or more items before clicking on " + 
      "'" + document.getElementById('submit').innerHTML + "' button."
      );
   return 0;
   }

dstIndex++;

// compute PayPal fee and append item for said fee

if (computePayPalFee(totalAmount) > 0.0)
   {
   var handlingAmount = toMoney(computePayPalFee(totalAmount));

   appendIndexedFormInput(dstForm, dstIndex, 'item_name',   'Handling fee');
   appendIndexedFormInput(dstForm, dstIndex, 'amount',      handlingAmount);
   appendIndexedFormInput(dstForm, dstIndex, 'quantity',    1);
   }

// update common data from template

updateFormFromTemplate(tplForm, dstForm);

if (isDebug)
   {
   var s = '';

   for (dstIndex = 0; dstIndex < dstForm.elements.length; dstIndex++)
      {
      var e = dstForm.elements[dstIndex];    // form's element collection
   
      s += ('name: ' + e.name + ' value: ' + e.value + "\n");
      }
   
   if (s)
      alert("Destination form:\n" + s);
   }

dstForm.submit();                         // submit constructed form
return 1;
}

//

function appendIndexedFormInput(form, index, name, value)
{
var e = document.createElement('input')

e.type  = 'hidden';
e.name  = name + '_' + index;
e.value = value;

form.appendChild(e);

return e;
}

function updateFormFromTemplate(tplForm, dstForm)
{
// copy action and method from template to destination form

dstForm.action = tplForm.action;
dstForm.method = tplForm.method;

// copy each template element to destination form

var srcIndex;

for (srcIndex = 0; srcIndex < tplForm.elements.length; srcIndex++)
   {
   var srcElement = tplForm.elements[srcIndex];
   var dstElement = document.createElement('input');

   dstElement.type  = 'hidden';
   dstElement.name  = srcElement.name;
   dstElement.value = srcElement.value;

   dstForm.appendChild(dstElement);
   }

return 1;
}

