// 24-11-11 V2.01 Renamed global variabes to avoid namespace conflicts
// 24-11-11 V2.00 Now allow checkboxes (with mandatory Associated Product) to be used as well
// 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 dppCommaFormatted(num){
	var sep = ',';
	num = num.toString().split('').reverse().join('');		// reverse number
	num = num.replace(/(\d\d\d)(?=\d)(?!\d*\.)/g,'$1' + sep);	// add commas
	return num.split('').reverse().join('');			// reverse number back;
}

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">' + dpp_currsymbol + '---</font>'
      }
    else
      {
      var ppraw = gtotfield.getAttribute('ppraw');		// it may contain base product price
      if ( ppraw != '' ) gtotal += ppraw * dpp_taxrate;		// add in product price if such pricing model
      gtothtml = dpp_currsymbol + dppCommaFormatted(gtotal.toFixed(2));
      }
    gtotfield.innerHTML = gtothtml;
    }
}

function changeprice(ref){					// called when a choice changes - also on page load to set sub-totals
if ( document.getElementById(ref) && (document.getElementById(ref).type == 'checkbox') )
	{
	var cbox =  document.getElementById(ref);
	var val = cbox.checked ? cbox.getAttribute('price') : 0;
	val = (val * dpp_taxrate).toFixed(2);
	permtotals[ref] = val;
	if ( document.getElementById(ref + '_ctotal') )
		{
		document.getElementById(ref + '_ctotal').innerHTML = dpp_currsymbol + dppCommaFormatted(val);	// display price
		}
	displaygrandtotal(ref);
	return;
	}
  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">' + dpp_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">' + dpp_currsymbol + '---</font>';
      permtotals[ref] = -1;
      }
    else
      {
      val = val * dpp_taxrate;
      permtotals[ref] = val.toFixed(2);
      val = dpp_currsymbol + dppCommaFormatted(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') ) thissel.onclick = function(){changeprice(ref);};
    if ( (thissel.type == 'checkbox') ) 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();
}

// in case we cannot activate on DOM loaded
if (window.attachEvent) 				// IE 
	{ 
	window.attachEvent("onload", startdpp); 
	} 
else 							// DOM
	{  
	window.addEventListener("load", startdpp, false); 
	}

// DOM Ready detect based on www.kryogenix.org/days/2007/09/26/shortloaded
(function(i) {var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st =
setTimeout;if(/webkit/i.test(u)){st(function(){var dr=document.readyState;
if(dr=="loaded"||dr=="complete"){i()}else{st(arguments.callee,10);}},10);}
else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
document.addEventListener("DOMContentLoaded",i,false); } else if(e){     (
function(){var t=document.createElement('doc:rdy');try{t.doScroll('left');
i();t=null;}catch(e){st(arguments.callee,0);}})();}})(startdpp);

