// Sum Single Add To Cart Pages V1.01

function dp_CommaFormatted(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 dp_totalpage(){
// look in <span class="dp_plist_ProductID">...</span> for sets of prices
if ( $('#dp_totalprice').length == 0 ) return;					// skip if no total on page
var rtot = 0;
var plists = $("span[class^='dp_plist_']");
for (i=0; i<plists.length; i++)
	{
	var pid = plists[i].className.replace('dp_plist_', '');
	var qty = $("input[name='Q_" + pid +"']").val() - 0;
	if ( qty > 0 )												// no need to test 0 quantity items
		{
		var breaks = new Array();
		var prices = new Array();
		var text = $(plists[i]).text().replace(/\s+/mg, ' ');	// remove any whitespace
		text = text.replace(/,/g, '');							// remove commas from prices
		// alert('Entire text: ' + text);
		var lines = text.split('(');							// if we have price breaks they contain "("
		if ( lines.length > 1 ) lines.shift();					// lose descriptive text before 1st price break
		for (j=0; j<lines.length; j++)
			{
			line = lines[j];
			// alert('Trying line: ' + line);
			var bits = line.match(/(\d+) (item\)|or less|or fewer).*£(\d+\.\d\d)/);	// n item)|or less|or fewer
			if ( bits != null )
				{
				breaks.push(0);
				prices.push(bits[3]);
				// alert('Less: ' + bits[1] + ' ' + bits[3]);
				}
			else 
				{
				var bits = line.match(/(\d+)( to | or more).*£(\d+\.\d\d)/);		// nn to nn OR nn or more
				if ( bits != null )
					{
					breaks.push(bits[1]);
					prices.push(bits[3]);
					// alert('To / Or More: ' + bits[1] + ' ' + bits[3]);
					}
				else 
					{
					var bits = line.match(/£(\d+\.\d\d)/);	// none of above, so look for simple single price
					if ( bits != null )
						{
						breaks.push(0);
						prices.push(bits[1]);
						// alert(' Single: ' + bits[1]);
						}
					else alert('Error! Cannor parse price fragment: ' + line + '\r\nWhole text: ' + text);	// unknown price format
					}
				}
			}
		var thisprice = 0;
		for (k=0; k<breaks.length; k++)	
			{
			// alert(breaks[k] + ' ' + prices[k] + ' ' + qty);
			if ( qty >= breaks[k] ) thisprice = prices[k];
			}
		// alert(pid + ' ' + qty + ' ' + thisprice);
		rtot += qty * thisprice;
		}
	}
$('#dp_totalprice').html('&nbsp;Total for above selection: £' + dp_CommaFormatted(rtot.toFixed(2)) + '&nbsp;+ vat');	// display the total
}

$(document).ready(function() { dp_totalpage() });		// deal with page reloads with pre-set form fields.
