/*************************************************************************************************************
**************************************************************************************************************
**************************************Created by: Bas Slagter, 2007*******************************************
****************************************http://www.basslagter.com*********************************************
**************************************************************************************************************
**************************************************************************************************************

Add this file to your webpage bij including it as followed: 
<script src="checkforms.js"	type="text/javascript" ></script>

In your form you can add a 'id' tag to specify what the script needs to check. For example:
	<input 	type="text" 	size="40" 	id="r,ext" 			name="name1[]">
	<input 	type="text" 	size="40" 	id="r,email" 		name="name1[]">
	<input 	type="text" 	size="40" 	id="email" 			name="name2">
	<input 	type="text" 	size="40" 	id="r,postal" 	name="name3">
	<input 	type="text" 	size="40" 	id="r" 					name="name4">
	<select name="mybox" id="r">
		<option value="x">--- Select ---</option>
		<-- your options here -->
	</select>
The 'r' is telling the script that is a required field. The value after the comma (wich is not needed if you just want 
to check on the value) let's the script check for: email, phone, postal, name, ext, or www.
For a required selectfield the script will check on value "x".  Edit settings below:


Below this line are some settings you can use to make the script the way you like it 
=================================================================================================================*/

var req_error_color = "#D32029";					//the color wich the corresponding field gets when it's nog filled in if required
var val_error_color = "#D32029";					//the color wich the corresponding field gets when the filled in value is not correct
var return_color 		= "#ffffff";					//the color to wich a faulty field returns if the value is corrected
var innerColor			= true;							//if true the background will be colored, otherwise just the borders. Note: borders will only work with textboxes

var permitted_extensions = new Array(); 	//array with permitted extensions
permitted_extensions = "jpg";
permitted_extensions[1] = "jpeg";
permitted_extensions[2] = "gif";

var domainArray = new Array(); 						//array with permitted domains for website entry
domainArray = "com";
domainArray[1] = "nl";
domainArray[2] = "eu";
domainArray[3] = "org";
domainArray[4] = "cc";
domainArray[5] = "co";
domainArray[6] = "uk";
domainArray[7] = "tk";

/*Set this option true or false depending on if you want to display a alert or not.
if you set this option to false, the script will write the error into the specified element below.
offcourse, you will need to create this div in your code first. something like: <div id="errorDiv"></div> */
var useAlert 			= true;
var errorDivId 		= "msgDiv";

//Not to edit, just to make a difference for newline's in alert box or html
if(useAlert) { var newline = "\n"; }else{ var newline = "<br />"; }

//Message's wich are displayed when errors occure
var faultyRequiredFields	= "U heeft niet alle verplichte velden ingevuld!" + newline + "Vult u aub de rood aangegeven velden in.";
var msgHead 							= "Corrigeerd u aub de volgende problemen:" + newline;
var faulty_mail 					= "foutief emailadres";
var faulty_phone 					= "foutief telefoonnummer";
var faulty_postal 				= "foutieve postcode";
var faulty_name 					= "foutieve naam invoer";
var faulty_ext 						= "foutieve extensies";
var faulty_www 						= "foutieve website url";


























































/* No need to edit below this line. If you do so, please read comments carefully! 
=================================================================================*/

/*Some variables to check if there are any error's occured
if you decide to extend the functionality of this script please extend this list and don't forget to do the same in the resetAll() function */
var tmpmsg 			= "";
var err_mail 		= false;
var err_phone		= false;
var err_postal	= false;
var err_name		= false;
var err_ext			= false;
var err_www			= false;


function resetAll()
{
	tmpmsg 			= "";
	err_mail 		= false;
	err_phone		= false;
	err_postal	= false;
	err_name		= false;
	err_ext			= false;
	err_www			= false;
}

//Main function; if correct the form will be submitted
function checkForm(myForm)
{
	myForm = document.forms[myForm];
	if(checkRequiredFields(myForm))
	{
		if(checkFieldFormats(myForm))
		{
			myForm.submit();
		}
	}
}

//Function the check either the required fields are filled in or not
function checkRequiredFields(myForm)
{
	var myArray = new Array();
	var skipArray = new Array();
	var error = false;
	resetColors(myForm);

	//Loop trough the fields
	for(var i=0;i<myForm.length;i++)
	{
		try
		{
			if(!myForm[i].className)
			{
				myID = "";
			}else{
				myID = myForm[i].className;
			}
		}catch(err){
			myID = "";
		}
			
		//Place required fields in array, if fieldname is an array it will be placed in special array
		mySplit = myID.split("_");
		
		if(mySplit[0] == "chk" && mySplit[1] == "r")
		{		
			if(!inArray(skipArray, myForm[myForm[i].id]))
			{
				if(isArray(myForm[myForm[i].id]) && myForm[i].type !== "select-one" && myForm[i].type !== "select-multiple")
				{
					skipArray.push(myForm[myForm[i].id]);	
				}else{
					myArray.push(myForm[myForm[i].id]);	
				}
			}
		}
	}
	
	//Loop trough required field and give error if not filled in
	for(var i=0; i<myArray.length; i++)
	{
		if(trim(myArray[i].value) == "" || myArray[i].type == "checkbox" && !myArray[i].checked  || myArray[i].type == "select-one" && myArray[i].options[myArray[i].options.selectedIndex].value == "x" || myArray[i].type == "select-multiple" && !hasSelection(myArray[i]))
		{
			setColor(myArray[i], req_error_color);
			error = true;
		}else{
			setColor(myArray[i], return_color);
		}
	}
	
	//Loop trough array field and give error on seperate fields of not filled in
	for(var i=0; i<skipArray.length; i++)
	{
		for(var y=0;y<skipArray[i].length;y++)
		{
			if(!skipArray[i][y].id)
			{
				myID = "";
			}else{
				myID = skipArray[i][y].id;
			}
			mySplit = myID.split("_");
			
		
			if(trim(skipArray[i][y].value) == "" && mySplit[0] == "r" || skipArray[i][y].type == "checkbox" && skipArray[i][y].checked == false && mySplit[0] == "r" || skipArray[i][y].type == "radio" && !skipArray[i][y].checked && mySplit[0] == "r" && mySplit[0] == "r")
			{
				setColor(skipArray[i][y], req_error_color);
				error = true;
			}else{
				setColor(skipArray[i][y], return_color);
			}
		}
	}
	
	//Show error if needed
	if(error)
	{
		showErrorMessage(faultyRequiredFields);
		return false;
	}else{
		return true;
	}
}

//function to check if multiple selectbox has selection
function hasSelection(myArray)
{
	for(var i=0;i<=myArray.length;i++)
	{
		if(myArray[i].selected)
		{
			return true;
		}
	}
	return false;
}

//Just a regular trim function
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}


//Reset the colors of the field
function resetColors(myForm)
{
	for(var i=0;i<myForm.length;i++)
	{
		if(!isArray(myForm[i]))
		{
			setColor(myForm[i], return_color);
		}else{
			for(var y=0;y<myForm[i].length;y++)
			{
				setColor(myForm[i][y], return_color);
			}
		}
	}
}


//Functions wich shows an error message
function showErrorMessage(myError)
{
	if(useAlert)
	{
		alert(myError);
	}else{
		var myErrorDiv = document.getElementById(errorDivId);
		if(myErrorDiv)
		{
			myErrorDiv.innerHTML = myError;
		}
	}
}

//Function to check filled in values
function checkFieldFormats(myForm)
{
	var error = "";
	msgHead = msgHead;
	var msg = "";
	var skipArray = new Array();
	resetColors(myForm);
		
	//Loop through all form fields again
	for(var i=0;i<myForm.length;i++)
	{
		//If form field is an array, all separate fields are checked
		if(isArray(myForm[myForm[i].id]) && !inArray(skipArray, myForm[myForm[i].id]))
		{
			skipArray.push(myForm[myForm[i].id]);	
			for(var y=0;y<myForm[myForm[i].id].length;y++)
			{
				try
				{
					if(!myForm[myForm[i].id][y].id)
					{
						myID = "";
					}else{
						myID = myForm[myForm[i].id][y].id;
					}
				}catch(err){
					myID = "";
				}
					
				mySplit = myID.split("_");			
				var checkValue = "";
				if(mySplit.length == 1 && mySplit[0] !== "r")
				{
					checkValue = mySplit[0];
				}
				else if(mySplit.length > 1 && mySplit[1] !== "")
				{
					checkValue = mySplit[1];
				}
				
				
				if(checkValue !== "" && myForm[myForm[i].id][y].value !== "")
				{
					if(!checkField(checkValue, myForm[myForm[i].id][y].value))
					{
						setColor(myForm[myForm[i].id][y], val_error_color);
						msg += tmpmsg;
					}else{
						setColor(myForm[myForm[i].id][y], return_color);
					}
				}
			}
			
		//Otherwise just the single field is checked
		}else{
			if(!isArray(myForm[myForm[i].id]))
			{
				try
				{
					if(!myForm[myForm[i].id].id)
					{
						myID = "";
					}else{
						myID = myForm[myForm[i].id].id;
					}
				}catch(err){
					myID = "";
				}
					
				mySplit = myID.split("_");			
				var checkValue = "";
				if(mySplit.length == 1 && mySplit[0] !== "r")
				{
					checkValue = mySplit[0];
				}
				else if(mySplit.length > 1 && mySplit[1] !== "")
				{
					checkValue = mySplit[1];
				}
				
				if(checkValue !== "" && myForm[myForm[i].id].value !== "")
				{
					if(!checkField(checkValue, myForm[myForm[i].id].value))
					{
						setColor(myForm[myForm[i].id], val_error_color);
						msg += tmpmsg;
					}else{
						setColor(myForm[myForm[i].id], return_color);
					}
				}
			}
		}				
	}
		
	//Show message and reset script
	if(msg !== "")
	{
		var errormsg = msgHead + msg;
		showErrorMessage(errormsg);
		msg = "";
		
		resetAll();
		return false;
	}else{
		return true;
	}
}

function setColor(myElement, myColor)
{
	if( innerColor )
	{
		myElement.style.backgroundColor = myColor;
	}else{
		myElement.style.borderColor = myColor;
	}
	return false;
}

//Function wich is called on differend check methods
function checkField(myCheck, myValue)
{
	switch(myCheck)
	{
			case "email": 
				if(!checkMail(myValue))
				{
					
					if(!err_mail) { tmpmsg = "- " + faulty_mail + newline; }else{ tmpmsg = ""; }
					err_mail = true;
					return false;
				}
				break

			case "phone": 
				if(!checkPhone(myValue) )
				{
					if(!err_phone) { tmpmsg = "- " + faulty_phone + newline; }else{ tmpmsg = ""; }
					err_phone = true;
					return false;
				}
				break

			case "postal": 
				if(!checkPostal(myValue))
				{
					if(!err_postal) { tmpmsg = "- " + faulty_postal + newline; }else{ tmpmsg = ""; }
					err_postal = true;
					return false;
				}
				break

			case "name": 
				if(IsNumeric(myValue))
				{
					if(!err_name) { tmpmsg = "- " + faulty_name + newline; }else{ tmpmsg = ""; }
					err_name = true;
					return false;
				}
				break

			case "ext": 
				if(!checkExtension(myValue))
				{
					if(!err_ext) { tmpmsg = "- " + faulty_ext + newline; }else{ tmpmsg = ""; }
					err_ext = true;
					return false;
				}
				break
			
			case "www": 
				if(!checkWWW(myValue))
				{
					if(!err_www) { tmpmsg = "- " + faulty_www + newline; }else{ tmpmsg = ""; }
					err_www = true;
					return false;
				}
				break
	}
	return true;
}

//Email address check function
function checkMail(str)
{
	  var at="@"
	  var dot="."
	  var lat=str.indexOf(at)
	  var lstr=str.length
	  var ldot=str.indexOf(dot)
	  
	  if (str.indexOf(at)==-1)
	  {
	    return false;
	  }
	
	  if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	  {
	   	return false;
	  }
	
	  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	  {
	    return false;
	  }
	
	  if (str.indexOf(at,(lat+1))!=-1)
	  {
	    return false;
	  }
	
	  if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	  {
	    return false;
	  }
	
	  if (str.indexOf(dot,(lat+2))==-1)
	  {
	    return false;
	  }
	  
	  if (str.indexOf(" ")!=-1)
	  {
	    return false;
	  }
	  
	  return true;           
}



//Phone number check
function checkPhone(str)
{	
	if(!IsNumeric(str))
	{
		return false;
	}
		
	return true;
}



//Numeric value check
function IsNumeric(sText)
{
  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;

  for (i = 0; i < sText.length && IsNumber == true; i++) 
  { 
    Char = sText.charAt(i); 
    if (ValidChars.indexOf(Char) == -1) 
    {
      IsNumber = false;
    }
   }
   
   return IsNumber;
}

//Check website value
function checkWWW(str)
{
	var str = str.split(".");
	
	if(str.length < 3)
	{
		return false;
	}
	if(str[0] !== "www")
	{
		return false;
	}
	if(str[1].length < 2)
	{
		return false;
	}
	if(!inArray(domainArray, str[2]))
	{
		return false;
	}
	return true;
}


//Postal code check
function checkPostal(str)
{
	str = str.split(" ");
	
	if(str.length !== 2)
	{
		return false;
	}
	
	if(!IsNumeric(str[0]))
	{
		return false;
	}
	
	if(IsNumeric(str[1]))
	{
		return false;
	}
	
	if(str[0].length > 4 || str[1].length > 2 || str[0].length < 4 || str[1].length < 2)
	{
		return false;
	}
	
	return true;
}

//Extension check
function checkExtension(str)
{
	str = str.split(".")
	var myExt = str[str.length-1];
	
	if(myExt == "")
	{
		//Set to false if empty fields need to fail on this to
		return true;	
	}
	
	if(inArray(permitted_extensions, myExt))
	{
		return true;
	}else{
		return false;
	}
}

//Function to check either an object is array or not
function isArray(myObject)
{
	try
	{
		var tmpVar = myObject[0].value;
	}catch(e){
		return false;
	}
	
	return true;
}

//Function to check if array contains a certain value
function inArray(myArray, myValue)
{
	for(var i=0;i<myArray.length;i++)
	{
		if(myArray[i] == myValue)
		{		
			return true;
		}
	}
	return false;
}

