var FormCheck = [];
var sErrorMessage = '';
/*
 * Initialize form check: add event handler
 * form = id of the form (<form id="")
 * error = id of the global error message (<div id="")
 */
initFormCheck = function(form,error) {
   FormCheck.form = document.getElementById(form) ? document.getElementById(form) : form;
   FormCheck.error = document.getElementById(error) ? document.getElementById(error) : error;
   var el = FormCheck.form.getElementsByTagName("*");
   for (var i=0;i<el.length;i++) {
      if (el[i].className && el[i].className.match("checkform")) {
         el[i].onsubmit = validateAll;
      }
      if (el[i].className && (el[i].className.match("require") || el[i].className.match("num")) && !el[i].className.match("nocheck")) {
         el[i].onblur = validate;
         //el[i].onchange = validate;
      }
      if (el[i].type == "radio" || "checkbox") {
         if(!el[i].className.match("nocheck")) {
            el[i].onblur = function() {
               validate.call(this);
               return true; 
           };
         }
      }
   }
}
/*
 * Initializes form check for additional form part (activated by checkbox)
 * switcher = id of the switching checkbox (needs the state)
 * optionalpart = additional part to be or not to be displayed
 * form = id of the form (<form id="")
 * error = id of the global error message (<div id="")
 */
initOptionalCheck = function(switcher, optionalpart, form, error) {
   if(document.getElementById(form) && document.getElementById(optionalpart) && document.getElementById(error)) {
      if(switcher.checked) {
         document.getElementById(optionalpart).style.display= "block";
      } else {
         document.getElementById(optionalpart).style.display= "none";
      }
      var el = FormCheck.form.getElementsByTagName("*");
      for (var i=0;i<el.length;i++) {
         if (el[i].className && el[i].className.match("optional")) {
            if(switcher.checked) {
               el[i].onblur = validate;
            } else {
               el[i].onblur = dummy;
            }
         }
      }
   }
}
/*
 * no validation; must overwrite eventhandler
 */
dummy = function() {
   //no validation; must overwrite eventhandler
   return true;
}
/*
 * validates all input fields of the form
 */
validateAll =  function() {
   var result = "";
   var el = FormCheck.form.getElementsByTagName("*");
   for (var i=0;i<el.length;i++) {
      
   if (el[i].className && el[i].className.match("require")) {
         result += this.validate(el[i]);
      }
      if(document.getElementById("optionalswitch") && document.getElementById("optionalswitch").checked) {
         if (el[i].className && el[i].className.match("optional")) {
            result += this.validate(el[i]);
         }
      }
   }
    if (result.indexOf('false') > -1) {
        return false;
    }
    return true;
}


/*
 * validates one input field and returns true|false
 * obj = input object
 */
validate = function(obj) {
   var errorBackground = "3px solid #0F94E3";
   var defaultBackground = "0px solid #666";
   var loader = (typeof(this.nodeName)=='undefined') ? obj : this;
   var passok = true;
   var isOptional = false;
   var classItem = loader.className.split(' ');
   
    //blur function moved here
    if(loader.value == "") {
        loader.value = loader.title;
    }
   
   //optional: reset default background
   if (loader.parentNode!=null && loader.parentNode.className!="form-submit") {
	if (loader.className.indexOf("require") > -1) {
          loader.style.outline = defaultBackground;
	}
   }
   for (var i=0; i<classItem.length; i++) {
      if(classItem[i]=="empty") isOptional= true;
   }
   if(isOptional && loader.value=="") return true;
   
   for (var i=0; i<classItem.length; i++) {
      switch (classItem[i]) {
         case "notempty" :
            passok = passok && (loader.value != "" && loader.value != loader.title);
			if(!passok) { sErrorMessage=sErrorMessage + loader.getAttribute('alt') + ' darf nicht leer sein.\n'; }
            break;
         case "email" :
            passok = passok && (loader.value.match(/^[\w\.\-\,\+]+@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/)!=null);
            break;
         case "num" :
            passok = passok && (loader.value.match(/^\d+$/)!=null || loader.value==loader.title || loader.value == '');
			if(!passok) { sErrorMessage=sErrorMessage + loader.alt + ' muss numerisch sein.\n'; }
            break;
         case "agree" :
            passok = passok && loader.checked;
			if(!passok) { sErrorMessage=sErrorMessage + 'Den Bedingungen muss zugestimmt werden.\n'; }
            break;
         case "radio" :
         case "checkbox" :
            passok = passok && checkRadio.call(loader);
            break;
         case "password" :
            passok = passok && checkPassword.call(loader);
            break;
         case "nospace" :
	         passok = passok && (loader.value.indexOf(" ")<0);
	         break;
         default :
            //no validation
            break;
      }
   }
   if (passok != true) {
      displayWarning.call(loader,"block");
      //optional: set error background
      //loader.style.border = errorBackground;
      loader.style.outline = errorBackground;
      
   } else {
      displayWarning.call(loader,"none");
      loader.style.outline = defaultBackground;
   }
   return passok;
}
/*
 * function to submit the form
 */
formCheckSubmit = function(TEHForm) {
   displayWarning("none",FormCheck.error);
   sErrorMessage = '';
   if (validateAll()) {
		//clear fields
		var el = document.forms[TEHForm].getElementsByTagName("input");
	    for (var i=0;i<el.length;i++) {
        	if (el[i].title == el[i].value) {
				el[i].value='';
			}
		}

		//submit form
      	document.forms[TEHForm].submit();
   } else {
   	  alert(sErrorMessage);
      displayWarning("block",FormCheck.error);
   }
}
/*
 * check a radio button
 */
checkRadio = function() {
   var el = FormCheck.form.getElementsByTagName("input");
   for (var i=0;i<el.length;i++) {
      if (el[i].name == this.name && el[i].checked) {
         return true;
      }
   }
   return false;
}
/*
 * check all password fields to be equal (className password and classNames must be equal)
 */
checkPassword = function() {
   var el = FormCheck.form.getElementsByTagName("input");
   for (var i=0;i<el.length;i++) {
      if (el[i].type==this.type && el[i].className==this.className) {
         if (el[i].value=="" || this.value=="" || el[i].value!=this.value) {
            el[i].style.outline = "1px solid #666";
            return false;
         } else {
            el[i].style.outline = "1px solid #fff";
         }
      }
   }
   return true;
}
/*
 * displays a warning for each field (must have the same parent as the object)
 */
displayWarning = function(state, obj) {
   if (obj) {
      obj.style.display = state;
   } else {
      if (this.parentNode.childNodes.length != 0) {
         for (var i=0;i<this.parentNode.childNodes.length;i++) {
            if (this.parentNode.childNodes[i].className && this.parentNode.childNodes[i].className.match("warning")) {
		 this.parentNode.childNodes[i].style.display = state;
            }
         }   
      }
   }
}


