/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Copyright Cylo.co.uk
Written by Graham Vincent 
Contact :: loudsphiers@gmail.com
Last Updated: 17/06/2008
*/
CyloAutoForm = new Object();
CyloAutoForm.DefDelimV = "[>]";
CyloAutoForm.DefDelimP = "[|]";
CyloAutoForm.autoValidateForm = function(form)
{
	
	source = "none";
	callback = "none";
	var url = "";
	formname = form.id;
	doc=form;
	result = true;
	for(i=0; i < doc.elements.length; i++)
	{ 
		
		var nameOfEle = doc.elements[i].name;
		var idOfEle = doc.elements[i].id;
		var type = doc.elements[i].type;
		var value = doc.elements[i].value;
		if(typeof(value)=="undefined")value="";
		var className = doc.elements[i].className;
		
		className=className.toLowerCase();
		if(className.indexOf("usename[") > -1)
		{ 
			t = className.substring(className.indexOf("usename[")+8);
			t = t.substring(0,t.indexOf("]"));
			if(t!="")nameOfEle = t;			
		}
		
		if(className.indexOf("autoIgnore")!=-1){type="ignore";className="ignore";}

		if((className.indexOf("*") > -1) && value=="")
		{ 
			CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can not be empty");
			return false;
		}
		if (className.indexOf("int[]") > -1 && value!="")
		{ 
			if(isNaN(value)==true)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + " is not a number");
				return false;
			}
		}
		if(className.indexOf("min[") > -1 && value!="")
		{ 
			t = className.substring(className.indexOf("min[")+4);
			t = t.substring(0,t.indexOf("]"));
			if(value.length < t)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + "\n\n The "+doc.elements[i].name+" must be at least "+t+" characters in length.");
				return false;
			}				
		}
		if(className.indexOf("max[") > -1 && value!="")
		{ 
			t = className.substring(className.indexOf("max[")+4);
			t = t.substring(0,t.indexOf("]"));
			if(value.length > t)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + "\n\n The "+doc.elements[i].name+" can't be more than "+t+" characters in length.");
				return false;
			}
		}

		if(className.indexOf("email[]") > -1 && value!="")
		{ 
			if(CyloAutoForm.emailCheck(value)==false)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + " is not a valid email address");
				return false;
			}
		}
		if(className.indexOf("match[") > -1 && value!="")
		{ 
			t = className.substring(className.indexOf("match[")+6);
			t = t.substring(0,t.indexOf("]"));
			if( value != document.getElementById(t).value)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + " does not match "+document.getElementById(t).name);
				return false;
			}
		}
		if (className.indexOf("nsq[]") > -1 && value!="")
		{ 
			//No single quotes allowed
			if(value.indexOf("'")>-1)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can not contain single quotes");
				return false;
			}
		}
		if (className.indexOf("ndq[]") > -1 && value!="")
		{
			//No double quotes allowed
			if(value.indexOf("\"")>-1)
			{ 
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can not contain double quotes");
				return false;
			}
		}
		if (className.indexOf("oftype[") > -1&& value!="")
		{ 
			t = className.substring(className.indexOf("oftype[")+7);
			t= t.substring(0,t.indexOf("]"));
			
			switch(t)
			{
				case "alphanumeric":
					if(CyloAutoForm.isAlphaNumeric(value)==false)
					{
						CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can only contain letters and numbers");
						return false;
					}
				break;
				case "alpha":
					if(CyloAutoForm.isAlpha(value)==false)
					{
						CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can only contain letters");
						return false;
					}
				break;
				case "numeric":
					if(isNaN(value)==true);
					{
						CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can only contain numbers");
						return false;
					}
				break;
				case "symbol":
					if(CyloAutoForm.issymbol(value)==false)
					{
						CyloAutoForm.addPrompt(idOfEle,nameOfEle + " can only contain symbols");
						return false;
					}
				break;
				default:break;
			}
		}
		
		if (className.indexOf("func[") > -1&& value!="")
		{ 
			//test value with a user defined function
			t = className.substring(className.indexOf("func[")+5);
			t = t.substring(0,t.indexOf("]"));
			
			if(eval(t+"('"+value+"')")==false)
			{
				CyloAutoForm.addPrompt(idOfEle,nameOfEle + " fails to meet the required format");
				return false;
			}
		}
		//You can either return true HERE to submit the form, or you can build up a URL string
		//for use with an AJAX application. 
		//return true;
		
		switch (type)
		{ 
			case "reset":break;
			case "submit":break;
			case "button":break; 
			case "text":url += idOfEle + CyloAutoForm.DefDelimV + CyloAutoForm.niceurl(CyloAutoForm.trim(value)) + CyloAutoForm.DefDelimP;break; 
			case "password":url += idOfEle + CyloAutoForm.DefDelimV + CyloAutoForm.niceurl(CyloAutoForm.trim(value)) + CyloAutoForm.DefDelimP;break;
			case "textarea":url += idOfEle + CyloAutoForm.DefDelimV + CyloAutoForm.niceurl(CyloAutoForm.trim(value))+ CyloAutoForm.DefDelimP;break;
			case "checkbox":
			if (doc.elements[i].checked==true)
			{ 
				if(value=="on")value="1";
				url += idOfEle + CyloAutoForm.DefDelimV + value + CyloAutoForm.DefDelimP;
			}
			break; 
			case "hidden":
			if(idOfEle=="source")source = value; 
			if(idOfEle=="callback")callback = value; 
			url += idOfEle + CyloAutoForm.DefDelimV + value + CyloAutoForm.DefDelimP;break; 
			case "image":url += idOfEle + CyloAutoForm.DefDelimV + value + CyloAutoForm.DefDelimP;break; 
			case "radio":
			tempradio = doc.elements[i]; 
			for(x=0;x<tempradio.length;x++)
			{
				if(tempradio[x].checked==true)
				{
					url += idOfEle + CyloAutoForm.DefDelimV + tempradio[x].value + CyloAutoForm.DefDelimP;
				}
			}
			break;
			case "select-multiple":
			if(className.indexOf("multi_all") > -1)
			{ 
				wait = selAll(idOfEle);
			}
			for (var x = 0; x< doc.elements[i].length; x++)
			{ 
				if (doc.elements[i].options[x].selected)
				{ 
					url += idOfEle + CyloAutoForm.DefDelimV + doc.elements[i].options[x].value + CyloAutoForm.DefDelimP;
				}
			}
			break; 
			case "select-one":
			if(doc.elements[i].selectedIndex > -1)
			{ 
				url += idOfEle + CyloAutoForm.DefDelimV + doc.elements[i].options[doc.elements[i].selectedIndex].value + CyloAutoForm.DefDelimP;
			}
			break;
		}
	}
	//You can define a call back function in a hidden input field called 'callback'
	//which will be called and passed the url variable or pass this on to a generic function.
	if(result == true && callback!="none")
	{ 
		eval(callback + "('"+url+"')");
	}else{
		CyloAutoForm.addPrompt("","No CallBack Function specified! This form requires a callback value");
	}
	return false;
}
CyloAutoForm.isAlphaNumeric = function(w)
{
	
	chars="1234567890abcdefghijklmnopqrstuvwxyz";
	w=w.toLowerCase();
	for(x=0;x<w.length;x++)
	{
		if(chars.indexOf(w.charAt(x))==-1)return false;
	}
	return true;
}
CyloAutoForm.isAlpha = function(w)
{
	chars="abcdefghijklmnopqrstuvwxyz";
	w=w.toLowerCase();
	for(x=0;x<w.length;x++)
	{
		if(chars.indexOf(w.charAt(x))==-1)return false;
	}
	return true;
}


CyloAutoForm.issymbol = function(w)
{
	chars="!£$%^&*()_+=-{}[]:@;'<>,.?/";
	for(x=0;x<w.length;x++)
	{
		if(chars.indexOf(w.charAt(x))==-1)return false;
	}
	return true;
}
CyloAutoForm.addPrompt = function(id,prompt)
{
	alert(prompt);
}

CyloAutoForm.niceurl = function(in_text)
{ 
	//swaps out ampersands, question marks and equals signs so as not to mess up a URL
	out_text = "";
	badchars = new Array(2);
	goodchars = new Array(2);
	badchars[0] = "&";
	goodchars[0] = "[AMP]";
	badchars[1] = "?";
	goodchars[1] = "[QM]";
	badchars[1] = "=";
	goodchars[1] = "[EQ]";
	had = false;
	for(var x = 0; x < badchars.length; x++)
	{ 
		if(in_text.indexOf(badchars[x]) > -1)
		{ 
			had = true;
			in_text = CyloAutoForm.replaceAll(in_text,badchars[x],goodchars[x]);
		}
	}
	return in_text;
}


CyloAutoForm.emailCheck = function(e)
{ 
//{0}REF : http://www.mantissa.co.uk I used to work for this company
	var emailStr;
	emailStr = e;
	valid = true;
	
	var checkTLD=0; 
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|uk|se)$/; 
	var emailPat=/^(.+)@(.+)$/; 
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; 
	var validChars="\[^\\s" + specialChars + "\]"; 
	var quotedUser="(\"[^\"]*\")"; 
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; 
	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("The email address is invalid"); 
		valid = false;
	}else
	{
		var user=matchArray[1]; 
		var domain=matchArray[2]; 
		
		for (i=0; i<user.length; i++)
		{ 
			if (user.charCodeAt(i)>127)
			{ 
				//alert("The username contains invalid Characters."); 
				valid = false; 
			} 
		} 
		for (i=0; i<domain.length; i++)
		{ 
			if (domain.charCodeAt(i)>127)
			{ 
				//alert("The domain dame contains invalid characters."); 
				valid = false; 
			} 
		} 
		if (user.match(userPat)==null)
		{ 
			//alert("The username is invalid."); 
			valid = false; 
		} 
		
		var IPArray=domain.match(ipDomainPat); 
		if (IPArray!=null)
		{ 
			for (var i=1;i<=4;i++)
			{ 
				if (IPArray[i]>255)
				{ 
					//alert("The destination IP address is invalid."); 
					valid = false; 
				} 
			} 
			
		} 
		var atomPat=new RegExp("^" + atom + "$"); 
		var domArr=domain.split("."); 
		var len=domArr.length; 
		for (i=0;i<len;i++)
		{ 
			if (domArr[i].search(atomPat)==-1)
			{ 
				//alert("The domain name is invalid."); 
				valid = false;
			} 
		} 
		if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
		{ 
			//alert("The domain name extension is invalid"); 
			valid = false; 
		} 
		if (len<2)
		{ 
			//alert("The address is missing a hostname."); 
			valid = false; 
		} 
	}
	return valid;
}

CyloAutoForm.replaceAll = function(str,from,to)
{ var idx = str.indexOf( from ); while ( idx > -1 ) { str = str.replace( from, to ); idx = str.indexOf( from );}
return str;}

CyloAutoForm.lTrim = function( value ) { var re = /\s*((\S+\s*)*)/; return value.replace(re, "$1");}
CyloAutoForm.rTrim = function( value ) { var re = /((\s*\S+)*)\s*/; return value.replace(re, "$1");}
CyloAutoForm.trim = function( value ) { return CyloAutoForm.lTrim(CyloAutoForm.rTrim(value));}