//************Configurtion starts here********************//

//*********************** Settings ***********************//

// Replace the error message here with one of your chosing.

var message = 'The following fields, marked with an \' R \' have either been left blank or have been filled out incorrectly'

// Replace the error sign here with one of your chosing.

var warningSign = 'R'

//*********************************************************//
// Field validation
///version 1
// created by Micahel hickland
// on 08/03/2006 (UK date format)
//
// This is a control function, which allow form fileds to be tested
// by using outside functions (found in the function bin further
// down this page) to test each form field.
//
// requires the field id and value to be passed as the parameter
// and return a boolean value of '0' or '1' as output
//**********************************************************//
function testFields(id, value)
{
var result;

switch(id)
{
case "firstname": result = nonEmptyFieldTest(value);
break;

case "lastname": result = nonEmptyFieldTest(value);
break;

case "From":  result = validEmail(value);
		break; 

case "cat": result = nonEmptyFieldTest(value);
break;

case "details": result = nonEmptyFieldTest(value);
break;
	
default: result = 1;
break;
}		 
return result;
}

//************Configurtion ends here********************//

//**************************************** Main script starts here ***************************//

//** create and initcialises a control variable, which indicates whether the script has been run this session **//
//** DO NOT CHANGE THIS VALUE ****//
var controlKey = 0;

//** This function requires two parameters and is called using the onsubmit event handler.***///
//** The first is an Int and represents the numbering of the form you want to process **//
//** which is a number that start at zero, for the first form that appears on a page, incrementing by one for each from element **//
//** so if your form is the second on the page, then it will be represented by the number one.
//**
//** the second parameter is the key word this, which pass all form elements into this function in the form of an array **//
function carjen_validateForm(para)//version 001
{

// Test is browser has the functionality to process this script **//
if (!document.getElementsByTagName || !document.getElementById || !document.createElement || !document.createTextNode)
{
		return;
}



//*** create & initcialises counter variables ***//
var i = 0, c = 0;
var objFormId, formLength;

var arrFormElementsValue = new Array;
var arrFormElementsId = new Array;
var arrValidFields = new Array;
var arrInValidFields = new Array;

//**** this get the form id*****//
objFormId = para.id;
formLength = document.forms[objFormId].length

//** this for loop get the id and value of all form elements.  The '.length -2' is to stop the submit button ****///
//**** from being processed and the negative value should be increased if a 'reset' or clear button are also used *//
for (var c = 0; c < formLength - 2; c++)
  {
  arrFormElementsValue[c] = document.getElementById(objFormId).elements[c].value;
	arrFormElementsId[c] = document.getElementById(objFormId).elements[c].id;

//****** this conditional test to see if the var controlKey is equal to '1' ****************//
//***** if it is equal to '1' this means that the script has been run already this session *//
//***** which means that the textNode '*' has already been applied and must be remove to stop duplication *//	
  if(controlKey == 1)
	 {
	 deleteItem(arrFormElementsId)
	 }	
	}
//*** this part of the function add the text node '*' to all fields signaling that they are invalid ***///
//*** later in the function the text node '*' will be removed from valid fiels ************************///
for (var c = 0; c < formLength - 2; c++)
  {
	warningElement(arrFormElementsId[c])
	
//******** call validation function here ********////
//**** external functions can be used here to validate each field based on their id ******//
//**** and be added to the arrValidFields array ******************************************//

if ((testFields(arrFormElementsId[c], arrFormElementsValue[c])))
 {
 arrValidFields[i] = arrFormElementsId[c]
 i++;
 }	
}
deleteItem(arrValidFields)

//******* this test to see if the number of valid fields equals the total amount of fields ****//
//******* if they are both equal then the function returns true and the form is submitted  ****//
//******* else the function returns false and the submit is cancelled  ************************//
if (arrValidFields.length == arrFormElementsId.length)
 {
 return true;
 }
 else 
	{
	 if(controlKey == 0)
	 {		 	 
	 warningMessage(objFormId, arrFormElementsId[0])	
	 }
	 
// This function set the focus() and select() to the first field which is in error **//	 
	 //rest i
	 i=0;
	 for (var c = 0; c < formLength - 2; c++)
  {
	
if (!(testFields(arrFormElementsId[c], arrFormElementsValue[c])))
 {
 arrInValidFields[i] = arrFormElementsId[c]
 i++;
 }	
}
	 document.getElementById(arrInValidFields[0]).focus();
//** This conditional ensures that the selct is not applied to the select element
	 var eTag = document.getElementById(arrInValidFields[0]).tagName;
	 if(!(eTag =='SELECT'))
	 {
	 document.getElementById(arrInValidFields[0]).select();
	 }
	controlKey = 1;	
 return false;
		}	
	
}
//***************** main script ends here ********************************//

//****** function bin ***********//

//*********************************************************//
// Null field test
///version 1
// created by Micahel hickland
// on 08/03/2006 (UK date format)
// Tests that a from field in not empty
// requires the fields value to be passed as the parameter
//**********************************************************//
 function nonEmptyFieldTest(para)
{
 if (para.length > 0 || para.length == !null)
 {
 return 1;
 }
 else
 {
 return 0;
 }
}

//*********************************************************//
// Email validator
// version 3
// Created by Michael Hickland
// on 07/08/2006 (UK date format)
// Test for correct email format
// requires the fields value to be passed as the parameter
//**********************************************************//
function validEmail(passForm)
{
var regTest;
//regex Developed by Keith Evett derived from Erik Voldengen http://www.thenetprofits.co.uk/coldfusion/faq 
regTest = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name))$/;
   //the conditional test if the email format is valid and returns a boolean value	
	if (!(passForm.match(regTest)))
	{
	return 0;
	}
	else
	{
	return 1;
	}      
}; 


//*********************************************************//
// Find first label
// version 1
// Created by Michael Hickland
// on 06/08/2006 (UK date format)
// Returns the position of the first label node in a form
// requires the id of the form to be testd to be passed as the parameter
//**********************************************************//

function getFirstLabel(para)
{
var label;

label = document.getElementById(para).getElementsByTagName('label')[0];
return label;
}

//*********************************************************//
// Delete span tag
// version 1
// Created by Michael Hickland
// on 06/08/2006 (UK date format)
// Deletes a span element directly after a parent element
// requires the id of the parent element to be passed as the parameter
//**********************************************************//
function deleteItem(para)
{

var target, delItem, delLastItem, deledItem;

if (para.length > 0)
	{
	for (var c = 0; c < para.length ; c++)
	 {
	 target =  document.getElementById(para[c]).parentNode;
	 delItem = target.getElementsByTagName('span');
	 if(delItem.length)
	 {
	 delLastItem = delItem.item(delItem.length - 1)
	 deledItem = target.removeChild(delLastItem)
	 }	
	}	
 }
}

//*********************************************************//
// Insert warning message
// version 1
// Created by Michael Hickland
// on 06/08/2006 (UK date format)
// Inserts a warning message into a form before the first label element
// requires the objFrom and first from element id to be passed as the parameter
// N.B The warning can be styled using the class 'warning'
//**********************************************************//

function warningMessage(objFormId, firstElementId)
{
var warning, warningTextItem, warningTarget

	 warning = document.createElement('p')
	 warning.setAttribute('className', 'warning');//this is for ie
	 warning.setAttribute('class', 'warning');	 
	 warningTextItem = document.createTextNode(message);
	 warning.appendChild(warningTextItem);
	 warningTarget = document.getElementById(firstElementId).parentNode;
	 warningTarget.insertBefore(warning, getFirstLabel(objFormId));
}

//*********************************************************//
// Insert warning sign
// version 1
// Created by Michael Hickland
// on 06/08/2006 (UK date format)
// Inserts a warning sign 'R' into a form after a specific from element
// requires the from element id to be passed as the parameter
// N.B The warning can be styled using the class 'warning'
//**********************************************************//

function warningElement(FormElementsId)
{
	var textItem, target, objSpan;
		
	objSpan = document.createElement('span');
	objSpan.setAttribute('className', 'warning');//this is for ie
	objSpan.setAttribute('class','warning');
	textItem = document.createTextNode(warningSign);
	objSpan.appendChild(textItem);
	target = document.getElementById(FormElementsId).parentNode;
	target.appendChild(objSpan);
}
