<!--
// calculate form field values for order form

function initForm()
{
	subtotal = 0;
	totalQuantity = 0;
	itemPostage = 0;
	itemTotal = 0;
	populatePrices();

	costTracker = new Array();
	for (i=1; i<=totalItems; i++)
	{
		costTracker[i] = 0
	}
}

function generateHiddens()
{
	// write form fields to page containing item names (for output email)
	for (i=1; i<=totalItems; i++)
	{
		var name = eval('item' + i +'[\'name\']')
		document.write('<input name="item' + i + 'Name" type="hidden" id="item' + i + 'Name" value="' + name + '">')
		document.write('<input name="item' + i + 'Output" type="hidden" id="item' + i + 'Output" value="">')
	}
}

function cent(amount)
{
// returns the amount in the .99 format
    amount -= 0;
    amount = (Math.round(amount*100))/100;
    return (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}

function reformatIfZero(amount)
{
	if (amount == '$0.00')
	{
		amount = '$    .  '
	}
	return (amount);
}

function populatePrices()
{
	// populate item price fields with default values out of item price arrays
	for (i=1; i<=totalItems; i++)
	{
		var itemPrice = eval('document.order.item' + i + 'Price')
		var itemDefaultPrice = eval('item' + i + '[0]')
		itemPrice.value = itemDefaultPrice
	}
}

function splitQuantity(quantity)
{
	// separate selected value into two halves - (eg "3_1" becomes "3" & "1")
	var midPoint = quantity.indexOf("_")
	qtyInBox = quantity.substring(0,midPoint)
	qtyOfBoxes = quantity.substring((midPoint+1)) // no final index specified so rest of string will be returned
}

function calculateItemCost(id)
{
	// update item price field to show correct price for differently sized boxes

	var dualQuantity = eval('document.order.item' + id + 'Qty.options[document.order.item' + id + 'Qty.selectedIndex].value') // NS4 compliant

	splitQuantity(dualQuantity)

	// replace visible item price with value stored in item price array
	var price = eval('document.order.item' + id + 'Price')
	var itemReplacementPrice = eval('item' + id + '[' + Number(qtyInBox) + ']')
	price.value = itemReplacementPrice

	price = price.value

	// process - strip out formatting to enable math equations
	price = price.replace(/\$/,"")
	price = price.replace(/\./,"")

	var cost = ((price * qtyOfBoxes) / 100)

	// show cents as .90, not .9 [2dp]
	cost2dp = cent(cost)

	// update item cost tracking variable (for calculation of subtotal)
	// Note that costTracking variable isn't formatted with '$' etc, or 2dp)
	eval('costTracker[' + id + '] = cost')

	// replace [$  . ] formatting
	cost = ('$' + cost2dp)
	cost = reformatIfZero(cost)

	// update visible item cost field
	eval('document.order.item' + id + 'Cost' + '.value = cost')

	// reset subtotal
	subtotal = 0

	// (totalItems defined on page load) - add up cost of all items
	for (i=0; i<totalItems; i++)
	{
		subtotal += Number(eval('costTracker[' + (i+1) + ']'))
	}

	// reset totalQuantity
	totalQuantity = 0

	// add up quantity of items (for postage rate)
	for (i=0; i<totalItems; i++)
	{
		partQuantity = eval('document.order.item' + (i+1) + 'Qty.options[document.order.item' + (i+1) + 'Qty.selectedIndex].value') // NS4 compliant

		splitQuantity(partQuantity)
		totalQuantity += Number(qtyOfBoxes)
	}

	// recalculate postage amount (qty affects postage amount)
	calculatePostageCost()

	// recalculate total amount
	calculateTotal()

	// update what user sees
	updateFields()
}

function calculatePostageCost()
{
	whichPostalZone = eval('document.order.postalZone.options[document.order.postalZone.selectedIndex].value') // NS4 compliant

	/*
		0 = Australia
		1 = South Pacific
		2 = East Asia & North America
		3 = UK and Europe
		4 = Rest of the World
		5 = New Zealand
	*/

	// rate per 100 grams (pull in from page variables so client does not need to touch THIS script file when updating values)

	// user selects an item but no postalZone selected yet, or user reverts to default position (default value == 9)

	if (whichPostalZone == 9)
	{
		// if no items selected
		itemPostage = -1
	}

	else if (whichPostalZone < 5){
		postalZoneRate = eval('postalZone' + whichPostalZone + 'Rate')
		postalZoneBase = eval('postalZone' + whichPostalZone + 'Base')

		if (totalQuantity == 0){
			// if no items selected
			itemPostage = 0
		}
		// 040803 - no minimum order for international:

		// else if (totalQuantity <7)
		// {
		// 	itemPostage = (postalZoneRate * 6)
		// }
		// else if (totalQuantity >=7)
		else{
			itemPostage = postalZoneBase + (postalZoneRate * (totalQuantity - 1));
		}
		//alert(totalQuantity);
	}

	// NZ
	else if (whichPostalZone == 5){
		postalZoneRate = eval('postalZone' + whichPostalZone + 'Rate')
		postalZoneBase = eval('postalZone' + whichPostalZone + 'Base')
		postalZoneMax = eval('postalZone' + whichPostalZone + 'Max')

		if (totalQuantity == 0)
		{
			// if no items selected
			itemPostage = 0
		}

		//else if (totalQuantity <7)
		//{
		//	// need *1 to convert to number
		//	itemPostage = (postalZoneMinRate * 1)
		//}
		//else if (totalQuantity >=7)
		//{
		//	// need *1 to convert to number
		//	itemPostage = (postalZoneMaxRate * 1)
		//}
		else {
			itemPostage = postalZoneBase + (postalZoneRate * (totalQuantity - 1));

			if (itemPostage > postalZoneMax) {
				itemPostage = postalZoneMax;
			}
		}
	}

	// recalculate total amount
	calculateTotal()

	// update what user sees
	updateFields()
}

function calculateTotal()
{
	if (itemPostage == -1)
	{
		itemPostage = 0

		// reset itemTotal (don't calculate as no postage amount chosen yet)
		itemTotal = 0

		// update what user sees
		updateFields()
	}

	else if ((itemPostage != 0) && (itemPostage != -1))
	{
		// reset itemTotal
		itemTotal = 0

		// calculate itemTotal
		itemTotal = Number(subtotal + itemPostage);

		// update what user sees
		updateFields()
	}
}

function updateFields()
{
	// format and output

	// SUBTOTAL

		// show cents as .90, not .9 [2dp]
		subtotal2dp = cent(subtotal)

		// replace [$  . ] formatting
		subtotalFormatted = ('$' + subtotal2dp)
		subtotalFormatted = reformatIfZero(subtotalFormatted)

		// update visible subtotal field
		eval('document.order.itemSubtotal.value = subtotalFormatted')

	// POSTAGE

		// show cents as .90, not .9 [2dp]
		itemPostage2dp = cent(itemPostage)

		// add [$  . ] formatting
		itemPostageFormatted = ('$' + itemPostage2dp)
		itemPostageFormatted = reformatIfZero(itemPostageFormatted)

		// update visible itemPostage field
		eval('document.order.itemPostage.value = itemPostageFormatted')

	// TOTAL

		// show cents as .90, not .9 [2dp]
		itemTotal2dp = cent(itemTotal)

		// add [$  . ] formatting
		itemTotalFormatted = ('$' + itemTotal2dp)
		itemTotalFormatted = reformatIfZero(itemTotalFormatted)

		// update visible itemTotal field
		eval('document.order.itemTotal.value = itemTotalFormatted')
}

// form validation

// Replaces text with by in string
function replace(string,text,by)
{
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0))
	{
		return string;
	}

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength)))
	{
		return string;
	}

    if (i == -1)
	{
		return string;
	}

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
	{
        newstr += replace(string.substring(i+txtLength,strLength),text,by);
	}

    return newstr;
}

updatedErrorMessage = ''

function updateErrorMessage(errorMessage)
{
	errorI ++
	errorIndex = (errorI + '. ')
	if (errorIndex.length < 4)
	{
		errorIndex = (' ' + errorIndex)
	}
	updatedErrorMessage += (errorIndex + errorMessage + '\n')
}

function checkEmail (field, errorMessage, notValidMessage, illegalCharsMessage)
{
	if (field == "")
	{
		updateErrorMessage(errorMessage)
	}

	var emailFilter=/^.+@.+\..{2,3}$/;
	if ((!(emailFilter.test(field))) && (field != "")) // avoid multiple errors
	{
		updateErrorMessage(notValidMessage)
	}
	else
	{
		//test email for illegal characters
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
		/* \\" Haxd in because the lack of formatting information from the unclosed tag annoys me. */
		if ((field.match(illegalChars)) && (field != "")) // avoid multiple errors
		{
			updateErrorMessage(illegalCharsMessage)
		}
	}
}

function checkPhone (field, errorMessage, badDataMessage)
{
	if (field == "")
	{
		updateErrorMessage(errorMessage)
	}

	var stripped = field.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters

	if ((isNaN(parseInt(stripped))) && (field != "")) // avoid multiple errors
	{
		updateErrorMessage(badDataMessage)
	}
}

function isEmpty(field, errorMessage) // textbox
{
	if (field.length == 0)
	{
		updateErrorMessage(errorMessage)
	}
}

function compareFields(field1, field2, errorMessage) // textbox
{
	if ((field1 != '') && (field2 != field1))
	{
		updateErrorMessage(errorMessage)
	}
}

function checkRadio(radioGroup, errorMessage)
{
	checked = false

	for (i=0; i<radioGroup.length; i++)
	{
        if (radioGroup[i].checked)
		{
			checked = true
			break
		}
	}

	if (checked	!= true)
	{
		updateErrorMessage(errorMessage)
	}
}

function checkDropdown(fieldSelected, errorMessage)
{
	if (fieldSelected == 0)
	{
		updateErrorMessage(errorMessage)
	}
}

function validate(formName)
{
    why = "";
	errorI = 0
	errorIndex = ''

	// item sub total
	var subTotal = document.order.itemSubtotal.value

	if ((subTotal.charAt(1) != '1') && (subTotal.charAt(1) != '2') && (subTotal.charAt(1) != '3') && (subTotal.charAt(1) != '4') && (subTotal.charAt(1) != '5') && (subTotal.charAt(1) != '6') && (subTotal.charAt(1) != '7') && (subTotal.charAt(1) != '8') && (subTotal.charAt(1) != '9'))
	{
		updateErrorMessage('Your order form is empty. Please select one or more items for purchase.')
	}
	else if (document.order.postalZone.selectedIndex == 0) // default dropdown value for item postage
	{
		updateErrorMessage('Please select your Postal Zone, so that we can calculate postage & packaging.')
	}
	// name
	 isEmpty(document.order.name.value, 'Please enter your Name');
	// email
	 checkEmail(document.order.email.value, 'Please enter your Email Address', 'Please re-enter a Valid Email Address', 'Your Email Address contains one or more of the following illegal characters ( ) < > [ ] , ; : \\ / \"');
	// phone
	 checkPhone(document.order.phone.value, 'Please enter your Phone Number', 'Please re-enter your Phone Number so that the field contains only numbers');
	// address
	 isEmpty(document.order.address.value, 'Please enter your Address');
	// cityZip
	 isEmpty(document.order.cityZip.value, 'Please enter your City/Zip');
	// country
	 checkDropdown(document.order.country.selectedIndex, 'Please select your Country from the drop-down menu');

	// deliveryAddress
	 isEmpty(document.order.deliveryAddress.value, 'Please enter your delivery Address');
	// deliveryCityZip
	 isEmpty(document.order.deliveryCityZip.value, 'Please enter your delivery City/Zip');
	// deliveryCountry
	 checkDropdown(document.order.deliveryCountry.selectedIndex, 'Please select your delivery Country from the drop-down menu');

	// create alert message from all erroneous fields
    if (updatedErrorMessage != "")
	{
		if (errorI > 1)
		{
			var errorIntro1 = ('There were ' + errorI + ' problems ')
		}
		else
		{
			var errorIntro1 = ('There was 1 problem ')
		}
		var errorIntro2 = 'with your form:\n\n'
		if (errorI > 1)
		{
			var errorOutro1 = 'Please make the necessary corrections,'
		}
		else
		{
			var errorOutro1 = 'Please make the necessary correction,'
		}
		var errorOutro2 = ' then resubmit the form.\n\n'
		alert(errorIntro1 + errorIntro2 + updatedErrorMessage + '\n' + errorOutro1 + errorOutro2);
		errorI = 0
		errorIndex = ''
		updatedErrorMessage = ''

		return false;
    }

	prepareForOutput()

	return true;
}

function prepareForOutput()
{
	// reformat form vars for easy readability
	for (i=1; i<=totalItems; i++)
	{
		iQty = eval('document.order.item' + i + 'Qty.options[document.order.item' + i + 'Qty.selectedIndex]')
		iPrice = eval('document.order.item' + i + 'Price')
		iCost = eval('document.order.item' + i + 'Cost')
		iName = eval('document.order.item' + i + 'Name')

		var fieldContents = eval('document.order.item' + i + 'Qty.options[document.order.item' + i + 'Qty.selectedIndex].value') // NS4 compliant
		if (fieldContents == 0) // 0 is default value and means no Qty has been selected
		{
			// wipe vars so not output (formmail print_blank_fields is off)
			//iQty.value = ""
			//iPrice.value = ""
			//iCost.value = ""
			//iName.value = ""
		}
		else if (fieldContents != 0)
		{
			splitQuantity(fieldContents)
			// discard qty in box value
			eval('document.order.item' + i + 'Qty.options[document.order.item' + i + 'Qty.selectedIndex].value = qtyOfBoxes')

			// output all relevant parameters as a big, sexy, per item string
			eval('document.order.item' + i + 'Output.value = "' + iQty.value + ' x ' + iName.value + ' (@ ' + iPrice.value + ' per ' + qtyInBox + ') = ' + iCost.value + '"')

			// now wipe vars so not output (formmail print_blank_fields is off)
			//iQty.value = ""
			//iPrice.value = ""
			//iCost.value = ""
			//iName.value = ""
		}

		document.order.itemSubtotal.value = ''

		// TOTAL

		// show cents as .90, not .9 [2dp]
		itemTotal2dp = cent(itemTotal)

		// populate hidden field for 2day securecard
		eval('document.order.scAMOUNT.value = itemTotal2dp')
	}
}
//-->