// JavaScript Document

// doCheckContactForm:
// function for checking the contact us form in about/contact.html
// DRE 8-2-2010
function doCheckContactForm()
{
	var select = document.contactus.recipient.selectedIndex;
	var rcpt = document.contactus.recipient;
	var okay = false;

	// check the product and platform are completed
	if (rcpt[select].value == "unknown") {
		alert("Please select a recipient");
		document.contactus.recipient.focus();
	}
	// now check the required fields have something in
	else if (document.contactus.firstname.value == "")  {
		alert("Please enter your first name");
		document.contactus.firstname.focus();
	}
	else if (document.contactus.surname.value == "")  {
		alert("Please enter your surname");
		document.contactus.surname.focus();
	}
	else if (document.contactus.username.value == "")  {
		alert("Please enter your e-mail address");
		document.contactus.username.focus();
	}
	else if (validate_email(document.contactus.username) == false)  {
		alert("Please enter a valid e-mail address");
		document.contactus.username.focus();
	}
	else if (document.contactus.enquiry.value == "")  {
		alert("Please enter a message in the query box");
		document.contactus.enquiry.focus();
	}
	else {
		// apparently nothing wrong or missing
		okay = true;
	}

	return(okay);
}


// doCheckSubscribeForm:
// function for checking the subscribe to e-mail form on the home page
// DRE 10-3-2011
function doCheckSubscribeForm()
{
	var okay = false;

	// now check the required fields have something in
	if (document.contactus.firstname.value == "")  {
		alert("Please enter your first name");
		document.contactus.firstname.focus();
	}
	else if (document.contactus.surname.value == "")  {
		alert("Please enter your surname");
		document.contactus.surname.focus();
	}
	else if (document.contactus.username.value == "")  {
		alert("Please enter your e-mail address");
		document.contactus.username.focus();
	}
	else if (validate_email(document.contactus.username) == false)  {
		alert("Please enter a valid e-mail address");
		document.contactus.username.focus();
	}
	else {
		// apparently nothing wrong or missing
		okay = true;
	}

	return(okay);
}


// doProduct:
// function for checking the product download form in products/download.html
// DRE 16-2-2010
//
// Original version DRE 16-10-2003
// Revised DRE 4-1-2007 to add Linux platform for Date Stamp
// Revised DRE 14-1-2008 to show supported Acrobat versions only (Date Stamp does not work with Acrobat 8.*)
// Revised DRE 29-1-2009 to remove products no longer supported
// Revised DRE 29-11-2010 to show Acrobat 10
function doProduct()
{
	doPlatforms();
	doAcrobat();
}

function doPlatforms()
{
	var i, n;
	var select = document.download.product.selectedIndex;
	var prod = document.download.product;

	n = document.download.platform.length;
	for (i = n - 1; i >= 1; i--)
	{
		document.download.platform[i] = null;
	}
	if (prod[select].value == "unknown")
	{
		document.download.platform[1] = new Option("HP-UX");
		document.download.platform[2] = new Option("Linux");
		document.download.platform[3] = new Option("Macintosh");
		document.download.platform[4] = new Option("Solaris");
		document.download.platform[5] = new Option("Windows");
		document.download.platform.selectedIndex = 0;
	}
	if (
		(prod[select].text == "Name It")
		|| (prod[select].text == "Search Results Printer")
		|| (prod[select].text == "View Info")
	)
	{
		document.download.platform[1] = new Option("Windows");
		document.download.platform.selectedIndex = 1;
	}
	if (prod[select].text == "Date Stamp")
	{
		document.download.platform[1] = new Option("Linux");
		document.download.platform[2] = new Option("Windows");
		document.download.platform.selectedIndex = 0;
	}
	if (prod[select].text == "Name It Launcher")
	{
		document.download.platform[1] = new Option("HP-UX");
		document.download.platform[2] = new Option("Solaris");
		document.download.platform[3] = new Option("Windows");
		document.download.platform.selectedIndex = 0;
	}
	if (prod[select].text == "Options")
	{
		//document.download.platform[1] = new Option("Macintosh");
		document.download.platform[1] = new Option("Windows");
		document.download.platform.selectedIndex = 1;
	}
}

function doAcrobat()
{
	var i, n;
	var select = document.download.product.selectedIndex;
	var prod = document.download.product;

	n = document.download.acrobat.length;
	for (i = n - 1; i >= 1; i--)
	{
		document.download.acrobat[i] = null;
	}
	if (prod[select].value == "unknown")
	{
		n = 1;
		document.download.acrobat[n++] = new Option("10.*", 10);
		document.download.acrobat[n++] = new Option("9.*", 9);
		document.download.acrobat[n++] = new Option("8.*", 8);
		document.download.acrobat[n++] = new Option("7.*", 7);
		document.download.acrobat[n++] = new Option("6.*", 6);
		document.download.acrobat[n++] = new Option("5.*", 5);
		document.download.acrobat[n++] = new Option("4.*", 4);
		document.download.acrobat[n++] = new Option("3.*", 3);
		document.download.acrobat.selectedIndex = 0;
	}
	else
	{
		n = 1;
		document.download.acrobat[n++] = new Option("10.*", 10);
		document.download.acrobat[n++] = new Option("9.*", 9);
		if (prod[select].text != "Date Stamp")
		{
			// Date Stamp does not work with Acrobat 8
			document.download.acrobat[n++] = new Option("8.*", 8);
		}
		document.download.acrobat[n++] = new Option("7.*", 7);
		document.download.acrobat[n++] = new Option("6.*", 6);
		document.download.acrobat[n++] = new Option("5.*", 5);
		document.download.acrobat[n++] = new Option("4.*", 4)
		document.download.acrobat[n++] = new Option("3.*", 3);
		document.download.acrobat.selectedIndex = 0;
	}
}

// Check the e-mail address -- the text must contain at least an @ sign and a dot (.).
// The @ must not be the first character of the email address,
// and the last dot must at least be one character after the @ sign
function validate_email(field)
{
	with (field) {
		apos = value.indexOf("@");
		dotpos = value.lastIndexOf(".");
		if (apos < 1 || dotpos - apos < 2) {
			return false;
		} else {
			return true;
		}
	  }
}

function doCheckForm()
{
	var select = document.download.product.selectedIndex;
	var prod = document.download.product;
	var okay = false;

	// check the product and platform are completed
	if (prod[select].value == "unknown") {
		alert("Please select the product to download");
		document.download.product.focus();
	}
	else if (document.download.platform.value == "unknown") {
		alert("Please select the platform for " + prod[select].text);
		document.download.platform.focus();
	}
	else if (document.download.acrobat.value == "unknown") {
		alert("Please select the version of Acrobat that you will be using with " + prod[select].text);
		document.download.acrobat.focus();
	}
	// now check the required fields have something in
	else if (document.download.forename.value == "")  {
		alert("Please enter your first name");
		document.download.forename.focus();
	}
	else if (document.download.surname.value == "")  {
		alert("Please enter your surname");
		document.download.surname.focus();
	}
	else if (document.download.address1.value == "")  {
		alert("Please enter your address");
		document.download.address1.focus();
	}
	else if (document.download.city.value == "")  {
		alert("Please enter your town/city");
		document.download.city.focus();
	}
	else if (document.download.country.value == "" || document.download.country.value.length < 2)  {
		alert("Please enter your country");
		document.download.country.focus();
	}
	else if (document.download.postcode.value == "")  {
		alert("Please enter your post code");
		document.download.postcode.focus();
	}
	else if (document.download.username.value == "" || validate_email(document.download.username) == false)  {
		alert("Please enter a valid e-mail address");
		document.download.username.focus();
	}
	else {
		// apparently nothing wrong or missing
		okay = true;
	}

	return(okay);
}


// checkLocation:
// DRE 18-2-2010
// called via the onsubmit callback in the add to cart form
// find out the customer's country and set the VAT rate appropriately
// pass through the customer's VAT number in the custom field
// DRE 21-12-2010
// Revised so that new 20% VAT rate automatically applied from 4th January 2011
// N.B. Remember also to change the VAT rate in the JavaScript in the PDF order form order.pdf
//      for direct purchases and payment by bank transfer!
function checkLocation(form)
{
	var okay = false;
	var debug = false;

	try {
		var rate = form.tax_rate;
		var custom = form.custom;

		// get customer's region from the cookie, if set
		var region = getRegion();
		if (region == "") {
			// force customer to set region before items may be added to the shopping cart
			window.open("http://www.merlin-os.co.uk/products/location.html", "location",
						"menubar=no,scrollbars=yes,modal=yes,dialog=yes"); // innerWidth=800 not needed?
		} else {
			// get buyer's country code and VAT number
			// and work out VAT rate
			if (region == "uk" || region == "eu") {
				var vat_number = getCookie('vat_number');

				if (vat_number != null && vat_number.length > 0) {
					// pass VAT number through in the custom field
					if (custom == null) {
						custom = document.createElement("input");
						custom.name = "custom";
						custom.type = "hidden";
						form.appendChild(custom);
					}
					custom.value = vat_number;
				}

				// pay VAT at UK rate if a customer is from UK, or EU with no VAT number
				if (region == "uk" || vat_number == null || vat_number.length == 0) {
					if (rate == null) {
						rate = document.createElement("input");
						rate.name = "tax_rate";
						rate.type = "hidden";
						form.appendChild(rate);
					}
					// apply new VAT rate from 4th January 2011
					var today = new Date();
					var changeDate = new Date();
					// date is year in full, month [0..11], day [1..31]
					// 4th January 2011
					changeDate.setFullYear(2011, 0, 4);
					if (today >= changeDate) {
						rate.value = "20.0";
					} else {
						// for safety, this is set to 20% as it is now after 4th January 2011
						// (was 17.5%)
						rate.value = "20.0";
					}
				}
			} // region is UK or EU

			if (debug == true) {
				alert("VAT number: "
					  + (form.custom ? form.custom.value : "n/a")
					  + "\nVAT rate: "
					  + (form.tax_rate ? form.tax_rate.value : "0") + "%");
			}

			// got the required information, so may add item to the shopping cart
			if (debug == false) okay = true;
		}
	} catch(err) {
		var txt="There was an error on this page.\n\n";
		txt += "Error description: " + err.description + "\n\n";
		txt += "Click OK to continue.\n\n";
		alert(txt);
		okay = false;
	}

	return(okay);
}


// checkForUpgrade:
// DRE 19-4-2011:
// check if an upgrade is being added to the basket
// if so, warn that we will check that the customer has a product to upgrade
function checkForUpgrade(form)
{
	var desc = form.os0.value;

	if (desc.match(/upgrade/i) != null) {
		alert("Thank you for ordering an upgrade.\n" +
			  "We will check our records to verify your current product details.");
	}
}


function getCookie(c_name)
{
  if (document.cookie.length > 0) {
	c_start = document.cookie.indexOf(c_name + "=");
	if (c_start != -1) {
	  c_start = c_start + c_name.length + 1;
	  c_end = document.cookie.indexOf(";", c_start);
	  if (c_end == -1) c_end = document.cookie.length;
	  return unescape(document.cookie.substring(c_start, c_end));
	}
  }
  return "";
}


// setCookie:
// create a cookie with the given name and value, and expiry date
// add a path of "/" so valid throughout domain
function setCookie(c_name,value,expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value)
		+ ((expiredays == null) ? "" : "; expires="
		+ exdate.toGMTString()
		+ "; path=/");
}


function deleteCookie(c_name)
{
	setCookie(c_name, "", -1);
}


function clearLocation()
{
	deleteCookie('country');
	deleteCookie('vat_number');
	showRegion();
}


// setLocation:
// DRE 19-2-2010
// find out the customer's region and save the country and VAT number, if applicable,
// in a cookie
function setLocation()
{
	var min_length = 4;		// minimum length of a VAT number including country code
	var expiredays = 365;	// how long we keep the information in the cookie
	var okay = false;
	var country = "";
	var vat_number = "";
	var region = document.location.region;

	if (region != null) {
		// find the selected region
		for (var i = 0; i < region.length; i++) {
			if (region[i].checked == true) {
				country = region[i].value;
				break;
			}
		}

		if (country == "eu") {
			// find EU member state and VAT number, if provided
			var cc = document.location.country_code;
			if (cc != null) {
				country = cc.options[cc.selectedIndex].value;
			}
			var vat = document.location.vat_number;
			if ((vat != null) && (vat.value.length > 0) && (country != "EU") && (country != "eu")) {
				vat_number = country + vat.value;
			}
		}

		country = country.toUpperCase();
		vat_number = vat_number.toUpperCase();

		if (country == "") {
			// ask user to select a region
			alert("Please select which region you are located in");
			region.focus();
		} else if ((country != "UK") && (country != "WORLD")
				&& (vat_number.length > 0) && (vat_number.length < min_length)) {
			// EU countries can either have no VAT number, or a valid one
			alert("The VAT number '" + vat_number + "' is too short");
			document.location.vat_number.focus();
		} else if ((country != "UK") && (country != "WORLD")
				&& (vat_number.length > 0) && !validateVATnumber(vat_number)) {
			alert("The VAT number '" + vat_number + "' is not valid");
			document.location.vat_number.focus();
		} else {
			// save the information
			setCookie('country', country, expiredays);
			setCookie('vat_number', vat_number, expiredays);
			okay = true;
		}
	}

	// if set, close window if this is the location pop-up window
	// i.e. called from an add to cart button
	if (okay && window.name == "location") {
		window.close();
	}

	// update region div on page too
	showRegion();

	return(okay);
}


// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
  var re = /[^a-zA-Z]/g
  if (re.test(str)) return false;
  return true;
}


// returns true if the string only contains characters 0-9
function isNumeric(str){
  var re = /[\D]/g
  if (re.test(str)) return false;
  return true;
}


// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
  var re = /[^a-zA-Z0-9]/g
  if (re.test(str)) return false;
  return true;
}


// validateVATnumber:
// DRE 23-2-2010
// Do a check that the number format provided is as expected.
// Return true if the number is valid, false if not.
// It is not currently possible to check on-line from a script that
// the number provided is a valid number of a real business. You need to
// go to the Europa web site and check the number manually to fully verify it.
function validateVATnumber(vat_number)
{
	var okay = false;
	var cc = vat_number.substring(0, 2);
	var n = vat_number.length - 2;
	var num = vat_number.substring(2, vat_number.length);

	// VAT numbers may be organised in several blocks of digits and/or characters
	// we will remove the spaces here for the comparison
	num = num.replace(/ /g, "");

	if (cc == "AT" && n == 9 && num.charAt(0) == "U" && isAlphaNumeric(num)) {
		// AT - U + 8 chars
		okay = true;
	} else if (cc == "BE" && n == 10 && num.charAt(0) == "0" && isNumeric(num)) {
		// BE - 0 + 9 digits
		okay = true;
	} else if (cc == "BG" && n >= 9 && n <= 10 && isNumeric(num)) {
		// BG - 9 or 10 digits
		okay = true;
	} else if (cc == "CY" && n == 9 && isAlphaNumeric(num)) {
		// CY - 9 chars
		okay = true;
	} else if (cc == "CZ" && n >= 8 && n <= 10 && isNumeric(num)) {
		// CZ - 8-10 digits
		okay = true;
	} else if (cc == "DE" && n == 9 && isNumeric(num)) {
		// DE - 9 digits
		okay = true;
	} else if (cc == "DK" && n == 8 && isNumeric(num)) {
		// DK - 4 blocks of 2 digits
		okay = true;
	} else if (cc == "EE" && n == 9 && isNumeric(num)) {
		// EE - 9 digits
		okay = true;
	} else if (cc == "EL" && n == 9 && isNumeric(num)) {
		// EL - 9 digits
		okay = true;
	} else if (cc == "ES" && n == 9 && isAlphaNumeric(num)) {
		// ES - 9 chars
		okay = true;
	} else if (cc == "FI" && n == 8 && isNumeric(num)) {
		// FI- 8 digits
		okay = true;
	} else if (cc == "FR" && n == 11
			   && isAlpha(num.substring(0, 2)) && isNumeric(num.substring(2, n))) {
		// FR - 1 block of 2 characters, 1 block of 9 digits
		okay = true;
	} else if (cc == "HU" && n == 8 && isNumeric(num)) {
		// HU - 8 digits
		okay = true;
	} else if (cc == "IE" && n == 8 && isAlphaNumeric(num)) {
		// IE - 8 characters
		okay = true;
	} else if (cc == "IT" && n == 11 && isNumeric(num)) {
		// IT - 11 digits
		okay = true;
	} else if (cc == "LT" && (n == 9 || n == 12) && isNumeric(num)) {
		// LT - 9 digits or 12 digits
		okay = true;
	} else if (cc == "LU" && n == 8 && isNumeric(num)) {
		// LU - 8 digits
		okay = true;
	} else if (cc == "LV" && n == 11 && isNumeric(num)) {
		// LV - 11 digits
		okay = true;
	} else if (cc == "MT" && n == 8 && isNumeric(num)) {
		// MT - 8 digits
		okay = true;
	} else if (cc == "NL" && n == 12 && isAlphaNumeric(num) && num.charAt(9) == "B") {
		// NL - 12 characters, 10th character is always a B
		okay = true;
	} else if (cc == "PL" && n == 10 && isNumeric(num)) {
		// PL - 10 digits
		okay = true;
	} else if (cc == "PT" && n == 9 && isNumeric(num)) {
		// PT - 9 digits
		okay = true;
	} else if (cc == "RO" && n >= 2 && n <= 10 && isNumeric(num)) {
		// RO - 1 block of minimum 2 digits and maximum 10 digits
		okay = true;
	} else if (cc == "SE" && n == 12 && isNumeric(num)) {
		// SE - 12 digits
		okay = true;
	} else if (cc == "SI" && n == 8 && isNumeric(num)) {
		// SI - 8 digits
		okay = true;
	} else if (cc == "SK" && n == 10 && isNumeric(num)) {
		// SK - 10 digits
		okay = true;
	}

	return(okay);
}


// getRegion:
// DRE 22-2-2010
// find the customer's region (UK/EU/WORLD) from the country cookie value
// return empty string if not set
function getRegion()
{
	var country = getCookie('country');
	var region = "";

	if (country != null) {
		if (country == "UK" || country == "GB") {
			region = "uk";
		} else if (country == "WORLD") {
			region = "world";
		} else if (country != "")
			region = "eu";
	}

	return(region);
}


// showLocation:
// DRE 22-2-2010
// Find the customer's country and VAT number from the cookie, if any,
// and show on the form.
// If this is the location window (opened from JavaScript when add to cart clicked)
// fill in the shopping paragraph with dynamic text.
function showLocation()
{
	var country = getCookie('country');
	var vat_number = getCookie('vat_number');
	var region = document.location.region;

	if (region != null && country != null) {
		var region_value = getRegion();

		// show the selected region
		for (var i = 0; i < region.length; i++) {
			if (region[i].value == region_value) {
				region[i].checked = true;
			} else {
				region[i].checked = false;
			}
		}

		var cc = document.location.country_code;
		if (vat_number != null && cc != null) {
			// show the country, if set
			for (var i = 0; i < cc.length; i++) {
				if (cc[i].value == country) {
					cc[i].selected = true;
				} else {
					cc[i].selected = false;
				}
			}

			// show the VAT number, if set
			var n = vat_number.length;
			if (n > 0) {
				document.location.vat_number.value = vat_number.substring(2,n);
			} else {
				document.location.vat_number.value = "";
			}
		}

		// enable/disable the country and VAT number fields appropriately
		changeRegion(region_value);
	}

	if (window.name == "location") {
		var para = document.getElementById('shopping');
		if (para != null) {
			para.innerHTML =
				"<em>You must set a location before you can add items to your shopping cart. When you click on &ldquo;Set Location&rdquo; you will return to the product page. Please click on the &ldquo;Add to Cart&rdquo; button again to continue with your purchase.</em>";
		}
	}
}


// changeRegion:
// DRE 19-2-2010
// Enable or disable the EU country code and VAT number fields
// depending on whether the region selected is EU or other
function changeRegion(region)
{
	if (region != null) {
		if (region == "eu") {
			document.location.country_code.disabled = false;
			document.location.vat_number.disabled = false;
		} else {
			document.location.country_code.disabled = true;
			document.location.vat_number.disabled = true;
		}
	}
}


// getFlagCountry:
// DRE 16-3-2010
// Return the full name of a country or region from the flag name
// (either a 2-letter abbreviation, or a region "eu" or "world")
function getFlagCountry(flagname)
{
	var flagMap = [
				   "uk", "United Kingdom",
				   "eu", "European Union",
				   "world", "World",
				   "at", "Austria",
				   "be", "Belgium",
				   "bg", "Bulgaria",
				   "cy", "Cyprus",
				   "cz", "Czech Republic",
				   "dk", "Denmark",
				   "ee", "Estonia",
				   "fi", "Finland",
				   "fr", "France",
				   "de", "Germany",
				   "el", "Greece",
				   "hu", "Hungary",
				   "ie", "Ireland",
				   "it", "Italy",
				   "lv", "Latvia",
				   "lt", "Lithuania",
				   "lu", "Luxembourg",
				   "mt", "Malta",
				   "nl", "Netherlands",
				   "pl", "Poland",
				   "pt", "Portugal",
				   "ro", "Romania",
				   "sk", "Slovak Republic",
				   "si", "Slovenia",
				   "es", "Spain",
				   "se", "Sweden"
				   ];
	var i, n = flagMap.length;
	var fullname = flagname;

	for (i = 0; i < n; i += 2) {
		if (flagMap[i] == flagname) {
			fullname = flagMap[i+1];
			break;
		}
	}

	return(fullname);
}


// showRegion:
// DRE 25-2-2010
// show the region in the element called "region" on the page
// the region is shown as a country or regional flag and/or a link to
// set/change the location
function showRegion()
{
	var para = document.getElementById('region');

	if (para != null) {
		var region = getRegion();
		var country = getCookie('country');
		var flag = "world";

		if (region == "eu" && country != null && country != "") {
			// use country instead of region here as we have all EU flags
			flag = country.toLowerCase();
		} else if (region != "")
			flag = region;
		var flagname = flag;
		flag = "/images/" + flag + ".png";

		var html = '<small>';
/*		if (flagname != "world") {*/
			html += '<img src="' + flag + '" align="middle" alt="';
			html += flagname + '" title="' + getFlagCountry(flagname);
			html += '"> ';
/*		}*/
		html += '<a href=\"http://www.merlin-os.co.uk/products/location.html\">';
		if (region == "") {
			html += 'Set';
		} else {
			html += 'Change';
		}
		html += ' Location</a></small>';

		para.innerHTML = html;
	}
}


// showLinkedIn:
// DRE 30-06-2011
// show the LinkedIn recommendations by writing HTML directly into the current paragraph
// (which is the element called "linkedin_rec" on the page)
// This uses the LinkedIn social plug-in to display the appropriate content and buttons
function showLinkedIn()
{
	var html = '<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>';
	var productid = 0;
	var url = window.location.toString();
  
	if (url.match("datestamp")) {
		productid = 325144;
	} else if (url.match("nameit")) {
		productid = 325193;
	} else if (url.match("options")) {
		productid = 325198;
	}
  
	if (productid != 0) {
		html += '<script type=IN/RecommendProduct data-product="' + productid
			+ '" data-company="1458674" data-counter="right"></script>';
		//para.innerHTML = html;
		document.write(html);
	}
}


// showFB:
// DRE 30-11-2010
// show the Facebook recommendations or likes in the element called "fb_rec"
// or "fb_like" on the page
// This uses the Facebook social plug-in to display the appropriate content and buttons
function showFB()
{
	var para = document.getElementById('fb_rec');
	var recommend = true;

	if (para == null) {
		para = document.getElementById('fb_like');
		recommend = false;
	}

	if (para != null) {
		var html = '<p><iframe src="http://www.facebook.com/plugins/like.php?href=';
		html = html + encodeURI(window.location);
		html= html + '&amp;layout=standard&amp;show_faces=true&amp;width=100%&amp;action=';
		if (recommend == true)
			html = html + 'recommend';
		else
			html = html + 'like';
		html = html + '&amp;font=arial&amp;colorscheme=light&amp;height=100" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100%; height:100px;" allowTransparency="true"></iframe></p>';

		para.innerHTML = html;
	}
}


// showDeliveryDateTxt:
// DRE 13-1-2011
// show the expected delivery date in the element called "delivery_date" on the page
// retrieves the holidays.csv file from the web site to check holiday dates too
function showDeliveryDateTxt(holidays)
{
	var para = document.getElementById('delivery_date');

	if (para != null) {
		if (holidays != null) {
			// got returned holiday dates to parse
			var today = new Date();
			var deliveryDate = new Date();
			var one_day = 1000 * 60 * 60 * 24;

			// set initial delivery date to tomorrow
			deliveryDate.setTime(deliveryDate.getTime() + one_day);

			// move date forward a day at a time to skip weekends and holidays
			var workingDay = false;

			// get holiday CSV data into a single line text string and then split into an array
			holidays = holidays.replace(/\r\n/g, ",");
			holidays = holidays.replace(/\r/g, ",");
			holidays = holidays.replace(/\n/g, ",");
			var bankHolidays = holidays.split(",");

			while (workingDay == false) {
				workingDay = true;

				// what is the day? (Sunday = 0, .., Saturday = 6)
				var day = deliveryDate.getDay();
				if (day == 0 || day == 6) {
					workingDay = false;
				} else {
					// check bank holidays
					// holidays.csv file has lines in format: year,month,day,holiday name
					// so read four fields at a time
					var n = Math.floor(bankHolidays.length / 4) * 4;
					var i;
					for (i = 0; i < n; i += 4) {
						if ((deliveryDate.getFullYear() == bankHolidays[i])
								&& ((deliveryDate.getMonth() + 1) == bankHolidays[i+1])
								&& (deliveryDate.getDate() == bankHolidays[i+2])) {
							workingDay = false;
						}
					}
				}

				if (workingDay == false) {
					// add a day if this day is a weekend or holiday
					deliveryDate.setTime(deliveryDate.getTime() + one_day);
				}
			}

			// create paragraph text for delivery date estimate
			para.innerHTML = 'We estimate that you will receive delivery of your order on:<br/>'
				+ deliveryDate.toLocaleDateString();
		} else {
			// load holiday dates
			loadXMLDoc("holidays.csv",
					   function() {
						   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
							   // pass the holiday data to our function to update
							   // the dynamic page element
							   showDeliveryDateTxt(xmlhttp.responseText);
						   }
						}
				);
		}
	}
}


// showDeliveryDate:
// DRE 14-1-2011
// show the expected delivery date in the element called "delivery_date" on the page
// retrieves the holidays.xml file from the web site to check holiday dates too
function showDeliveryDate(holidays)
{
	var para = document.getElementById('delivery_date');

	if (para != null) {
		if (holidays != null) {
			// got returned holiday dates to parse
			var today = new Date();
			var deliveryDate = new Date();
			var one_day = 1000 * 60 * 60 * 24;

			// set initial delivery date to tomorrow
			deliveryDate.setTime(deliveryDate.getTime() + one_day);

			// move date forward a day at a time to skip weekends and holidays
			var workingDay = false;

			// holidays is an XML DOM object
			// get the <holiday> elements from that as bankHolidays
			var bankHolidays = holidays.getElementsByTagName("holiday");

			while (workingDay == false) {
				workingDay = true;

				// what is the day? (Sunday = 0, .., Saturday = 6)
				var day = deliveryDate.getDay();
				if (day == 0 || day == 6) {
					workingDay = false;
				} else {
					// check bank holidays
					// holidays.xml file has holiday elements containing elements:
					// year, month, date, title
					var n = bankHolidays.length;
					for (var i = 0; i < n; i ++) {
						var year = (bankHolidays[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
						var month = (bankHolidays[i].getElementsByTagName("month")[0].childNodes[0].nodeValue);
						var date = (bankHolidays[i].getElementsByTagName("date")[0].childNodes[0].nodeValue);
						if ( ((year == "*") || (deliveryDate.getFullYear() == year))
								&& ((deliveryDate.getMonth() + 1) == month)
								&& (deliveryDate.getDate() == date)) {
							workingDay = false;
						}
					}
				}

				if (workingDay == false) {
					// add a day if this day is a weekend or holiday
					deliveryDate.setTime(deliveryDate.getTime() + one_day);
				}
			}

			// create paragraph text for delivery date estimate
			para.innerHTML = 'We estimate that you will receive delivery of your order on:<br/>'
				+ deliveryDate.toLocaleDateString();
		} else {
			// load holiday dates
			loadXMLDoc("holidays.xml",
					   function() {
						   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
							   // pass the holiday data to our function to update
							   // the dynamic page element
							   showDeliveryDate(xmlhttp.responseXML);
						   }
						}
				);
		}
	}
}


function getMonth(month)
{
	var months = [ "January", "February", "March", "April", "May", "June",
				  "July", "August", "September", "October", "November", "December" ];

	return months[month - 1];
}


// showHolidays:
// DRE 17-1-2011
// show a table of the bank holidays and our own holidays
// retrieves the holidays.xml file from the web site to get the holiday dates
function showHolidays(holidays)
{
	var para = document.getElementById('holidays_table');

	if (para != null) {
		if (holidays != null) {
			// got returned holiday dates to parse
			var today = new Date();
			var this_year = today.getFullYear();
			var html = '<table width="100%" border="0">\n';

			// holidays is an XML DOM object
			// get the <holiday> elements from that as bankHolidays
			var bankHolidays = holidays.getElementsByTagName("holiday");

			// build a list of holidays
			// holidays.xml file has holiday elements containing elements:
			// year, month, date, title
			var n = bankHolidays.length;
			var table = [];
			for (var i = 0; i < n; i ++) {
				var year = (bankHolidays[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
				var month = (bankHolidays[i].getElementsByTagName("month")[0].childNodes[0].nodeValue);
				var date = (bankHolidays[i].getElementsByTagName("date")[0].childNodes[0].nodeValue);
				var title = bankHolidays[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
				if ((year == "*") || (this_year == year)) {
					// add to list
					// build description string
					// prefix the string by month and date in form <MM><DD> to use for sorting
					// this prefix string will be removed on output
					var sort_month;
					if (month < 10)
						sort_month = "0" + month;
					else
						sort_month = month;
					var sort_date;
					if (date < 10)
						sort_date = "0" + date;
					else
						sort_date = date;
					var s = sort_month + sort_date
						+ date + " " + getMonth(month) + " " + this_year + "</td><td>" + title;

					// insert string into array in correct place
					table.push(s);
				}
			}

			// sort the strings (by date)
			table.sort();

			// create the table data html
			// remember to omit the sort key (first four characters) from the string
			for (var i = 0; i < table.length; i++) {
				html += "<tr><td>" + table[i].substr(4) + "</td></tr>\n";
			}

			html += "</table>\n";

			// set paragraph text for table
			para.innerHTML = html;
		} else {
			// load holiday dates
			loadXMLDoc("holidays.xml",
					   function() {
						   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
							   // pass the holiday data to our function to update
							   // the dynamic page element
							   showHolidays(xmlhttp.responseXML);
						   }
						}
				);
		}
	}
}


// loadXMLDoc:
// DRE 14-1-2011
// generic function using AJAX to get document data asynchronously
// the passed in function will be called when readyState changes
// and can then process the returned data when ready
function loadXMLDoc(url, func)
{
	// create an XMLHttpRequest to send back to our web server
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {
		// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	// set up a callback function (passed in) for when the asynchronous data has been received
	// onreadystatechange -- called automatically *each time* the readyState property changes 
	// readyState holds the status of the XMLHttpRequest. Changes from 0 to 4: 
	// 0: request not initialized 
	// 1: server connection established
	// 2: request received 
	// 3: processing request 
	// 4: request finished and response is ready 
	// HTTP status returned -- 200: "OK", 404: Page not found 
	xmlhttp.onreadystatechange = func;

	// get the document data asynchronously
	xmlhttp.open("GET", url, true);
	xmlhttp.send();
}


function loadXMLString(txt) {
	if (window.DOMParser) {
		parser = new DOMParser();
		xmlDoc = parser.parseFromString(txt, "text/xml");
	} else {
		// Internet Explorer
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.loadXML(txt); 
	}

	return xmlDoc;
}


// showDynamic:
// DRE 30-11-2010
// called from the onload element in the body element of a page
// to populate any dynamic elements
function showDynamic()
{
	// show the customer's location
	showRegion();
	// show Facebook recommendations or likes
	showFB();
	// show delivery date on order acknowledgement pages
	showDeliveryDate(null);
	// show holidays on order info page
	showHolidays(null);
}

