//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//															//
// File:	GSFfunctions.js												//
// Author:	Adrian Lumsden, Blakedale Trading Ltd.									//
// Copyright	© 2008, Blakedale Trading Ltd.										//
//		All Rights Reserved											//
// Version:	v01.00.00												//
// Date:	29-Sep-2008												//
// Purpose:	Define common and useful functions for the GSFilters							//
//		website. Some of these routines were filtched from the							//
//		Blakedale website.											//
//															//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


/** **********************************************************************************************************************
 * Check the E-mail form before sending it off.
 *
 * They don't have to supply an e-mail address but if they do then
 * it has to look valid (we can't check it actually works!).
 *
 * They should leave a message else what's the point?
 *
 * They should never be able to submit a completely empty form.
 */
function checkContactForm(form) { //////////////////////////////////////////////////////////////////////////////////////// checkContactForm()
															//
    if (form.eMail.value.length > 0) {											// If have an e-mail
	emailStr = form.eMail.value;											// Get the string
	if (false == emailCheck(emailStr)) {										// And if it doesn't check out
	    return false;												// Don't submit
	    }														//
	}														//
    else if (form.sender.value != "contact-us") {									// For non-Contact Us forms
	alert('Please supply an e-mail address.');									// Have to have an e-mail address
	return false;													// Don't submit
	}														//
															//
    var txt = ""; 													// Debug text
    var len = 0;													// Lenght of text/textarea contents
    for (var i = 0; i < form.elements.length; i++) {									// For each element on the form
	if (form.elements[i].type.indexOf("text") >= 0) {								// If text / textarea field
	    len += form.elements[i].value.length;									// Add in its length
	    }														//
	txt += form.elements[i].type + ": " +										// Debug
	       form.elements[i].name + " = " + form.elements[i].value + ", " +						//
	       form.elements[i].value.length + "\n";									//
	}														//
    //alert(txt + "\n\nLength = " + len);										// Debug
    if (len <= 0) {													// If nothing there?
	alert('Please complete at least one field!');									// Complain to visit
	return false;													// Don't submit
	}														//
															//
    // Special handling for Contact Us form.										//
    if (form.sender.value == "contact-us") {										// If handling Contact Us form
	if (form.msgBody.value.length <= 0) {										// If no useful message
	    var msg = 'Please leave at least a message.';								// Default
	    if (form.name.value.length <= 0) {										// If no name param
		msg = 'You can be anonymous if you like\nbut please leave a message at least.';				// Make up the moan
		}													//
	    alert(msg);													// Moan
	    form.msgBody.focus();											// (Re)-focus back to the msg
	    form.msgBody.select();											// Select it all (there's none!)
	    return false;												// Return NAK
	    }														//
	}														//
															//
    return true;													// Flag OK
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of checkContactForm()


/** **********************************************************************************************************************
 * Check to see if cookies are enabled or not. Set a global to indicate teh outcome.
 */
var cookiesEnabled = 'undetermined';
function checkIfCookiesEnabled() { /////////////////////////////////////////////////////////////////////////////////////// checkIfCookiesEnabled()
    															//
    document.cookie = "GSFcookieTest=Are cookies enabled?";								// Create a session cookie?
    if(document.cookie.indexOf("GSFcookieTest") == -1) {								// If not there then disabled
	cookiesEnabled = false;												// Flag it so
	}														//
    else {														// Else it created
	cookiesEnabled = true;												// Flag enabled
	var expiryDate = new Date();											// Now delete it
	expiryDate.setTime(expiryDate.getTime() - (24 * 60 * 60 * 1000));						// Expires 24 hours ago
	document.cookie = "GSFcookieTest=Deleting; expires=" + expiryDate.toGMTString();				// Expire it (delete it)
	}														//
															//
//  alert('cookiesEnabled: ' + cookiesEnabled);										// Debug
    return cookiesEnabled;												// Return the outcome
    															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of checkIfCookiesEnabled()


/** **********************************************************************************************************************
 * Check the supplied parameter is a valid e-mail address.
 *
 * From: http://javascript.internet.com/forms/email-address-validation.html
 * but has been extensively edited to remove all comments to make it smaller
 * to speed up download.
 *
 */
function emailCheck(emailStr) { ////////////////////////////////////////////////////////////////////////////////////////// emailCheck()
															//
    if (emailStr == 'e-mail address') {											// If it's a prompt
    	alert('Please enter a valid e-mail address.');									//
    	return false;													// Oops
	}														//
															//
//    alert("emailCheck(" + emailStr + ")");										//
															//
    var invalidMsg = "Invalid e-mail address.Please re-enter.\n\n";							//
    var checkTLD = 1;													// Check for valid TLD. 1=yes, 0=no.
    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;				//
    var emailPat = /^(.+)@(.+)$/;											//
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";									// Dissallowed special characters
    var validChars = "\[^\\s" + specialChars + "\]";									// Valid characters
    var quotedUser = "(\"[^\"]*\")";											//
    var ipPat = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;								// IP address pattern
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;						// IP domain for e-mail target
    var atom = validChars + '+';											//
    var word = "(" + atom + "|" + quotedUser + ")";									//
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");							//
    var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");							//
															//
    var matchArray = emailStr.match(emailPat);										//
    if (matchArray == null) {												//
	alert(invalidMsg + '"' + emailStr + '"');									//
	return false;													//
	}														//
															//
    var user = matchArray[1];												// Get user part
    for (i = 0; i < user.length; i++) {											// Check user name
	if (user.charCodeAt(i) > 127) {											//
	    alert(invalidMsg + "Invalid characters in user name: " +							//
		'"' + user + '"');											//
	    return false;												//
	   }														//
	}														//
    if (user.match(userPat) == null) {											//
	    alert(invalidMsg + "Bad user name part: " +									//
		'"' + user + '"');											//
	return false;													//
	}														//
															//
    var domain = matchArray[2];												// Get domain part
//  alert('domain: ' + domain);												// Debug
    for (i = 0; i<domain.length; i++) {											// Check domain name
	if (domain.charCodeAt(i) > 127) {										//
	    alert(invalidMsg + "Invalid characters in domain name: " +							//
		'"' + domain + '"');											//
	    return false;												//
	   }														//
	}														//
															//
    // Adrian: Check for domain being a straight IP address (no [])							//
    var IPArray = domain.match(ipPat);											//
    if (IPArray != null) {												// If it matched plain IP
	alert(invalidMsg + 'It looks like you are trying to use an IP\n' +						// Then whinge
	    'address for the target domain.\nDid you mean: ' +								//
	    '[' + domain + ']?');											//
	form.eMail.value = user + '@[' + domain + ']';									// Fix it for them
	return false;													//
	}														//
															//
    IPArray = domain.match(ipDomainPat);										// Check for IP style domain
    if (IPArray != null) {												// If have an IP address
	for (var i = 1; i <= 4; i++) {											//
	    if (IPArray[i] > 255) {											//
		alert(invalidMsg + "Destination domain is an " +							//
		    'invalid IP address: "' + domain + '"' +								//
		    ' (' + IPArray[i] + ')');										//
		return false;												//
		}													//
	    }														//
	return true;													//
	}														//
															//
    var atomPat = new RegExp("^" + atom + "$");										// Have domain name
    var domArr = domain.split(".");											//
    var len = domArr.length;												//
    for (i = 0; i < len; i++) {												//
	if (domArr[i].search(atomPat) == -1) {										//
	    alert(invalidMsg + "Invalid domain name: " +								//
		'"' + domain + ' (' + domArr[i] + ')"');								//
	    return false;												//
	    }														//
	}														//
															//
    // Check against known TLDs												//
    if (checkTLD &&													// If doesn't check out
	    domArr[domArr.length-1].length != 2 &&									//
	    domArr[domArr.length-1].search(knownDomsPat) == -1) {							//
	alert(invalidMsg + "Unknown Top Level Domain: " +								//
		'"' + domArr[domArr.length-1] + '"');									//
	return false;													//
	}														//
															//
    if (len < 2) {													// Valid hostname preceding the domain?
	alert(invalidMsg + "Invalid hostname: " + '"' + domain + '"');							//
	return false;													//
	}														//
															//
    return true;													// Passed all the tests
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// end of emailCheck()


/** **********************************************************************************************************************
 * Do whatever client processing we want to happen at the end of each page.
 * At the moment this contains code that is useful for debugging. It doesn't
 * do anything critical.
 */
function doEndOfPage() { ///////////////////////////////////////////////////////////////////////////////////////////////// doEndOfPage()
															//
    /*********************************************************************************************************************
    document.write("<br />Navigator.userAgent=" + navigator.userAgent);							//
    document.write(",&nbsp;Navigator.platform=" + navigator.platform);							//
    if (document.getElementById || document.all || document.layers) {							//
	document.write("<br />Handles DHTML via");									//
	if (document.getElementById) document.write(" getElementById");							//
	if (document.all) document.write(" document.all");								//
	if (document.layers) document.write(" document.layers");							//
	}														//
															//
    if (document.getElementById && document.createElement) {								//
	document.write("<br />Fully Supports the W3C DOM.");								//
	}														//
    *********************************************************************************************************************/
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of doEndOfPage()


/** **********************************************************************************************************************
 * Append a query parameter to the Shop URL that indicates to the Shop code (Jacco) whether cookies
 * are turned on or not. This is a client-time indication. It depends on the cookie check having been
 * made earlier in the page execution.
 */
function doShopLinkClick(href) { ///////////////////////////////////////////////////////////////////////////////////////// doShopLinkClick()
															//
    if (typeof(window['cookiesEnabled']) != "undefined" ) {								// If cookie state known
	if (cookiesEnabled) {												//
	    href += '&cookiesEnabled=yes';										//
	    }														//
	else {														//
	    href += '&cookiesEnabled=no';										//
	    }														//
	}														//
    else {														//
	href += '&cookiesEnabled=undetermined';										//
	}														//
    															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of doShopLinkClick()


/** **********************************************************************************************************************
 * DHTML mini-API functions to return an object irrespective of browser DOM
 *
 * See:	http://www.quirksmode.org/js/dhtmloptions.html (2009-09-09: now broken)
 */
function getObj(name) { ////////////////////////////////////////////////////////////////////////////////////////////////// getObj()
															//
    if (document.getElementById) {											// If supports getElementById()
  	this.obj = document.getElementById(name);									// Use it
	if (this.obj) this.style = document.getElementById(name).style;							// If got one gets its style too
	}														//
    else if (document.all) {												// Else if supports document.all array
	this.obj = document.all[name];											//
	if (this.obj) this.style = document.all[name].style;								// If got one gets its style too
	}														//
    else if (document.layers) {												// Else if Netscape 4 (oh hell)
	this.obj = getObjNN4(document, name);										//
	this.style = this.obj;												//
	}														//
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of getObj()


/** **********************************************************************************************************************
 * Print out a message that tells us the state of cookies being set or not (or can't determine).
 */
function printCookiesEnabled() { ///////////////////////////////////////////////////////////////////////////////////////// printCookiesEabled()
															//
    document.write('<p>');												//
    if (typeof(window['cookiesEnabled']) != 'undefined' ) {					   			//
	if (cookiesEnabled) {									 			//
	    document.write('Session cookies are enabled.');					   			//
	    }											 			//
	else {														//
	    document.write('Session cookies are disabled.');					  			//
	    }											 			//
	}											     			//
    else {											    			//
	document.write('Cookie enabled/disabled state is unknown.');				  			//
	}											     			//
    document.write('<\p>\n');									 			//
    															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of printCookiesEnabled()


/** **********************************************************************************************************************
 * Function to locate all the child <input> elements and to set their default values to the supplied parameter.
 */
function resetInputs(container, val) { /////////////////////////////////////////////////////////////////////////////////// clearInputs()
															//
    var parent = document.getElementById(container);									// Find the container element
    var allInputs = parent.getElementsByTagName('input');								// Get child <input> elements
    var input;
    for (var i = 0; i < allInputs.length; i++) {									// For each <input>
    	input = allInputs[i];												// Get the input
    	input.defaultValue = val;											// Zap it
	}														//
    input = allInputs[0];												// Get the first input
    input.focus();													// Go back to the first field
    input.select();													// Select its contents
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of clearInputs()


/** **********************************************************************************************************************
 * Function that handles the onFocus event for a field object. The purpose
 * is to select the entire contents when the object receives focus (like
 * what Windows does).
 */
function selectContents(fieldObject) { /////////////////////////////////////////////////////////////////////////////////// selectContents()
															//
    fieldObject.select();												// Do it!
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of selectContents()


/** **********************************************************************************************************************
 * Show the next slide in the Welcome page slide show.
 */
function showSlide() { /////////////////////////////////////////////////////////////////////////////////////////////////// showSlide()
    															//
    slides[slideNum].style.display = 'none';										// Turn current one off
    slideNum = ++slideNum % slides.length;										// Compute next index
    slides[slideNum].style.display = 'block';										// Turn it on
    var delay = Math.max(turnOverRate, (turnOverRate * (slides[slideNum].innerHTML.length / 50.0)));			// Minimum is turnOverRate
    delay = Math.max(turnOverRate * 3, delay);										// Max is thrice the min
    window.setTimeout('showSlide();', delay);										// Do it again in a while
    															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of showSlide()


/** **********************************************************************************************************************
 * Get the <h2> elements in the <div id="welcomeSlideShowSlides"> and build an array of them. Each one is a slide
 * for the slide show. Start the slide show going over the array.
 */
var slideNum = 0;													// Current slide showing
var slides = new Array();												// Array of slide <h2>s

function startSlideShow() { ////////////////////////////////////////////////////////////////////////////////////////////// startSlideShow()
    															//
    var slidesDiv = document.getElementById("welcomeSlideShowSlides");							// Find the slide <div>
    if (slidesDiv.childNodes.length > 0) {										// If have some
	var childNodes = slidesDiv.childNodes;										// Point to them
	for (var node in childNodes) {											// For each one
	    if ((typeof(childNodes[node].nodeName) != "undefined") && (childNodes[node].nodeName == 'H2')) {		// If it's an <h2>
		    childNodes[node].style.display = 'none';								// Turn it off
		    slides.push(childNodes[node]);									// Add to array
		    }													//
	    }														//
	slides[0].style.display = 'block';										// Turn on the 1st one
	window.setTimeout('showSlide();', turnOverRate * 1.5);								// Start with longish first delay
	}														//
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of startSlideShow()


/** **********************************************************************************************************************
 * Function to change the amount of text in a div for testing liquid layout.
 */
function toggleContent(name, n) { ////////////////////////////////////////////////////////////////////////////////////////
															//
    var i, t = '', el = document.getElementById(name);									//
    if ( ! el.origCont) {												//
	el.origCont = el.innerHTML;											//
	}														//
	for (i = 0; i < n; i++) {											//
	    t += el.origCont;												//
	    }														//
    el.innerHTML = t;													//
															//
    } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


/** **********************************************************************************************************************
 * Function that handles the submission of the contact details form. Check it for validity.
 * The check is that all inputs that have a name starting with an "_" must have content.
 */
function validateContactForm(contactFormTable) { ///////////////////////////////////////////////////////////////////////// validateContactForm()
															//
    var table = document.getElementById(contactFormTable);								// Find the table element
    var allInputs = table.getElementsByTagName('input');								// Get child <input> elements
    for (var i = 0; i < allInputs.length; i++) {									//
    	var inputItem = allInputs[i];											// Get next  one
    	if ('_' == inputItem.name.charAt(0) && (inputItem.value.length <= 0)) {						// If checked and if no input
	    alert('Please complete all required contact details fields.');						//
	    return false;												//
	    }														//
	}														//
    var email = document.getElementById('_email');									// Find the _email input
    return emailCheck(email.value);											// Check it out
    															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of validateContactForm()


/** **********************************************************************************************************************
 * Function to validate the item order quantity for the order form and update the line item total.
 * This is triggered by the blur event of one of the <input> elements in the form.
 */
function validateItemQuant(quantItem) { ////////////////////////////////////////////////////////////////////////////////// validateItemQuant()
															//
    var retVal = true;													// Assume OK
    if (isNaN(quantItem.value) || isNaN(parseInt(quantItem.value))) {							// If not a number
	alert('"' + quantItem.value + '" is not a valid order quantity.\nPlease use a numeric value!\n');		// Whinge										//
	quantItem.value = 0;												// Force it to zero
	quantItem.focus();												// Focus back to it
	quantItem.select();												// And select the contents
	retVal = false;													// Set duff
	}														//
    quantItem.value = parseInt(quantItem.value);									//
    var id = (quantItem.id.split('_'))[0];										// Extract name part of ID
    var price = document.getElementById(id + '_Price').innerHTML;							//
    price = price.match(/[0-9.]+/);											// Leave only floating point number
    var total = price * quantItem.value;										// Line item total
    document.getElementById(id + '_Total').innerHTML = '&euro;' + total.toFixed(2);					// Update total
    return retVal;													// Done
															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of selectContents()


/** **********************************************************************************************************************
 * Function that handles the submission of the order form. Check it for validity.
 * The check is that there are some items being ordered and all quantities are valid.
 */
function validateOrderForm(orderFormTable) { ///////////////////////////////////////////////////////////////////////////// validateOrderForm()
															//
    var quantItem;													// The item quantity
    var quantTotal = 0;													// Total order quantity
    var table = document.getElementById(orderFormTable);								// Find the table element
    var allInputs = table.getElementsByTagName('input');								// Get child <input> elements
    for (var i = 0; i < allInputs.length; i++) {									//
    	quantItem = allInputs[i];											// Get next *_Quant one
    	if (validateItemQuant(quantItem)) {										// If validates
	    quantTotal += quantItem.value;										// Get the order quantity
	    }														//
	else {														//
	    return false;												//
	    }														//
	}														//
															//
    if (quantTotal <= 0) {												// If ordering nothing
	alert('To place an order you must select some items!');								// Complain
	input = allInputs[0];												// Get the first input
	input.focus();													// Go back to the first field
	input.select();													// Select its contents
	return false;													//
	}														//
    return true;													// Else OK
    															//
    } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// End of validateOrderForm()



