/**
 * @author: jr 
 * @date: 03.08.2009
 * Description:
 * 	Simple Form validation:
 * 	Check all members of a form which includes the class required
 *
 * 	You can add min_DIGIT oder max_DIGIT as classname. You can add an individual value for minLen
 * 	or maxLen on a single form element.
 * 	Example: <input type="text" class="required min_3 max_10"> checks if the value's length is >2 and <11
 *
 * Defaults:
 * 	stdError: 	Standard message when the form is not valid
 * 	mailError: 	Error message when the email address is not valid
 *  captError:	Error message when the Captcha-Code is not valid
 *  captcha:	Set on true if there is a Captcha in the Formular
 * 	errClass: 	The CSS-class which is added to an invalid form element and which marks the error for the user
 * 	errMsgSel:	The CSS-id of the DOM-Element which shows the error message to the user
 *	minLen:		The minimum length of the input
 *	maxLen:		The maximum length of the input
 *
 * Usage:
 * 	$("#formName").validate();
 * 	or
 * 	$("#formName").validate({minLen:4,maxLen:10}); // changed defaults values
 * 
 * Further Development:
 *  25.01.2011	Adding optional Captcha-Validation because of a new voila Version (TK) 
 */
(function($) {
   $.fn.validate = function(options) {
      var defaults = {
         stdError: 	'Please fill out the mandatory fields!',
         mailError: 'Wrong format for email-adress - e.g. mymail@myprovider.com',
         captError: 'You entered a wrong securitycode!',
         captcha: 	true,
         errClass: 	'error',
         errMsgSel: '#error',
         minLen: 	1,
         maxLen: 	10000
      };
      var opts = jQuery.extend(defaults, options);
      var isValid = true, len = 0, msg = "", min, max, tmpMin, tmpMax;
      // create onsubmit event for the form					  		
      this.submit(function() {
         isValid = true;
         if(opts.captcha==true){
        	 captValid = false;
        	 isValidCaptcha();
         };
         msg 	= 	"";
         stdErr =	false;
         $('.required', this).each(function() {
            if ($(this).is(':text,:password,textarea,select')) {
               // check text input (mail or normal text)
               if ($(this).hasClass("email")) {
                  isValidMail($(this).val()) ? clean(this) : markError(this, opts.mailError);
               } else {
                  // check if an extra min or max length as class is given						
                  tmpMin = getExtraVal($(this).attr("class"), "min_");
                  tmpMax = getExtraVal($(this).attr("class"), "max_");
                  tmpMin != "" ? min = parseInt(tmpMin) : min = opts.minLen;
                  tmpMax != "" ? max = parseInt(tmpMax) : max = opts.maxLen;
                  len = $(this).val().length;
                  if(len < min || len > max){markError(this); stdErr=true}else{clean(this)};
               }
            } else if ($(this).is(':radio,:checkbox')) {
               $(this).is(":checked") ? clean(this) : markError(this, opts.stdError);
            }
         });
         if(opts.captcha == true){
        	 if (captValid == false){
         		markError($("#captcha"), opts.captError)
        	 }
      	 };
      	 if(stdErr==true){
      		 msg += opts.stdError;
      	 };
         isValid ? cleanMsg() : showMsg();
         return isValid;
      });
      /* ************************
       * *** helper functions ***
       * ************************/
      // check if mail address is valid
      function isValidMail(email) {
         var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
         return regex.test(email);
      }
      // check if Captcha-Code is valid (must be splitted in two functions!!!)
      function isValidCaptcha() {
    		var captcha = $("#captcha").val();
    		if(captcha != "") {
    			$.ajax({
    				type: "GET",
    				async: false,
    				url:  $("#dbPfad").val()+"(web_formular_checkcaptcha)?OpenAgent",
    				data: "captcha=" + captcha,
    				success: function(msg){
    					validCapt($.trim(msg));
    				}
    			});
    		}
      }
      function validCapt(reply) {
    	  if(reply=="ERROR"){
    		  captValid = false;
    	  }else{
    		  captValid = true;
    	  }
      }
      // highlight error dom element
      function markError(domElement, addMsg) {
         isValid = false;
         addMsg ? msg += addMsg + "<br>" : "";
         $(domElement).addClass(opts.errClass);
      }
      // remove error highlighting when error is fixed
      function clean(domElement) {
         $(domElement).removeClass(opts.errClass);
      }
      // show error message
      function showMsg() {
         $(opts.errMsgSel).html(msg).show();
      }
      // hide error message
      function cleanMsg() {
         $(opts.errMsgSel).html("").hide();
      }
      // get extra val given in classname example: min_10
      function getExtraVal(classString, extra) {
         var classArr, found = false, extraClass = "";
         classArr = classString.split(" ");
         for (i = 0; i < classArr.length; i++) {
            if (classArr[i].indexOf(extra) != -1) {
               found = true;
               extraClass = classArr[i];
            }
         }
         return found ? extraClass.substr(extraClass.indexOf("_") + 1) : "";
      }
   };
})(jQuery);

