// 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);
}


// 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
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")
	{
		document.download.acrobat[1] = new Option("9.*", 9);
		document.download.acrobat[1] = new Option("8.*", 8);
		document.download.acrobat[2] = new Option("7.*", 7);
		document.download.acrobat[3] = new Option("6.*", 6);
		document.download.acrobat[4] = new Option("5.*", 5);
		document.download.acrobat[5] = new Option("4.*", 4);
		document.download.acrobat[6] = new Option("3.*", 3);
		document.download.acrobat.selectedIndex = 0;
	}
	else
	{
		n = 1;
		document.download.acrobat[n++] = new Option("9.*", 9);
		if (prod[select].text != "Date Stamp")
		{
			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
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);
					}
					rate.value = "17.5";
				}
			} // 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);
}


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;
	}
}
