//*** enable trace instead of alerts
var doTrace = false;

var errorField="";
function formCheck() {
//*** validate form and displey errorMessages

	//*** set errors back to standard style
	if (errorField != "") {
		var errorFieldArray = errorField.split(",");
		for (var i=0;i<errorFieldArray.length-1;i++) {
			formSign(errorFieldArray[i],true);
		}
		errorField = "";
	}
	//*** build array of validated fields and kind of validation
	var validationFieldArray = validationField.split(";");
	var validationProcessArray = validationProcess.split(";");
	for (var i=0;i<validationFieldArray.length-1;i++) {
		formValidate(validationFieldArray[i], validationProcessArray[i]);
	}
	//*** mark errors of validation
	var errorFieldArray = errorField.split(",");
	for (var i=0;i<errorFieldArray.length-1;i++) {
		formSign(errorFieldArray[i],false);
	}
	
	//*** display error message or submit form
	if (errorField != "") {
		document.getElementById("errorMessageTop").style.display = "block";
		document.getElementById("errorMessageBottom").style.display = "block";
	} else {
		document.forms[0].submit();
	}
}


function formValidate(fieldName, processName) {
//*** validate each field depending on kind of validation

	var value = "";
	var processNameArray = processName.split(",");
	for (var i=0;i<processNameArray.length;i++) {
		//*** field must be a date
		if (processNameArray[i]=="Date") {
			value = eval("document.forms[0]."+fieldName+".value");
			if (!isDate(value)) {
				errorField+=fieldName + ",";
			}
		}

		//*** field must be filled with any value
		if (processNameArray[i]=="Captcha") {
			value = eval("document.forms[0]."+fieldName+".value");
			if (value != "9") {
				errorField+=fieldName + ",";
			}
		}

		//*** field must be filled with any value
		if (processNameArray[i]=="Filled") {
			value = eval("document.forms[0]."+fieldName+".value");
			if (value == "") {
				errorField+=fieldName + ",";
			}
		}
		//*** field must be a string
		if (processNameArray[i]=="String") {
			value = eval("document.forms[0]."+fieldName+".value");
			if (!isNaN(value)) {
				errorField+=fieldName + ",";
			}
		}
		//*** field must be a number
		if (processNameArray[i]=="Number") {
			value = eval("document.forms[0]."+fieldName+".value");
			if ((isNaN(value)) || (value == "")) {
				errorField+=fieldName + ",";
			}
		}
		//*** field must be checked with 1 value
		if (processNameArray[i]=="CheckedRadio") {
			for (var j=0;j<eval("document.forms[0]."+fieldName+".length");j++) {
				value += eval("document.forms[0]."+fieldName+"[j].checked");
			}
			if (value.indexOf("true") == -1) {
				errorField+=fieldName + ",";
			}
		}
		//*** field must be checked
		if (processNameArray[i]=="CheckedCheckbox") {
			value += eval("document.forms[0]."+fieldName+".checked");
			if (value.indexOf("true") == -1) {
				errorField+=fieldName + ",";
			}
		}
		//*** field must be an email address
		if (processNameArray[i]=="EmailAddress") {
			if(!emailAdressCheck(eval("document.forms[0]."+fieldName+".value"),"de")) {
				errorField+=fieldName + ",";
			}
		}
		//*** field must have a length of at least ...
		if (!isNaN(processNameArray[i])) {
			value = eval("document.forms[0]."+fieldName+".value");
			if (value.length < processNameArray[i]) {
				errorField+=fieldName + ",";
			}
		}
	}
}


function formSign(fieldName,ok) {
//*** mark fields with errors

	if (ok) {
		document.getElementById(fieldName+"Pointer").style.color = "#000000";
	}
	else {
		document.getElementById(fieldName+"Pointer").style.color = "#ff0000";
	}
}


function trace(tracerName, tracer) {
//*** trace instead of alerts
	if (doTrace) {
		alert("***    " + tracerName + " : <" + tracer + ">");
		
	}
}


function replaceCharacter(stringToChange, findStr, replaceStr) {
  r = new RegExp(findStr,"ig");
  t = stringToChange.replace(r, replaceStr);
  return t;
}


var dtCh= ".";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}

function emailAdressCheck(emailStr,language) {
	if (!language) language = "de"; //default deutsch
	var ue = String.fromCharCode(252); //umlaut
	
	var errorEmailHTML;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	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 nsc (basically a series of
	   non-special characters.) */
	var nsc=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 nsc or quoted string. */
	var word="(" + nsc + "|" + 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("^" + nsc + "(\\." + nsc +")*$");


	/* 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. */
		if (language == "de") errorEmailHTML = "Die email-Adresse ist nicht korrekt (achten Sie auf @ und Punkte.)"; else errorEmailHTML = "Email address seems incorrect (check @ and .'s)";
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

		// See if "user" is valid 
	if (user.match(userPat)==null) {
    	// user is not valid
    	if (language == "de") errorEmailHTML = "Der email-Username ist nicht korrekt."; else errorEmailHTML = "The email 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) {
		        if (language == "de") errorEmailHTML = "Die Ziel-IP der email-Adresse ist ung" + ue + "ltig!"; else errorEmailHTML = "Destination IP of email address is invalid!";
			return false;
		    }
	    }
	    return true;
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat);
	if (domainArray==null) {
		if (language == "de") errorEmailHTML = "Die email-Domain scheint ung" + ue + "ltig zu sein."; else errorEmailHTML = "The email domain name doesn't seem to be valid.";
	    return false;
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many nscs
	   it consists of. */
	var nscPat=new RegExp(nsc,"g");
	var domArr=domain.match(nscPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   if (language == "de") errorEmailHTML = "Die email-Domain scheint ung" + ue + "ltig zu sein."; else errorEmailHTML = "The email address must end in a three-letter domain, or two letter country."
	   return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr = "";
	   if (language == "de") errStr = "Der Hostname der email-Adresse fehlt!"; else errStr = "This email address is missing a hostname!"; 
	   errorEmailHTML = errStr
	   return false;
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}
