// START of dynamic prices helper routines - updated 28-11-05
var attindex;
var selcode;				// we'll keep the <select...> code in here.
var sequence = 1;			// sequence number for local var's (incremented for each product on page)
var thisseq;				// sequence number of current item being created.
var itm = new Object();			// global for current <SELECT> object being created
var vatfactor = '';			// will determine if we want additional VAT Inc field.
var SelectIndex;
var CurrentRadio;

function pricefield(fname){		// look through all forms 'till one containing field "fname"
  var df = document.forms;		// simplified version - only return object fname - or selected RADIO
  var i = df.length - 1;
  for ( var j = 0; j <= i; j++ )
    {
    var k = df[j].length - 1; 
    for ( var l = 0; l <= k; l++ )
      {
      if ( df[j].elements[l].name == (fname) ) 
        {
        if ( df[j].elements[l].type != 'radio' ) return df[j].elements[l];
        if ( df[j].elements[l].checked ) return df[j].elements[l];
        }
      }
    }
  alert('Cannot find field ' + fname);  // shouldn't happen...
  return false;
}

function settotal(prefix){
  thisseq = sequence++;
  eval('items_' + thisseq + '=new Object();itm = items_' + thisseq);
  itm.Base = 0;
  itm.SelectNames = new Array();
  itm.SelValues = new Array();
  itm.OptPrices = new Array();
  itm.HavePrices = false;
  itm.TotalPrefix = prefix;
  SelectIndex = 0;
  CurrentRadio = null;
}

function makenum(value){
  value = value.replace(/&#44;/g, "");                  // strip url encoded commas
  value = value.replace(/,/g, "");                      // strip vanilla flavour commas
  var val = value.match(/(\d*&#46;\d\d)/);		// deal with multi-currency (look for 1st number only)
  if ( val == null ) return 0;				// no match so return zero
  value = val[1];					// the valid first number
  return value.replace(/&#46;/,".");			// restore decimal point
}

function getoptionprice(opttext){
//
// this routine could be changed to allow for different ways of including the option price.
//
  var val = opttext.match(/\((.*)\)/);			// have we a "(" and ")" in the text?
  if ( val == null ) return 0;				// no match so return zero
  var thisval = val[1];					// extract the value
  thisval = thisval.replace(/[ |£|\$|€]/g,"");		// remove any space, pound, dollar or euro chars
  if ( isNaN(thisval) ) return 0;			// ignore invalid numbers
  itm.HavePrices = true;				// set flag so total field will get displayed
  return thisval;
}

function topounds(nPounds)
  {
  var nCurrency, nWholeCurrency, nFraction, sFraction;
  nWholeCurrency = Math.floor(nPounds);                // no of pounds
  nFraction = Math.round((nPounds - nWholeCurrency) * 100);  // Number of Fraction (2 decimal places)
  if ( nFraction > 99 ) nFraction = 99;
  if (nFraction < 10)                                  // Needs to be two digits
    {
    sFraction = "0" + nFraction.toString();            // Pad with leading zero
    }
  else
    {                                                 // Already has two digits
    sFraction = nFraction.toString();                  // So just format it
    }
  return(nWholeCurrency.toString() + '.' + sFraction);
  }

function update(thisseq){
  eval('itm = items_' + thisseq);			// find the apporpriate object
  if ( ! itm.HavePrices ) return;			// abandon if no total price needed
  var tot = itm.Base - 0;				// the base price
  for ( var i = 0; i < itm.SelectNames.length; i++)	// for each <CHECKBOX> <SELECT> or <RADIO> statement
    {
    var k = pricefield(itm.SelectNames[i]);
    if ( k.type == 'checkbox')				// if <CHECKBOX>
      {
      if ( k.checked ) tot += itm.OptPrices[i] - 0;	// use value if selected
      }
    else if ( k.type == 'select-one')
      {
      tot += itm.OptPrices[i][k.selectedIndex] - 0;	// look up it's value and add to total
      }
    else if ( k.type == 'radio')			// if <RADIO>
      {
      for ( var j = 0; j < itm.SelValues[i].length; j++ ) // loop through all buttons
        {
        if ( k.value == itm.SelValues[i][j] ) 
          {
          tot += itm.OptPrices[i][j] - 0;		// look up it's value and add to total
          }
        }
      }
    else alert('Unknown Variant Type (' + k.type + ') in DynamicPrices'); // Should never get here but Actinic might change
    }
  var stot = topounds(tot);
  pricefield('Tot_' + thisseq).value = itm.TotalPrefix + stot;	// save updated value
  if (vatfactor)
    {
    pricefield('Inc_' + thisseq).value = itm.TotalPrefix + topounds(Math.round(stot * vatfactor * 100) / 100);	// save updated value
    }
}

function CheckBox(cbname,cbstate,cblabel){
  document.write('<INPUT TYPE=CHECKBOX NAME="' + cbname + '" '  	// the original <CHECKBOX> statement
                 +  cbstate + ' onclick="update(' + thisseq + ')"> '
                 + cblabel);

  itm.SelectNames[SelectIndex] = cbname;				// save the name of this attribute
  itm.OptPrices[SelectIndex++] = getoptionprice(cblabel);		// we'll store the CHECKED price here
}

function RadioButton(attribref,choicesel,checked,choicename){
  document.write('<INPUT TYPE=RADIO NAME="' + attribref + '" VALUE="'  // the original <RADIO> statement
                 + choicesel + '" ' + checked 
		 + ' onclick="update(' + thisseq + ')">'
                 + choicename);

  if ( CurrentRadio != attribref )					// first call of this button
    {
    CurrentRadio = attribref;						// mark that we're in this item
    itm.SelectNames[SelectIndex] = attribref;				// save the name of this attribute
    itm.SelValues[SelectIndex] = new Array();
    itm.OptPrices[SelectIndex++] = new Array();				// we'll store the OPTION values here
    attindex = 0;							// base for OPTION values
    }
  itm.SelValues[SelectIndex - 1][attindex] = choicesel;
  itm.OptPrices[SelectIndex - 1][attindex++] = getoptionprice(choicename);	// save the price (if any) for this OPTION
}

function StartSelect(attribname){			// the <SELECT...> statement from Act_VariantListHeader.html
  selcode='<SELECT STYLE="FONT-FAMILY=Helvetica, Arial, sans-serif; FONT-SIZE=110%; WIDTH=450PX" NAME="' + attribname + '" onchange="update(\'' + thisseq + '\');">';  // recreate HTML
  itm.SelectNames[SelectIndex] = attribname;		// save the name of this attribute
  itm.OptPrices[SelectIndex] = new Array();		// we'll store the OPTION values here
  attindex = 0;						// base for OPTION values
}

function SelectOption(choice,selected,value){				// the <OPTION...> statement from Act_VariantListChoice.html
  selcode += '<OPTION VALUE=' + choice + ' ' + selected + '>' + value;	// recreate original <OPTION..> statement
  itm.OptPrices[SelectIndex][attindex++] = getoptionprice(value);	// save the price (if any) for this OPTION
}
 
function EndSelect(){					// the </SELECT> statement from Act_VariantListFooter.html
  document.write(selcode + '</SELECT>');		// write the HTML out
  SelectIndex++;					// bump count
}
// END of dynamic prices helper routines

