// Generic Form Validation
// Jacob Hage (jacob@hage.dk)
// Extended by Lex & Mathilde
var checkObjects	= new Array();
var errors			= "";
var returnVal		= false;
var language		= new Array();

var stripChar		= /^\$|,| |&/g; 

language["header"]	= "The following error(s) occured:"
language["start"]	= "->";
language["field"]	= " ";
language["require"]	= " is required";
language["min"]		= " and must consist of at least ";
language["max"]		= " and must not contain more than ";
language["minmax"]	= " and no more than ";
language["chars"]	= " characters";
language["num"]		= " and must contain a number";
language["email"]	= " must contain a valid e-mail address";
language["zip"]	    = " must contain 4 numbers followed by two letters";
language["tel"]	    = " must contain 10 numbers starting with 06";
// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------
function define(n, type, HTMLname, min, max, d) {
	var p;
	var i;
	var x;
	if (!d) d = document;
		if ((p=n.indexOf("?"))>0&&parent.frames.length) {
			d = parent.frames[n.substring(p+1)].document;
			n = n.substring(0,p);
		}
	if (!(x = d[n]) && d.all) x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++) {
		x = d.forms[i][n];
	}
	for (i = 0; !x && d.layers && i < d.layers.length; i++) {
		x = define(n, type, HTMLname, min, max, d.layers[i].document);
	return x;       
	}
	eval("V_"+n+" = new formResult(x, type, HTMLname, min, max);");
	checkObjects[eval(checkObjects.length)] = eval("V_"+n);
	}

function redefine(n, type, HTMLname, min, max, d) {
	var p;
	var i;
	var x;
	if (!d) d = document;
		if ((p=n.indexOf("?"))>0&&parent.frames.length) {
			d = parent.frames[n.substring(p+1)].document;
			n = n.substring(0,p);
		}
	if (!(x = d[n]) && d.all) x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++) {
		x = d.forms[i][n];
	}
	for (i = 0; !x && d.layers && i < d.layers.length; i++) {
		x = redefine(n, type, HTMLname, min, max, d.layers[i].document);
	return x;       
	}
	eval ("V_"+n+" = new formResult(x, type, HTMLname, min, max);");
	checkObjects[eval(checkObjects.length-1)] = eval("V_"+n);

}

function checkTrendCodes (TrendCode){
	var Minutes = 0;
	TrendCode = TrendCode.toUpperCase();
	if (TrendCode.length == 10) {
			if (TrendCode.substring(0,6) == TrendCodeM1.substring(0,6)) {Minutes = 5;}
			else if (TrendCode.substring(0,6) == TrendCodeM2.substring(0,6)) {Minutes = 0;}
			else if (TrendCode.substring(0,6) == TrendCodeM3.substring(0,6)) {Minutes = 10;} 
			else if (TrendCode.substring(0,6) == TrendCodeM4.substring(0,6)) {Minutes = 0;}
			}
return Minutes;
}

function checkTrendCodesDiscount (TrendCode){
	var Discount = 0;
	TrendCode = TrendCode.toUpperCase();
	if (TrendCode.length == 10) {
			if (TrendCode.substring(0,6) == TrendCodeD1.substring(0,6)) {Discount = 4.95;}
			else if (TrendCode.substring(0,6) == TrendCodeD2.substring(0,6)) {Discount = 9.95;} 
			else if (TrendCode.substring(0,6) == TrendCodeD3.substring(0,6)) {Discount = 9.95;} 
			else if (TrendCode.substring(0,6) == TrendCodeD4.substring(0,6)) {Discount = 12.50;}
    		}
return Discount;
}


function isBlank(val)
{
	if( val==null )
	{
		return true;
	}
	for(var i=0;i<val.length;i++) 
	{
		if ((val.charAt(i)!=' ') &&
				(val.charAt(i)!="\t") &&
				(val.charAt(i)!="\n") &&
				(val.charAt(i)!="\r"))
		{
			return false;
		}
	}
	return true;
}

function isDigit(num) 
{
	if( num.length>1 )
	{
		return false;
	}
	var string="1234567890";
	if (string.indexOf(num)!=-1)
	{
		return true;
	}
	return false;
}

function isChar(mychar) 
{
	if( mychar.length > 1 )
	{
		return false;
	}
	var string="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	if( string.indexOf( mychar ) !=-1 )
	{
		return true;
	}
	return false;
}

function isInteger(val)
{
	if( isBlank( val ))
	{
		return false;
	}
	for(var i=0;i<val.length;i++)
	{
		if(!isDigit(val.charAt(i)))
		{
			return false;
		}
	}
	return true;
}
function isAlpha( val )
{
	if( isBlank( val ))
	{
		return false;
	}
	for(var i=0;i < val.length;i++)
	{
		if(!isChar(val.charAt(i)))
		{
			return false;
		}
	}
	return true;
}

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. */
language["email"]	= " must contain a valid email 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) {
language["email"]	= " must contain a valid user name.";
//alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
language["email"]	= " must contain a valid domain name.";
//alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid
language["email"]	= " must contain a valid user name.";
//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) {
language["email"]	= " must contain a vaid IP Address or domain name.";
//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) {
language["email"]	= " must contain a valid domain name.";
//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) {
language["email"]	= " must end in a well-known domain or two letter " + "country.";
//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) {
language["email"]	= " must contain a hostname.";
//alert("This address is missing a hostname!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}


function formResult(form, type, HTMLname, min, max) {
this.form = form;
this.type = type;
this.HTMLname = HTMLname;
this.min  = min;
this.max  = max;
}

function validate() {
if (checkObjects.length > 0) {
errorObject = "";

for (i = 0; i < checkObjects.length; i++) {
validateObject = new Object();
validateObject.form = checkObjects[i].form;
validateObject.HTMLname = checkObjects[i].HTMLname;
validateObject.val = checkObjects[i].form.value;
validateObject.len = checkObjects[i].form.value.length;
validateObject.min = checkObjects[i].min;
validateObject.max = checkObjects[i].max;
validateObject.type = checkObjects[i].type;

if (validateObject.type == "num" || validateObject.type == "string") 
{ 
	if ((validateObject.type == "num" && validateObject.len <= 0) || (validateObject.type == "num" && isNaN(validateObject.val))) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['num'] + "\n";
		} else if (validateObject.min && validateObject.max && (validateObject.len < validateObject.min || validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['minmax'] + validateObject.max+language['chars'] + "\n";
		} else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['min'] + validateObject.min + language['chars'] + "\n";
		} else if (validateObject.max && !validateObject.min &&(validateObject.len > validateObject.max)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['max'] + validateObject.max + language['chars'] + "\n";
		} else if (!validateObject.min && !validateObject.max && validateObject.len <= 0) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + "\n";
		}
} 

else if(validateObject.type == "email") 
{
	// Checking existense of "@" and ".". 
	// Length of must >= 5 and the "." must 
	// not directly precede or follow the "@"
	if (!emailCheck(validateObject.val)) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['email'] + "\n";}
} //if email

else if(validateObject.type == "trendcall")
{
	//check NL tel (field may also be left empty)
	if (validateObject.len>0 && ((validateObject.val.substring(0,2)!="06") || (validateObject.val.substring(2,1)=="0") || (validateObject.len!=10 ))) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['tel'] + "\n";}
}

else if(validateObject.type == "tel")
{
	//check NL tel 
	if ((validateObject.val.substring(0,2)!="06") || (validateObject.val.substring(2,1)=="0") || (validateObject.len!=10 )) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['tel'] + "\n";}
}


else if(validateObject.type == "zip")
{
	//check NL zip code
	if ( (validateObject.len < 6) || (!isAlpha(validateObject.val.substring(4,6))) || (!isInteger(validateObject.val.substring(0,4))) ) { errors += language['start'] + language['field'] + validateObject.HTMLname + language['zip'] + "\n";}
}

   }  //for
} //validate


if (errors) {
alert(language["header"].concat("\n" + errors));
errors = "";
returnVal = false;
} else {
returnVal = true;
   }
}


function disableForm(theform) {
	if (document.all || document.getElementById) {
		for (i = 0; i < theform.length; i++) {
			var tempobj = theform.elements[i];
				if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
				tempobj.disabled = true;
			}
	}
}

