// GLOBAL VALIDATION MAGIC BULLET
//Can this validate every form in the universe from the top of the grassy knoll?

/*	Guidelines:
	1. always pass an array to this script with all required form elemnts to validate
	2. if checking emails - use "email" for field name
	3. if comparing emails - use "email" and "emailConfirm" for field names
	4. don't forget to add a title attribute to the form fields for the alert messages
	5. post code fields should always be labled 'postcode' to validate
	6. phone number fields should always be labled 'phone' to validate
	
	This code is in the process of being developed so may be subject to change from time to time - if you have any questions about implementation, please email me - go
	to www.pixelz.co.uk for the address.
	
	You are welcome to use any or all of this code in your own projects if you like it! 
	
	We're getting there slowly but surely...
*/

//uncomment below line to show script loaded...
//alert('BANG!');

//enables addition/removal of elements of the validation array - passinf an array though - use "validationArray = addToArray(new Array(value 1,value 2),validationArray)"
function addToArray(fieldName, fieldArray) {
	for (i=0; i<fieldName.length; i++){fieldArray.push(fieldName[i]);}
	//alert(fieldArray);
	return fieldArray;
}

function takeFromArray(elem, fieldArray) {
 for(i=0; i<fieldArray.length; i++){
	  for(j=0; j<elem.length; j++){	
		if (fieldArray[i]==elem[j]) {fieldArray[i] = null;}
	}	
 }
// alert(fieldArray);
 return fieldArray;
}


//replace ' in text and free text to bypass SQL problem

function replaceQuote(textToCheck) {
	
	var strReplaceAll = textToCheck;
	var intIndexOfMatch = strReplaceAll.indexOf("'");


	while (intIndexOfMatch != -1) {
		// Relace out the current instance.
		strReplaceAll = strReplaceAll.replace("'","&rsquo;");
		 // Get the index of any next matching substring.
		intIndexOfMatch = strReplaceAll.indexOf("'");
	}
	return strReplaceAll;
}

/*function valuePair(original, replacement) {
	this.original = original;
	this.replacement = replacement;
}

function sanitise(textToCheck) {
	var charArry = new Array();
	charArray[charArray.length] = new valuePair('<','&lt;');
	charArray[charArray.length] = new valuePair('>','&gt;');
	charArray[charArray.length] = new valuePair('(','&#40;');
    charArray[charArray.length] = new valuePair(')','&#41;');
	charArray[charArray.length] = new valuePair('#','&#35;');
    charArray[charArray.length] = new valuePair('&','&#38;');
	charArray[charArray.length] = new valuePair('\'','&rsquo;');
	
	for (i=0; i<charArray.length; i++){	
		var inIndexofMatch = strReplaceAll.indexOf(charArray[i].original);
		while (intIndexOfMatch != -1) {
			// Relace out the current instance.
			strReplaceAll = strReplaceAll.replace(charArray[i].original,charArray[i].replacement);
			 // Get the index of any next matching substring.
			intIndexOfMatch = strReplaceAll.indexOf(charArray[i].original);
		}
	}
}*/

function isSelected(elm) {
	//alert('checking selection'+elm);
	if((elm.value == "")||(elm.value == "0")) 
	{	//alert(elm.value);
		return false;}
	else {
		//alert(elm.value);
		return true;}
}



//check postcode for valid postcode
function isValidPostcode(elm) {
	/*re = /^([a-z]|[A-Z]){1,2}\d{1,2}(([a-z]|[A-Z]){1})?\s*(\d{1}([a-z]|[A-Z]){2})*$/
	alert(elm);
	alert(re.test(elm));
	if(re.test(elm)==true){ return true; }
	else { return false; } */
		
	if (elm.value != "") { return false; }
	else { return true; }
}

//check phone for valid phone number
function isValidPhone(elm) {
	re = /^[\d|\s]*$/
	if(re.test(elm)==true){ return true; }
	else { return false; } 
		
	/*if (elm.value != "" && elm.value.indexOf("@") != "-1" && elm.value.indexOf(".") != "-1") { return false; }
	else { return true; }*/
}

//check email for valid email address
function isEmail(elm) {
	re = /^\w+([\.-]?\w+)*([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/
	if(re.test(elm)==true){ return true; }
	else { return false; } 
		
	/*if (elm.value != "" && elm.value.indexOf("@") != "-1" && elm.value.indexOf(".") != "-1") { return false; }
	else { return true; }*/
}

//check input field for empty value
function isEmpty(elm) {
	if (elm.value == "" || elm.value == null || elm.value == "none" || elm.value == "undefined") 
	{  return true; }
	else {	return false; }
}

//Check for radio button values
function isRadioEmpty(formName,radioName) {
		   	var selectedRadio = -1;
		  	for(i=0; i<formName[radioName].length; i++) 
				{  	//alert("i: "+i);
					if (formName[radioName][i].checked) 
					{ selectedRadio = i;
					  //alert("selected radio: "+selectedRadio); 
					 }	
				}
			if (selectedRadio == -1) { return true; }
			else {	return false;	}
		  }

// check for checkbox values
function isCheckboxEmpty(elm)
			{	if (elm.checked) 
				{ 	return false; }
				else { return true; }
			}
			
//external length check fn - use onBlur eevnt to check specific fields
function quickLengthCheck(elm, myLength) {
			if (elm.value.length > myLength) 
				{ 	alert('Your entry is too long. Please restrict to '+myLength+' characters.')
					elm.focus();
					return false;}	
}


function findElement(fieldName, fieldArray) {
	var foundElement = false;
	for (var i=0; i<fieldArray.length; i++) {
	  if(fieldArray[i]!='') {
		  
		if (fieldArray[i] == fieldName) 
		{ 	//alert('found element '+fieldArray[i]+" corresp to "+fieldName)
			foundElement = true;}
		
	  }
	}
	if (foundElement == true)
	{ return true }
	else
	{ return false }
}

function findEmailValue(fieldArray, thisForm) {
	//alert("gonna find email field...")
	var i = 0;	
	while (i<fieldArray.length)
		{	if (fieldArray[i] == "email") 
			{ 	alert('found it at position '+i+' with value '+thisForm.elements[i].value);
				return new String(thisForm.elements[i].value);
				i = fieldArray.length;
				}
			else {	i++;	}
		}
}

//compare email addresses
function emailsDifferent(elm, email) {
	alert('Comparing emails...');
	var emailOne = new String(elm);
	var emailTwo = new String(email);	
	alert('Email 1: '+emailOne);
	alert('Email 2: '+emailTwo);
	if (emailOne == emailTwo) { return false; }
	else {return true; }
}

function confirmEmail(confirmEmailField, emailField) {
	var emailOne = confirmEmailField.value;
	var emailTwo = emailField;
	alert(emailOne+" = "+emailTwo);
	
	if (emailOne != emailTwo) 
	{ alert('Email addresses do not match'); confirmEmailField.focus(); } 
	
	
}

function spamCheck(value) {
				//alert(value);
			 	var valueChecker = /\[URL|\[url|<a|<script|<\/a>|\'\);|\';|\'%|;/;
				var value = value.toString();
				if (value.match(valueChecker)) {
					return true;
				}
			 	return false;
			 }

//main validation fn - passed form name and required fields array
function validateMe(thisForm, fieldArray) {
	
	//spam check all fields - whether required or not
	
	var formFieldsLength = document.forms[0].length;
	/*for (i=0; i<formFieldsLength; i++) {
			
			checkValue = new String(document.forms[0].elements[i].value)
			//alert(checkValue)
			spamCheck(checkValue);
			if (spamCheck(checkValue)==true) {
				alert('I\'m sorry! This form doesn\'t allow urls, links, HTML or SQL reserved syntax like semicolons. Please review  your entry.');
				document.forms[0].elements[i].focus();
				return false;	
			}
				
	}*/
	
	
	var i = 1;
	//iterate through all form fields
	//alert("thisForm.length= "+thisForm.length+" i= "+i+" element name:"+thisForm.elements[i].name);
	while (i<=thisForm.length)
	{	//reassign obj val
		var thisElem = thisForm.elements[i];
		//find element in array of required fields
		if(findElement(thisElem.name,fieldArray)==true) {
		//test on field type
		//alert(thisElem.name+" is a "+thisElem.type+" type field");
		//thisElem.value = sanitise(thisElem.value);
		switch (thisElem.type) {
						//check radio buttons
						case 'radio' :
							//alert('check radio');
							if(isRadioEmpty(thisForm,thisElem.name)) 
							{ 	alert('Please complete '+thisElem.title); 
								thisElem.focus();
								return false;
							}
						break;
						//check select fields
						case 'select-one' :
							//alert('check select');
							if(isSelected(thisElem)==false) 
							{ 	alert('Please complete '+thisElem.title);
								thisElem.focus();
								return false;
							}
						break;
						//check text input
						case 'text' :
								//alert('check text');
								if(isEmpty(thisElem)) 
								{	alert('Please complete '+thisElem.title);
									thisElem.focus();
									return false;
								} 
								if (spamCheck(thisElem)) {
									alert('I\'m sorry! This form doesn\'t allow urls, links or HTML.');
									thisElem.value = '';
									return false;	
								}
								//if email field, check for validity
								if(thisElem.name == "email") {
									if(isEmail(thisElem.value)==false) 
									{	alert('Please enter a valid email address in '+thisElem.title);
										thisElem.focus();
										return false;
									} 
								if (spamCheck(thisElem)) {
										alert('I\'m sorry! This form doesn\'t allow urls, links or HTML.');
										thisElem.value = '';
										return false;	
									}	
								}
								//if phone field, check for validity
								/*if(thisElem.name == "phone") {
									if(isValidPhone(thisElem.value)==false) 
									{	alert('Please enter a valid phone number in '+thisElem.title);
										thisElem.focus();
										return false;
									}	
								}*/
								//if postcode field, check for validity
								/*if(thisElem.name == "postcode") {
									if(isValidPostcode(thisElem.value)==false) 
									{	alert('Please enter a full valid postcode in '+thisElem.title);
										thisElem.focus();
										return false;
									}	
								}*/
								
							//check for and replace quotes	
							thisElem.value = replaceQuote(thisElem.value);
						break;
						//check checkboxes
						case 'checkbox' :
						//alert('check checkbox');
							if (isCheckboxEmpty(thisElem))
								{ 	alert('Please complete '+thisElem.title);
									thisElem.focus();
									return false;
								}
						break;
						//check free text
						case 'textarea' :
						//alert('check checkbox');
							if(isEmpty(thisElem)) 
								{ 	alert('Please complete '+thisElem.title); 
									thisElem.focus();
									return false;
								} 
							if (spamCheck(thisElem)) {
									alert('I\'m sorry! This form doesn\'t allow urls, links or HTML.');
									thisElem.value = '';
									return false;	
								}
							//check for and replace quotes	
							thisElem.value = replaceQuote(thisElem.value);
						break;
						case 'file' :
						//alert('check checkbox');
							if(isEmpty(thisElem)) 
								{ 	alert('Please complete '+thisElem.title); 
									thisElem.focus();
									return false;
								}
						break;
					}
		}
	//next value in form
	//alert('next element');
	i++;
	}
	
	
	
	
	//alert('finished searching');
	return true;
}




			

