// Version 1.09
// 15-10-10 V1.09	Added in capability for selling Foil rolls by area and also calculate weight.
// 17-08-10 V1.08	Added in Weight control.
// 29-04-10 V1.07	Added in NorPrice display.
// 12-04-10 V1.06	Experimental discount based on customer price bands.
// 07-04-10 V1.05	Artwork upload added (allows optional artwork).
// 06-04-09 V1.04	Using EncodedProductAnchor as this is safer with jQuery.
// 06-04-10 V1.03	jQuery based. Changed product layout too.
// 05-04-10 V1.02	Display £--.-- when price not known.
// 04-04-10 V1.01	Added in Info Field.

var infomaxlength = 200;		// maximum length for customer additional info field

var dieprices = new Object();		// Will hold parameters and pricing info for each product id

function getdiscount(span, pid){
	// experimental code - calculate discount from List Price / Your Price text
	var dscfactor = 1;
	var prctext = document.getElementById(span + pid).innerHTML;
	var prcbits = prctext.match(/£\d+\.\d\d/g);	// get all £n.nn entries
	if ( 0 && prcbits )	// temporarily disable
		{
		for ( var i=0; i<prcbits.length; i++ ) prcbits[i] = prcbits[i].replace(/£/,'');
		var numbits = prcbits.length;
		if ( ((numbits == 2) || (numbits == 4)) && (prcbits[0] > 0) )
			{
			dscfactor = prcbits[numbits / 2] / prcbits[0];  // 0th and 1st or 0th and 2nd
			}	  
		}
	return dscfactor;	
}

function setdieparams(pid, prices, minwidth, minheight, maxwidth, maxheight, weightfactor){	// save product specific info
	dieprices[pid] = new Object();
	dieprices[pid].prices = prices;
	dieprices[pid].minwidth = minwidth;
	dieprices[pid].minheight = minheight;
	dieprices[pid].maxwidth = maxwidth;
	dieprices[pid].maxheight = maxheight;
	dieprices[pid].weightfactor = weightfactor;
	dieprices[pid].dscfactor = 1;
	dieprices[pid].dscfactor = getdiscount('ddsc_', pid);
}		

function noenter(ev){				// prevent enter key in text fields from submitting form
	return ((ev.which ? ev.which : ev.keyCode) != '13');
} 

function dielimitlength(th, ev){	// limit length of instructions textarea - called when key pressed
	var key = ev.which ? ev.which : ev.keyCode; 				// the key that was pressed
	return ((key==8)||(key==46)||(th.value.length <= infomaxlength));	// allow backspace and delete
}

function disppricetable(pid){	// diagnostic display of pricing table
	var headings = srg[dieprices[pid].prices].xs;
	var prices = srg[dieprices[pid].prices].ys;
	var html = '<style>#dptable {border:1px solid silver;} #dptable td {text-align:right;}</style>';
	html += 'Diagnostic Info: ' + dieprices[pid].prices + '<table id="dptable">';
	html += '<tr style="background-color: #bbb;"><td>Area</td>';
	for (var i=0; i<headings.length; i++)
		{
		html += '<td>' + headings[i] + '</td>';
		}
	html += '</tr>';
	for (i=0; i<prices.length; i++)
		{
		html += '<tr style="background-color: #ddd;">';
		var row = prices[i];
		for (var j=0; j<row.length; j++)
			{
			html += '<td>' + ((j == 0) ? prices[i][j] : '£' + prices[i][j].toFixed(2)) + '</td>';
			}
		html += '</tr>' ; 
		}
	html += '</table>';
	document.write(html);  
}

function dieprice(el, submitting){	// main calculation routine - called when price changes and before add to cart
	// collect parameters
	var pid = el.id.replace(/.{4}_/,'');				// get anchor from abcd_a1234 (NB Id must be exactly 4 chars before _)
	var prices = srg[dieprices[pid].prices].ys;		// product specific prices structure
	var minwidth = dieprices[pid].minwidth;			// product Minimum Width
	var minheight = dieprices[pid].minheight;			// product Minimum Height			
	var maxwidth = dieprices[pid].maxwidth;			// product Maximum Width
	var maxheight = dieprices[pid].maxheight;			// product Maximum Height			
	var weightfactor = dieprices[pid].weightfactor;			// product Maximum Height			
	var width = $('#dwid_' + pid).val();				// customer entered Width
	var height = $('#dhgt_' + pid).val();				// customer entered Height
	var qty =  $('#dqty_' + pid).val();				// customer entered Quantity
	var custref = $('#dref_' + pid).val();			// customer entered Order Ref.
	var custinfo = $('#dinf_' + pid).val();			// customer entered Other Info
	var artwork = $('#file_' + pid).val();			// customer uploaded file

	if ( artwork == '' ) artwork = 'No artwork uploaded';	// make artwork optional

	// lookup Gauge
	var gauges = new Array(0, '7', '6.35', '5', '3', '1.6');
	if ( dieprices[pid].prices == "copper_foiling") gauges = new Array(0, '7', '6.35', '5.38', '1.63', '1.05');
	var gauge = $("input[id='dgau_" + pid + "']:checked").val();

	// lookup Counter Force (optional)
	var cforces = new Array(0, 'Hard', 'Flexible', 'Not Required');
	var cforceused = $('#dctf_' + pid).length;
	cforce = cforceused ? $("input[id='dctf_" + pid + "']:checked").val() - 0 : 0;

	var errs = '';	

	// check width
	if ( isNaN(width) )
		{
		errs += 'Bad width: ' + width + '\n';
		}	
	else
		{
		if  ( width < minwidth ) errs += 'Width (' + width + ') below minimum allowed. Must be at least ' + minwidth + 'cm.\n';
		if  ( width > maxwidth ) errs += 'Width (' + width + ') above maximum allowed. Must be ' + maxwidth + 'cm. or lower.\n';
		}	

	// check height
	if ( isNaN(height) )
		{
		errs += 'Bad height: ' + height + '\n';
		}	
	else
		{
		if  ( height < minheight ) errs += 'Height (' + height + ') below minimum allowed. Must be at least ' + minheight + 'cm.\n';
		if  ( height > maxheight ) errs += 'Height (' + height + ') above maximum allowed. Must be ' + maxheight + 'cm. or lower.\n';
		}

	// if adding to cart, check that all required options ticked  
	if ( submitting )
		{
		if ( ! gauge ) errs += 'Gauge not selected.' + '\n';
		if ( cforceused && (! cforce) ) errs += 'Counter Force not selected.' + '\n';
		if ( (submitting != 2) && (qty == 0) ) errs += 'Quantity not selected.' + '\n';
		if ( artwork == '' ) errs += 'Artwork not uploaded.' + '\n';
		}
	if ( errs )
		{
		$('#dprc_' + pid).html('£--.--');
		$('#dtot_' + pid).html('£--.--');
		alert(errs);
		return false;
		}

	// see if we've enough info to calculate a price  
	if ( ! gauge ) return false;							// no gauge yet
	if ( cforceused && (! cforce) ) return false;				// no counter force yet

	// lookup price
	var area = width * height;
	var areaband, gaugeprices;
	for ( i=0; i<prices.length; i++)
		{
		gaugeprices = prices[i];								// area, followed by list of prices
		areaband = gaugeprices[0];								// area is first entry
		if ( areaband >= area ) break;
		}

	if ( area > areaband )
		{
		errs = 'Die area (' + area + ') greater than maximum (' + areaband + ') allowed.';
		$('#dprc_' + pid).html('£--.--');
		$('#dtot_' + pid).html('£--.--');
		alert(errs);
		return false;
		}

	// Price calculation	
	var price = gaugeprices[gauge] - 0;						// gauge based price
	if ( (cforce == 1) || (cforce == 2) ) price += gaugeprices[5 + cforce] - 0;	// supplement if Counter Force
	price = price * dieprices[pid].dscfactor;
	price = price.toFixed(2);
	
	// format calculated price
	var unitprice = '£' + price;
	var totprice = '£' + (price * qty).toFixed(2);
	
	// V1.07 - Deal with NorPrice conversion (remove if not using NorPrice V2) 
	if ( choicealtprice )
		{
		unitprice = cnvtext(unitprice, true);
		totprice = cnvtext(totprice, true);
		}
	
	// display prices
	$('#dprc_' + pid).html(unitprice);
	$('#dtot_' + pid).html(totprice);
	
	var ovr = price 
		+ '¦Width¬' + width + '¬cm'
		+ '¦Height¬' + height + '¬cm'
		+ '¦Gauge¬' + gauges[gauge] + '¬mm';
	if ( cforce )		ovr += '¦C. Force¬' + cforces[cforce] + '¬';
	if ( custref )	ovr += '¦Cust. Ref.¬' + custref.replace(/[¦¬]/g, ' ') + '¬';
	if ( custinfo )	ovr += '¦Notes¬' + custinfo.replace(/[¦¬]/g, ' ') + '¬';
	if ( artwork )	ovr += '¦Artwork¬' + artwork + '¬';

	// weight calculation
	var weight = (area * gauges[gauge] * weightfactor).toFixed(1);				// weight in Kg to nearest 100g
	if ( weight - 0 )	ovr += '¦Weight¬' + weight + '¬Kg';

	$('#ovr_' + pid).val(ovr);	
	return true;  
} 

// Additional code for Foil pricing

var foilitems = new Object();

function setfoilparams(pid, pricepersqmetre, weightfactor){
	foilitems[pid] = new Object();
	foilitems[pid].pricepersqmetre = pricepersqmetre;
	foilitems[pid].weightfactor = weightfactor;
	foilitems[pid].dscfactor = 1;
	foilitems[pid].dscfactor = getdiscount('fdsc_', pid);
}

function foilprice(pid){
	var weightfactor = foilitems[pid].weightfactor;
	var pricepersqmetre = foilitems[pid].pricepersqmetre;
	var width = $("#fwid_" + pid).val();
	var length = $("input[id='flen_" + pid + "']:checked").val();
	var area = (width / 1000 * length).toFixed(2);
	var weight = (area * weightfactor).toFixed(2);
	var price = (area * pricepersqmetre * foilitems[pid].dscfactor).toFixed(2);
	$('#fprc_' + pid).html('£' + price);
	$('#ovr_' + pid).val(price + '¦Roll Width¬' + width + '¬mm¦Length¬' + length + '¬M¦Area¬' + area + '¬Sq M¦Weight¬' + weight + '¬Kg');
}





