// ### Validation Functions ### //

///////////////////////////////////////////////////////////////////////////////
var PHPForm = new Object();
PHPForm.val_required = Array();
PHPForm.val_regex = Array();
PHPForm.val_numeric = Array();
PHPForm.val_callback = Array();
PHPForm.val_selected = Array();
PHPForm.val_dropdownnotnull = Array();
PHPForm.val_phonenumber = Array();
PHPForm.val_validemail = Array();

var FormName;

///////////////////////////////////////////////////////////////////////////////
PHPForm.add_required = function add_required (elname, form, valnum) {
	// Add element name to required array
	PHPForm.val_required.push (Array(elname, form, valnum));
	FormName = form;
}
PHPForm.add_numeric = function (elname, form, valnum) {
	// Add element name to numeric array
	PHPForm.val_numeric.push (Array(elname, form, valnum));
}
PHPForm.add_regex = function (elname, form, valnum, regex) {
	// Add element name to regex array
	PHPForm.val_regex.push (Array(elname, form, valnum, regex));
}
PHPForm.add_callback = function (elname, form, valnum, callback) {
	// Add element name to callback array
	PHPForm.val_callback.push (Array(elname, form, valnum, callback));
}
PHPForm.add_selected = function (elname, form, valnum) {
	// Add element name to selected array
	PHPForm.val_selected.push (Array(elname, form, valnum));
}
PHPForm.add_dropdownnotnull = function (elname, form, valnum) {
	// Add element name to dropdownnotnull array
	PHPForm.val_dropdownnotnull.push (Array(elname, form, valnum));
}
PHPForm.add_phonenumber = function (elname1, elname2, elname3, form, valnum) {
	// Add element name to phonenumber array
	PHPForm.val_phonenumber.push (Array(elname1, elname2, elname3, form, valnum));
}
PHPForm.add_validemail = function (elname, form, valnum) {
	// Add element name to validemail array
	PHPForm.val_validemail.push (Array(elname, form, valnum));
}


///////////////////////////////////////////////////////////////////////////////
PHPForm.do_validemail_validate = function (formel) {
	var returnval = true;
		
	for (var i = 0; i < PHPForm.val_validemail.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_validemail[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		el = formel.elements[elname];
		el_value = el.value;
		
		// Check value
		if (emailCheck(el_value) == false) {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			PHPForm.hide (form + '_normal_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
			PHPForm.show(form + '_normal_' + valnum);
		}
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_phonenumber_validate = function (formel) {
	var returnval = true;

	// Loop numeric
	for (var i = 0; i < PHPForm.val_phonenumber.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_phonenumber[i];
		var elname1 = temp[0];
		var elname2 = temp[1];
		var elname3 = temp[2];
		var form = temp[3];
		var valnum = temp[4];
		
		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// A Phone Number looks like XXX XXX XXXX
		
		// Get element1
		el1 = formel.elements[elname1];
		el_value1 = PHPForm.get_value(el1);
		// Get element2
		el2 = formel.elements[elname2];
		el_value2 = PHPForm.get_value(el2);
		// Get element3
		el3 = formel.elements[elname3];
		el_value3 = PHPForm.get_value(el3);
		
		// Check value
		if ((el_value1 == null || el_value1.length != 3 || PHPForm.IsNumeric(el_value1) == false) || 
			  (el_value2 == null || el_value2.length != 3 || PHPForm.IsNumeric(el_value2) == false) || 
			  (el_value3 == null || el_value3.length != 4 || PHPForm.IsNumeric(el_value3) == false)) {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			PHPForm.hide (form + '_normal_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
			PHPForm.show (form + '_normal_' + valnum);
		}
	}
	
	return returnval;
}

///////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////
PHPForm.do_regex_validate = function (formel) {
	var returnval = true;

	// Loop regex
	for (var i = 0; i < PHPForm.val_regex.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_regex[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];
		var regex = temp[3]

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		el = formel.elements[elname];
		el_value = PHPForm.get_value(el);

		// Check regex
		if (!el_value.match(regex)) {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
		}
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_callback_validate = function (formel) {
	var returnval = true;

	for (var i = 0; i < PHPForm.val_callback.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_callback[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];
		var callback = temp[3];

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		el = formel.elements[elname];
		el_value = PHPForm.get_value(el);

		// Create code
		code = "if (window." + callback + ") {\n";
			code = code + "if (typeof(el_value) == 'string' && " + callback + "(el_value) == true) {\n";
			code = code + "result = true;\n";
			code = code + "} else {\n";
			code = code + "result = false;\n";
			code = code + "}\n";
		code = code + "} else {\n";
		code = code + "result = null;\n";
		code = code + "}";

		// Execute code
		eval(code);

		// Check result
		if (result == false) {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			returnval = false;
		} else if (result == true) {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
		} 
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_selected_validate = function (formel) {
	var returnval = true;

	for (var i = 0; i < PHPForm.val_selected.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_selected[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		el = formel.elements[elname];
		el_value = el.selectedIndex;

		// Check value
		if (el_value == -1) {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
		}
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_dropdownnotnull_validate = function (formel) {
	var returnval = true;
		
	for (var i = 0; i < PHPForm.val_dropdownnotnull.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_dropdownnotnull[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		el = formel.elements[elname];
		el_value = el.value;
		
		// Check value
		if (el_value == "null") {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			PHPForm.hide (form + '_normal_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
			PHPForm.show(form + '_normal_' + valnum);
		}
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_required_validate = function (formel) {
	var returnval = true;
		
	// Loop required
	for (var i = 0; i < PHPForm.val_required.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_required[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		el = formel.elements[elname];
		el_value = PHPForm.get_value(el);

		// Check value
		if (el_value == null || el_value == '') {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			PHPForm.hide (form + '_normal_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
			PHPForm.show(form + '_normal_' + valnum);
		}
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_numeric_validate = function (formel) {
	var returnval = true;

	// Loop numeric
	for (var i = 0; i < PHPForm.val_numeric.length; i++ ) {
		// Get variables
		var temp = PHPForm.val_numeric[i];
		var elname = temp[0];
		var form = temp[1];
		var valnum = temp[2];

		// Check form
		if (typeof(formel.__FORM.value) != 'string' || form != formel.__FORM.value) { continue; }

		// Get element
		// Get element
		el = formel.elements[elname];
		el_value = PHPForm.get_value(el);

		// Check value
		if (el_value == null || PHPForm.IsNumeric(el_value) == false) {
			// Show validator
			PHPForm.show(form + '_validator_' + valnum);
			returnval = false;
		} else {
			// Hide validator
			PHPForm.hide (form + '_validator_' + valnum);
		}
	}

	return returnval;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.do_validate = function (e) {
	var cancel_submit = false;

	// Hide all error messages first
	PHPForm.hide_validators();

	// Get caller form name
	var formel = PHPForm.getTarget(e);

	// Do Required Validate
	if (PHPForm.do_required_validate(formel) == false) { cancel_submit = true; }

	// Do Numeric Validate
	if (PHPForm.do_numeric_validate(formel) == false) { cancel_submit = true; }

	// Do Regex Validate
	if (PHPForm.do_regex_validate(formel) == false) { cancel_submit = true; }

	// Do Callback Validate
	if (PHPForm.do_callback_validate(formel) == false) { cancel_submit = true; }

	// Do Selected Validate
	if (PHPForm.do_selected_validate(formel) == false) { cancel_submit = true; }
	
	// Do DropDownNutNull Validate
	if (PHPForm.do_dropdownnotnull_validate(formel) == false) { cancel_submit = true; }
	
	// Do PhoneNumber Validate
	if (PHPForm.do_phonenumber_validate(formel) == false) { cancel_submit = true; }
	
	// Do ValidEmail Validate
	if (PHPForm.do_validemail_validate(formel) == false) { cancel_submit = true; }

	var requiredNoticeActive = FormName + "_notice_on";
	var requiredNoticePassive = FormName + "_notice_off";
	if (cancel_submit == false)
	{
	  PHPForm.hide (requiredNoticeActive);
	  PHPForm.show (requiredNoticePassive);
	}
	
	// Should we stop the form from submitting?
	if (cancel_submit == true)
	{
	  PHPForm.hide (requiredNoticePassive);
	  PHPForm.show (requiredNoticeActive);
		
		if (e && e.preventDefault) {
		e.preventDefault(); // DOM style
		}

		return false; // IE style
	}
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.hide_validators = function () {
	var spans = document.getElementsByTagName('span');

	// Loop through each span
	for (var i=0; i < spans.length;i++) {
		// Classname equals php_form_validator?
		if (spans[i].className == 'php_form_validator') {
			PHPForm.hide (spans[i]);
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.getElementByName = function (name, ownerform) {
	var els = document.getElementsByName(name);
	
	// Any matches?
	if (els.length < 1)	{ return null; }

	// Should we look for a particular form?
	if (ownerform == '' || ownerform == null) {
		// Make sure we actually return an object
		for (var i = 0;i < els.length;i++ ) {
			if (els[i].name) {
				return els[i];
			}
		}
	}

	for (var i = 0;i < els.length;i++ ) {
		// Correct form?
		if (els[i].form && els[i].form.__FORM.value == ownerform) {
			return els[i];
		}
	}
}

PHPForm.IsNumeric = function (strString) {
	var strValidChars = "0123456789.-,";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);

		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}

	return blnResult;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.hide = function (element) {
	if (typeof(element) == 'string') {
		el = document.getElementById(element);
	} else if (typeof(element) == 'object') {
		el = element;
	} else {
		return false;
	}

	if (typeof(el) == 'object' && el != null && el.style) {
			el.style.display = 'none';
	}
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.show = function(element, display) {
	if (typeof(element) == 'string') {
		el = document.getElementById(element);
	} else if (typeof(element) == 'object') {
		el = element;
	} else {
		return false;
	}

	if (typeof(el) == 'object' && el != null && el.style) {
			el.style.display = '';
	}
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.addEventListener = function (target,type,callback,captures) {
	if (target == null) { return false; }

	if (target.addEventListener) {
		// EOMB
		target.addEventListener(type,callback,captures);
	} else if (target.attachEvent) {
		// IE
		target.attachEvent('on'+type,callback,captures);
	} else {
		// IE 5 Mac and some others
		target['on'+type] = callback;
	}
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.getTarget = function(event) {
	if (event.target) {
		targ = event.target;
	} else if (event.srcElement) {
		targ = event.srcElement;
	}

	// Defeat Safari bug
	if (targ.nodeType == 3)	{
		targ = targ.parentNode;
	}

	return targ;
}

///////////////////////////////////////////////////////////////////////////////
PHPForm.get_value = function (el) {
	// Is nodeList or not?
	if (typeof(el[0]) != 'object') {
		// Nope, just return value
		return el.value;
	}

	// Yes, nodeList: loop through it
	for (var i=0; i < el.length; i++) {
		var el_child = el[i];

		// Is checked?
		if (el_child.checked == true) {
			return el_child.value
		}
	}

	// If we reach this, then nothing has been checked
	return null;
}

///////////////////////////////////////////////////////////////////////////////
// For Backwards Compatibility (with PHP:Form 1.0)
function add_required (elname, form, valnum) { PHPForm.add_required(elname, form, valnum); }
function add_numeric (elname, form, valnum) { PHPForm.add_numeric(elname, form, valnum); }
function add_regex (elname, form, valnum, regex) { PHPForm.add_regex(elname, form, valnum, regex); }
function add_callback (elname, form, valnum, callback) { PHPForm.add_callback(elname, form, valnum, callback); }
function add_selected (elname, form, valnum) { PHPForm.add_selected(elname, form, valnum); }
function add_dropdownnotnull (elname, form, valnum) { PHPForm.add_dropdownnotnull(elname, form, valnum); }
function add_phonenumber (elname1, elname2, elname3, form, valnum) { PHPForm.add_phonenumber(elname1, elname2, elname3, form, valnum); }
function add_emailvalid (elname, form, valnum) { PHPForm.add_emailvalid(elname, form, valnum); }
function do_validate (e) { return PHPForm.do_validate(e); }
function getElementByName (name, ownerform) { return PHPForm.getElementByName(name, ownerform); }
function addEventListener(target,type,callback,captures) { PHPForm.addEventListener(target,type,callback,captures); }

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// For Checking Email Address Code

function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

//alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
//alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
//alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

//alert("The username doesn't seem to be valid.");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
//alert("Destination IP address is invalid!");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
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 does not seem to be valid.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
//alert("The address must end in a well-known domain or two letter " + "country.");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
//alert("This address is missing a hostname!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}