// <![CDATA[
		
// initialisation
function initWink()
{	YAHOO.util.Event.addListener('wink1', 'mouseover', wink);	}	// wink on logo mouseover
function initBuy(divId)
{	showDiv(divId);	// form remains invisible if user has no JS
	document.orderForm.pkgQty.focus();	// init orderForm
}

// copy of the Prototype library function $() = document.getElementById(x)
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}
function showDiv(elementId)
{	var	e = $(elementId);
	e.style.display = 'block';
}

function putEmailAdr(who, site, suffix, subject, label)
{	document.write('<a href=\"mailto:' + who +'@' + site +'.'+ suffix + '?subject=' + subject + '\">');
	document.write(label + '</a>');
}

// clean a numeric string; return null string if invalid number
function  checkNum( str )
{	var	aReg = new RegExp(/^(0|[1-9]\d*)([.,]\d{1,2})?$/);
	if (aReg.test(str) === true)
	{	return str.replace(/,/,'.');	}
	else
	{	return '';	}
}

// make a nice integer
function makeNum(str)
{	if (str === "")
	{	return 0;	}
	else if (str.match(/^\d+$/))	// null on failure
	{	return parseInt(str, 10);	}
	else
	{	return -1;	}
}

// Convert to currency string
function formatCurrency(num, currency)
{	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num))
	{	num = "0";	}
	var sign = (num == (num = Math.abs(num)));	// beware of == coercion here!
	num = Math.floor(num*100+0.50000000001);
	var pence = num%100;
	num = Math.floor(num/100).toString();
	if (pence < 10)
	{    pence = "0" + pence;	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); ++i)
	{    num = num.substring(0, num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));	}
	return (((sign)?'':'-') + currency + num + '.' + pence);
}

// check eg name field
// strip leading/trailing spaces else ignore odd chars & diacriticals
// eg 'André St. John d'Eath-Villiers'
function chkName(name)
{	var returnString = name;
	while(''+returnString.charAt(0)==' ')
	{	returnString=returnString.substring(1,returnString.length);		}
	while(''+returnString.charAt(returnString.length-1)==' ')
	{	returnString=returnString.substring(0,returnString.length-1);	}
	return returnString;
}

// refocus to specified field
function	reFocus(aField)
{	setTimeout(function() { aField.focus(); }, 20);	}

// get a nice date/time for cartID
function	makeDate()
{	var now = new Date();
	var nowISO8601 = now.getFullYear();
	var month = now.getMonth() + 1;
	if (month < 10)	{ nowISO8601 += "-0" + month; }
	else	{ nowISO8601 += "-" + month; }
	if (now.getDate() < 10)		{ nowISO8601 += "-0" + now.getDate(); }
	else	{ nowISO8601 += "-" + now.getDate(); }
	if (now.getHours() < 10)	{ nowISO8601 += "T0" + now.getHours(); }
	else	{ nowISO8601 += "T" + now.getHours(); }
	if (now.getMinutes() < 10)	{ nowISO8601 += ":0" + now.getMinutes(); }
	else	{ nowISO8601 += ":" + now.getMinutes(); }
	if (now.getSeconds() < 10)	{ nowISO8601 += ":0" + now.getSeconds(); }
	else	{ nowISO8601 += ":" + now.getSeconds(); }
var	offset = now.getTimezoneOffset();
	if (offset >= 0) {
		nowISO8601 += "-";
	} else {
		nowISO8601 += "+";
		offset = -offset;
	}
var offsetHours = Math.floor(offset / 60);
var offsetMinutes = offset - offsetHours * 60;
	if (offsetHours < 10)	{ nowISO8601 += "0" + offsetHours; }
	else	{ nowISO8601 += offsetHours; }
	if (offsetMinutes < 10)	{ nowISO8601 += ":0" + offsetMinutes; }
	else	{ nowISO8601 += ":" + offsetMinutes; }
	return nowISO8601;
}

// Determine postage charge for this weight
function postageCharge(weight, region)
{
// Address as rateTable[region][product][GTweight|max|cost]
// var	rateTable = new Array();
// var rateTable = {};
var	rateTable = [];
// UK small packet + signed for; multiples as needed;
rateTable[0] = [ [0, 250, 1.62], [250, 500, 2.14], [500, 1000, 4], [1000, 2000, 7.3], [2000, 3000, 8.97], [3000, 4000, 8.97], [4000, 5000, 12.52], [5000, 6000, 12.52], [6000, 7000, 16.07], [7000, 8000, 16.07], [8000, 9000, 19.62], [9000, 10000, 19.62] ];
// Europe - Airmail + international signed for; multiples as needed; Parcelforce cheaper after 5Kg?
rateTable[1] = [ [0, 250, 2.37], [250, 500, 3.85], [500, 1000, 10.85], [1000, 2000, 12.25], [2000, 3000, 25], [3000, 4000, 30], [4000, 5000, 40], [5000, 6000, 45], [6000, 7000, 55], [7000, 8000, 60], [8000, 9000, 70], [9000, 10000, 75] ];
// Africa, N America, M East - airmail + international signed for (after 0.5Kg); multiples as needed
rateTable[2] = [ [0, 250, 3.64], [250, 500, 6.51], [500, 1000, 15.96], [1000, 2000, 26.96], [2000, 3000, 42.92], [3000, 4000, 53.92], [4000, 5000, 69.88], [5000, 6000, 80.88], [6000, 7000, 96.84], [7000, 8000, 107.84], [8000, 9000, 123.8], [9000, 10000, 134.8] ];
// Rest of the world - as for Africa, N America, M East
rateTable[3] = [ [0, 250, 3.64], [250, 500, 6.51], [500, 1000, 15.96], [1000, 2000, 26.96], [2000, 3000, 42.92], [3000, 4000, 53.92], [4000, 5000, 69.88], [5000, 6000, 80.88], [6000, 7000, 96.84], [7000, 8000, 107.84], [8000, 9000, 123.8], [9000, 10000, 134.8] ];

	if (weight > 0)
	{	for (var i = 0; i < rateTable[region].length; ++i)
		{	if (weight >= rateTable[region][i][0] && weight <= rateTable[region][i][1])
			{	return (rateTable[region][i][2]);	}
		}
	}
	else if (weight === 0)
	{	return 0;	} // ad hoc payment = no postage charge
	return -1;
}

// Calculate final price of all purchases
// description, price(£), weight(gms)
var itemTable = [	['Hidden Depths package of cards, book and stereoscope', 39.00, 925], 
					['Hidden Depths card set', 29.00, 805],
					['Hidden Depths stereoscope', 12.00, 120],
					['Pair of stereoscope lenses', 2.50, 22],
					['Ad hoc payment (by prior agreement)'] ];
function showPrice()
{
// constants
var packWeight = 100;	// weight of carton etc
var maxWeight = 10000;	// not handling more than 10Kg

// variables
var	errorFree = true;
var	priceGoods = 0;
var	pricePost = 0;
var	priceTotal = 0;
var	totalWeight = 0;
var qP, qC, qV, qL;
// calculate total weight of the order
var	txt = document.orderForm.pkgQty.value;
	if ((qP = makeNum(txt)) >= 0)
	{	totalWeight = qP * itemTable[0][2];	}
	else	// deal with negative entries
	{	alert("Invalid package quantity: " + txt);
//		reFocus(document.orderForm.pkgQty);
		qP = 0;
		errorFree = false;
	}
	txt = document.orderForm.cardQty.value;
	if ((qC = makeNum(txt)) >= 0)
	{	totalWeight += qC * itemTable[1][2];	}
	else
	{	alert("Invalid cardset quantity: " + txt);
//		reFocus(document.orderForm.cardQty);
		qC = 0;
		errorFree = false;
	}
	txt = document.orderForm.viewerQty.value;
	if ((qV = makeNum(txt)) >= 0)
	{	totalWeight += qV * itemTable[2][2];	}
	else
	{	alert("Invalid viewer quantity: " + txt);
//		reFocus(document.orderForm.viewerQty);
		qV = 0;
		errorFree = false;
	}
	txt = document.orderForm.lensQty.value;
	if ((qL = makeNum(txt)) >= 0)
	{	totalWeight += qL * itemTable[3][2];	}
	else
	{	alert("Invalid lens quantity: " + txt);
//		reFocus(document.orderForm.lensQty);
		qL = 0;
		errorFree = false;
	}
	txt = document.orderForm.adHocPayment.value;
var	aV = 0;
	if (txt !== '')
	{	var adHocStr = checkNum(txt);
		if (adHocStr === '')
		{	alert("Invalid ad hoc payment entered: " + txt);
			errorFree = false;
		}
		else
		{	aV = (+adHocStr);	}	//type convert
	}

	if (totalWeight !== 0)
	{	totalWeight += packWeight;	}
	// determine postal zone from country
var	countryCode = "";
var zone = 0;
var	code = document.orderForm.country[document.orderForm.country.selectedIndex].value;
	if (totalWeight > maxWeight)
	{	alert("This order is too heavy for standard shipment, please email us for special terms");
		errorFree = false;
	}
	else if (code !== "")	// then a country has been selected
	{	countryCode = code.slice(0, 2);
		zone = makeNum(code.charAt(2));
		pricePost = postageCharge(totalWeight, zone);
	}
	priceGoods = qP*itemTable[0][1] + qC*itemTable[1][1] + qV*itemTable[2][1] + qL*itemTable[3][1] + aV;
	priceTotal = priceGoods + pricePost;
	document.orderForm.price.value = formatCurrency(priceGoods, '£');
	document.orderForm.postage.value = formatCurrency(pricePost, '£');
	document.orderForm.total.value = formatCurrency(priceTotal, '£');
	return errorFree;	// true or false
}

// create fieldset from <node> and label it with <num>
function createNewInputFieldset(fsetName, num)
{	var node, newFs, inFields, f;
	node = $(fsetName);
	newFs = node.cloneNode(true);	// create a new field set
	newFs.setAttribute('name', newFs.getAttribute('name').slice(0, -1) + num);	// rename it
	newFs.setAttribute('id', newFs.getAttribute('id').slice(0, -1) + num);
	inFields = newFs.getElementsByTagName('input');	// list of input fields
	for (var i = 0; i < inFields.length; ++i)	// set them to correct suffix
	{	f = inFields[i];
		f.setAttribute('name', f.getAttribute('name').slice(0, -1) + num);
//		f.setAttribute('id', f.getAttribute('id').slice(0, -1) + num);
	}
	node.parentNode.appendChild(newFs);		// add the new field set to the form
}

function setInputFields(fsetName, fields)
{	var inFields;
	inFields = $(fsetName).getElementsByTagName('input');
	for (var i = 0; i < fields.length; ++i)
	{	inFields[i].setAttribute('value', fields[i]);	}
}
// validate the form, and submit if OK.
// Return False if not - this cancels the orderForm action to allow input correction
function checkSubmit()
{	var	ordered = document.orderForm.pkgQty.value;
	ordered += document.orderForm.cardQty.value;
	ordered += document.orderForm.viewerQty.value;
	ordered += document.orderForm.lensQty.value;
	ordered += document.orderForm.adHocPayment.value;
	if (ordered <= 0)
	{	alert("Nothing ordered!");
		return false;
	}
	if (document.orderForm.country.selectedIndex === 0)
	{	alert("Please select a country for delivery");
		return false;
	}
	if (showPrice() === false)
	{	return false;	}
	return true;
}
function checkSubmit_Google()
{	if (checkSubmit() === false) return false;	
var	G_item = ['', '', '', '', 'GBP'];	// item_name, item_description, item_quantity, item_price, item_currency
	var i = 1;	// point to the first field set, which we will later clone
	if (document.orderForm.pkgQty.value > 0)
	{	G_item[1] = itemTable[0][0];	// package
		G_item[2] = '' + document.orderForm.pkgQty.value;
		G_item[3] = '' + itemTable[0][1];
		setInputFields('GooglePayFields_' + i, G_item);
		createNewInputFieldset('GooglePayFields_1', ++i);
	}
	if (document.orderForm.cardQty.value > 0)
	{	G_item[1] = itemTable[1][0];	// cardset
		G_item[2] = '' + document.orderForm.cardQty.value;
		G_item[3] = '' + itemTable[1][1];
		setInputFields('GooglePayFields_' + i, G_item);
		createNewInputFieldset('GooglePayFields_1', ++i);
	}
	if (document.orderForm.viewerQty.value > 0)
	{	G_item[1] = itemTable[2][0];	// stereoscope
		G_item[2] = '' + document.orderForm.viewerQty.value;
		G_item[3] = '' + itemTable[2][1];
		setInputFields('GooglePayFields_' + i, G_item);
		createNewInputFieldset('GooglePayFields_1', ++i);
	}
	if (document.orderForm.lensQty.value > 0)
	{	G_item[1] = itemTable[3][0];
		G_item[2] = '' + document.orderForm.lensQty.value;
		G_item[3] = '' + itemTable[3][1];
		setInputFields('GooglePayFields_' + i, G_item);
		createNewInputFieldset('GooglePayFields_1', ++i);
	}
	if (document.orderForm.adHocPayment.value > 0)
	{	G_item[1] = itemTable[4][0];
		G_item[2] = '1';
		G_item[3] = '' + document.orderForm.adHocPayment.value;
		setInputFields('GooglePayFields_' + i, G_item);
		createNewInputFieldset('GooglePayFields_1', ++i);
	}
	G_item[1] = 'Postage and packing';
	G_item[2] = '1';
	G_item[3] = document.orderForm.postage.value.slice(1);
	setInputFields('GooglePayFields_' + i, G_item);
	document.GooglePay.submit();
	return false;	// returning false prevents immediate execution of action on orderForm
}

function checkSubmit_Paypal()
{	if (checkSubmit() === false) return false;	
var	P_item = ['', '', ''];	// item_name, quantity, amount
var ship = $('hc');	// set postage value in <handling_cart>
	ship.setAttribute('value', document.orderForm.postage.value.slice(1));
	// point to the first field set, which we will later clone
	var i = 1;
	if (document.orderForm.pkgQty.value > 0)
	{	P_item[0] = itemTable[0][0];
		P_item[1] = '' + document.orderForm.pkgQty.value;
		P_item[2] = '' + itemTable[0][1];
		setInputFields('PaypalPayFields_' + i++, P_item);
	}
	if (document.orderForm.cardQty.value > 0)
	{	if (i > 1)	// then we've used up the first fieldset, so create another
		{	createNewInputFieldset('PaypalPayFields_1', i);	}
		P_item[0] = itemTable[1][0];
		P_item[1] = '' + document.orderForm.cardQty.value;
		P_item[2] = '' + itemTable[1][1];
		setInputFields('PaypalPayFields_' + i++, P_item);
	}
	if (document.orderForm.viewerQty.value > 0)
	{	if (i > 1)
		{	createNewInputFieldset('PaypalPayFields_1', i);	}
		P_item[0] = itemTable[2][0];
		P_item[1] = '' + document.orderForm.viewerQty.value;
		P_item[2] = '' + itemTable[2][1];
		setInputFields('PaypalPayFields_' + i++, P_item);
	}
	if (document.orderForm.lensQty.value > 0)
	{	if (i > 1)
		{	createNewInputFieldset('PaypalPayFields_1', i);	}
		P_item[0] = itemTable[3][0];
		P_item[1] = '' + document.orderForm.lensQty.value;
		P_item[2] = '' + itemTable[3][1];
		setInputFields('PaypalPayFields_' + i++, P_item);
	}
	if (document.orderForm.adHocPayment.value > 0)
	{	if (i > 1)
		{	createNewInputFieldset('PaypalPayFields_1', i);	}
		P_item[0] = itemTable[4][0];
		P_item[1] = '1';
		P_item[2] = '' + document.orderForm.adHocPayment.value;
		setInputFields('PaypalPayFields_' + i, P_item);
	}
	document.PaypalPay.submit();
	return false;	// returning false prevents immediate execution of action on orderForm
}

/**** Simple animation (for winking logo only!) ****/
// This slides an n-image background behind a clear foreground space
function animate(evObject, imageWidth, nImages, totalTime)
{	var offset = imageWidth;
	var dt = totalTime/nImages;
	var tmr = setInterval
	(	function()
		{	if (--nImages <= 1)	// then this was the last image
				clearInterval(tmr);	// so stop the timer
			redraw(evObject, offset);	// slide to the next image
			offset += imageWidth;
		}, dt	// timer interval
	);
}
// NB 'by' may be +ve = forwards, or -ve = backwards
function redraw(ele, by)
{	ele.style.backgroundPosition = -by + "px 0px";	}	// move image L to show next animation on R

function wink(e)	// must be an element (div) with a background image
{	YAHOO.util.Event.removeListener(this.id, "mouseover");	// no more until I've finished
	animate(this, 150, 13, 500);
	setTimeout(initWink, 500);
}

// ]]>
