// 01-08-11 Tweak for UK Map Centre to use jQuery DOM ready
// 20-10-10 V1.10 Now allow radio buttons to be used as well
// 31-08-10 V1.09 Use Option values instead of option text
// Full List Code V1.08 - uses internally generated JavaScript object containing all price names and combinations
var perms = new Object();			// Actinic created list of permutations
var allperms = new Array();			// list of permutation variant names.
var permtotals = new Object();			// current value for each permutation

function getgrandtotal(ref){					// calculate and return grand total (-1 id error)
  var trueref = ref.replace(/v_(.*)_.*/,"$1");			// extract ProductID
  var gtotfield = document.getElementById(trueref + '_gtotal');
  var spantest = new RegExp('v_' + trueref + '_\\d+');	// match our component totals
  var gtotal = 0;
    for ( var i=0; i < allperms.length; i++ )
    {
    if ( allperms[i].match(spantest) )			// look for our component totals
      {
      val = permtotals[allperms[i]];				// extract current total
      if ( val < 0 ) 
        {
        gtotal = -1;						// flag invalid values
        }
      else if ( gtotal >= 0 )					// if invalid perm, don't set a price
        {
        gtotal += (val - 0);
        }
      }
    }
  return gtotal;  
}

function displaygrandtotal(ref){				// display grand total if field exists
  var trueref = ref.replace(/v_(.*)_.*/,"$1");			// extract ProductID
  if ( document.getElementById(trueref + '_gtotal') )		// have we a gtotal field
    {
    var gtotfield = document.getElementById(trueref + '_gtotal');
    var gtotal = getgrandtotal(ref);
    var gtothtml;
    if ( gtotal < 0 )						// invalid permutation selection - so invalid total
      {
      gtothtml = '<font color="red">' + currsymbol + '---</font>'
      }
    else
      {
      var ppraw = gtotfield.getAttribute('ppraw');		// it may contain base product price
      if ( ppraw != '' ) gtotal += ppraw * taxrate;		// add in product price if such pricing model
      gtothtml = currsymbol + gtotal.toFixed(2);
      }
    gtotfield.innerHTML = gtothtml;
    }
}

function changeprice(ref){					// called when a choice changes - also on page load to set sub-totals
  var span = document.getElementById(ref + '_clist');		// our drop downs and radios are within this span
  var sels = span.getElementsByTagName('*');			// the list of sub elements (v1.10)	
  var thisperm =  perms[ref];					// array like [[price1,sel1choice,sel2choice,...],[price2,sel1choice,sel2choice,...]]
  var thisselect = new Array();					// list of currently selected option texts
  var idx = 0;
  for ( var i=0; i < sels.length; i++ )					
    {
    thissel = sels[i];
    if (thissel.type == 'select-one')
	{
	thisselect[idx++] = thissel.options[thissel.selectedIndex].value;//  fill list with current selections (v1.10 change)
	}
    if ( (thissel.type == 'radio') && thissel.checked )
	{
	thisselect[idx++] = thissel.value;			//  fill list with current selections (v1.10 change)
	}
    }
  // now see if we've  match
  for ( var i=0; i < thisperm.length; i++ )			// for each permutation row
    {
    var foundit = true;
    thisprice = thisperm[i][0];					// 1st entry is price
    for ( j = 0; j < thisselect.length; j++ )			// each choice within permutation
      {
      if (! ((thisperm[i][j+1] == '-1') || (thisperm[i][j+1] == thisselect[j])) )	// have we "Any choice" or exact match (v1.09 change)
        {
        foundit = false;					// no - so not this combination
        }
      }
    if ( foundit ) break;					// if valid combination, no need to search further
    }
  if ( ! foundit ) 						// the Allow none option
    {
    val = '<font color="gray">' + currsymbol + '0.00</font>';	// set greyed out 0.0
    permtotals[ref] = 0;
    }
  else
    {
    var val = thisprice - 0;					// make numeric	
    if ( val == -1 )
      {
      alert('This combination is unavailable');
      val = '<font color="red">' + currsymbol + '---</font>';
      permtotals[ref] = -1;
      }
    else
      {
      val = val * taxrate;
      permtotals[ref] = val.toFixed(2);
      val = currsymbol + val.toFixed(2);
      }
    }
  if ( document.getElementById(ref + '_ctotal') )
    {
    document.getElementById(ref + '_ctotal').innerHTML = val;	// display price
    }
  displaygrandtotal(ref); 
}

function checkvalidperms(ref){				// return whether permutations valid or not
  if ( getgrandtotal(ref) >= 0 ) return true;
  alert('Invalid combination selected!');
  return false;
}

function setupprices(ref){				// set onchange for drop-downs - called after permutation displayed
  var span = document.getElementById(ref + '_clist');
  var sels = span.getElementsByTagName('select');
  for ( var i=0; i < sels.length; i++ )
    {
    // set form to inhibit add to cart if invalid permutation
    thissel = sels[i];
    if ( ! thissel.form.onsubmit ) thissel.form.onsubmit = function(){return checkvalidperms(ref);};
     thissel.onchange = function(){changeprice(ref);};
    }
  var sels = span.getElementsByTagName('input');	// v1.10 now do radio buttons
  for ( var i=0; i < sels.length; i++ )
    {
    // set form to inhibit add to cart if invalid permutation
    thissel = sels[i];
    if ( ! thissel.form.onsubmit ) thissel.form.onsubmit = function(){return checkvalidperms(ref);};
    if (thissel.type == 'radio') 
	{
	if ( thissel.id == 'redrawbox' )		// UK Map.  Maintain their onclick code if required
		{
		thissel.onclick = function(){reDrawBBox(this);changeprice(ref);};
		}
	else	
		{
		thissel.onclick = function(){changeprice(ref);};
		}
	}
    }
  allperms.push(ref);					// save reference for onload update  
}

function setallprices(){				// called on page load
  for ( var i=0; i < allperms.length; i++ )		// for all components with permutations
    {
    changeprice(allperms[i]);				// display totals
    }
}

// page load - setup DPP
var bDppSet = false;

function startdpp(){
  if ( bDppSet ) return;				// only do once
  bDppSet = true;
  setallprices();
}

// DOM Ready startup
$(document).ready(function(){startdpp();});

