/*
 * Inline Form Validation Engine, jQuery plugin
 * 
 * Copyright(c) 2009, Cedric Dugas
 * http://www.position-relative.net
 *	
 * Form validation engine witch allow custom regex rules to be added.
 * Licenced under the MIT Licence
 */

$(document).ready(function() {

	// SUCCESS AJAX CALL, replace "success: false," by:     success : function() { callSuccessFunction() }, 
	$("[class^=validate]").validationEngine({
		success :  false,
		failure : function() {}
	})
});

function CValidate() {
	// Local variables
	var allRules = {"required":{
                                                "regex":"none",
                                                "alertText":"* Dies ist ein Pflichtfeld",
                                                "alertTextCheckboxMultiple":"* Triff eine Auswahl",
                                                "alertTextCheckboxe":"* Dies ist ein Pflichtfeld"},
                                        "length":{
                                                "regex":"none",
                                                "alertText":"* Zwischen ",
                                                "alertText2":" und ",
                                                "alertText3":" Zeichen sind erlaubt"},
                                        "minCheckbox":{
                                                "regex":"none",
                                                "alertText":"* Zu viele Felder ausgew&auml;hlt"},
                                        "confirm":{
                                                "regex":"none",
                                                "alertText":"* Die Eingaben sind nicht identisch"},
                                        "telephone":{
                                                "regex":"/^[0-9\-\(\)\ ]+$/",
                                                "alertText":"* Die Telefonnummer ist invalid"},
                                        "email":{
                                                "regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
                                                "alertText":"* Die E-Mail-Adresse ist invalid"},
                                        "date":{
                         "regex":"/^[0-9]{1,2}\-\[0-9]{1,2}\-\[0-9]{4}$/",
                         "alertText":"* Datum invalid, Format: TT-MM-JJJJ"},
                                        "onlyNumber":{
                                                "regex":"/^[0-9\ ]+$/",
                                                "alertText":"* Nur Zahlen erlaubt"},
                                        "noSpecialCaracters":{
                                                "regex":"/^[0-9a-zA-Z]+$/",
                                                "alertText":"* Keine Sonderzeichen erlaubt"},
                                        "onlyLetter":{
                                                "regex":"/^[a-zA-Z\ öüäß\']+$/",
                                                "alertText":"* Nur Buchstaben erlaubt"}
                                };

	var settings = {
		success :  false,
		failure : function() {}
	};
			
	settings = jQuery.extend({
		allrules:allRules,
		success : false,
		failure : function() {}
	}, settings);

	
	/**
	* Function to build the prompt
	*/
	var buildPrompt = function(caller,promptText) {
		// Create the elements
		var divFormError = document.createElement('div')
		var formErrorContent = document.createElement('div')
		var arrow = document.createElement('div')
		// Assign classes		
		$(divFormError).addClass("formError")
		$(divFormError).addClass($(caller).attr("name"))
		$(formErrorContent).addClass("formErrorContent")
		$(arrow).addClass("formErrorArrow")
		// Append new content
		$("body").append(divFormError)
		$(divFormError).append(arrow)
		$(divFormError).append(formErrorContent)
		$(arrow).html('<div class="line10"></div><div class="line9"></div><div class="line8"></div><div class="line7"></div><div class="line6"></div><div class="line5"></div><div class="line4"></div><div class="line3"></div><div class="line2"></div><div class="line1"></div>')
		$(formErrorContent).html(promptText)
		// Set position
		callerTopPosition = $(caller).offset().top;
		callerleftPosition = $(caller).offset().left;
		callerWidth =  $(caller).width()
		callerHeight =  $(caller).height()
		inputHeight = $(divFormError).height()
		callerleftPosition = callerleftPosition + callerWidth -30
		callerTopPosition = callerTopPosition  -inputHeight -10
		// Set position
		$(divFormError).css({
			top:callerTopPosition,
			left:callerleftPosition,
			opacity:0
		})
		// Show prompt
		$(divFormError).fadeTo("fast",0.8);
	};
	
	/**
	* Updates the text error if an error is already displayed
	*/
	var updatePromptText = function(caller,promptText) {
		// Get the prompt
		updateThisPrompt =  $(caller).attr("name")
		// Update
		$("."+updateThisPrompt).find(".formErrorContent").html(promptText)
		
		callerTopPosition  = $(caller).offset().top;
		inputHeight = $("."+updateThisPrompt).height()
		// Update position
		callerTopPosition = callerTopPosition  -inputHeight -10
		$("."+updateThisPrompt).animate({
			top:callerTopPosition
		});
	}
	
	/**
	* Gets the validations to be executed
	*/
	this.loadValidation = function(caller) {
		
		rulesParsing = $(caller).attr('class');
		rulesRegExp = /\[(.*)\]/;
		getRules = rulesRegExp.exec(rulesParsing);
		str = getRules[1]
		pattern = /\W+/;
		result= str.split(pattern);	
		
		var validateCalll = validateCall(caller,result)
		return validateCalll
		
	};
	
	/**
	* Gets the validations to be executed
	*/
	var loadValidation = function(caller) {
		
		rulesParsing = $(caller).attr('class');
		rulesRegExp = /\[(.*)\]/;
		getRules = rulesRegExp.exec(rulesParsing);
		str = getRules[1]
		pattern = /\W+/;
		result= str.split(pattern);	
		
		var validateCalll = validateCall(caller,result)
		return validateCalll
		
	};
	
	var closePrompt = function(caller) {	// CLOSE PROMPT WHEN ERROR CORRECTED
		closingPrompt = $(caller).attr("name")

		$("."+closingPrompt).fadeTo("fast",0,function(){
			$("."+closingPrompt).remove()
		});
	};
	
	this.submitValidation = function(caller) {	// FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
		var stopForm = false
		$(caller).find(".formError").remove()
		var toValidateSize = $(caller).find("[class^=validate]").size()
		
		$(caller).find("[class^=validate]").each(function(){
			var validationPass = loadValidation(this)
			return(validationPass) ? stopForm = true : "";	
		});
		if(stopForm){							// GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
			destination = $(".formError:first").offset().top;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100)
			return true;
		}else{
			return false
		}
	};
	
	/**
	* Execute validation required by the user for this field
	*/
	var validateCall = function(caller,rules) {
		var promptText =""	
		var prompt = $(caller).attr("name");
		var caller = caller;
		isError = false;
		callerType = $(caller).attr("type");
		
		for (i=0; i<rules.length;i++){
			switch (rules[i]){
			case "optional": 
				if(!$(caller).val()){
					closePrompt(caller)
					return isError
				}
			break;
			case "required": 
				_required(caller,rules);
			break;
			case "custom": 
				 _customRegex(caller,rules,i);
			break;
			case "length": 
				 _length(caller,rules,i);
			break;
			case "minCheckbox": 
				 _minCheckbox(caller,rules,i);
			break;
			case "confirm": 
				 _confirm(caller,rules,i);
			break;
			default :;
			};
		};
		if (isError == true){
			
			if($("input[name="+prompt+"]").size()> 1 && callerType == "radio") {		// Hack for radio group button, the validation go the first radio
				caller = $("input[name="+prompt+"]:first")
			}
			($("."+prompt).size() ==0) ? buildPrompt(caller,promptText)	: updatePromptText(caller,promptText)
		}else{
			closePrompt(caller)
		}
		
		function _required(caller,rules){   // VALIDATE BLANK FIELD
			callerType = $(caller).attr("type")
			
			if (callerType == "text" || callerType == "password" || callerType == "textarea"){
				
				if(!$(caller).val()){
					isError = true
					promptText += settings.allrules[rules[i]].alertText+"<br />"
				}	
			}
			if (callerType == "radio" || callerType == "checkbox" ){
				callerName = $(caller).attr("name")
		
				if($("input[name="+callerName+"]:checked").size() == 0) {
					isError = true
					if($("input[name="+callerName+"]").size() ==1) {
						promptText += settings.allrules[rules[i]].alertTextCheckboxe+"<br />" 
					}else{
						 promptText += settings.allrules[rules[i]].alertTextCheckboxMultiple+"<br />"
					}	
				}
			}	
			if (callerType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you
					callerName = $(caller).attr("name");
				
				if(!$("select[name="+callerName+"]").val()) {
					isError = true;
					promptText += settings.allrules[rules[i]].alertText+"<br />";
				}
			}
			if (callerType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you
					callerName = $(caller).attr("id");
				
				if(!$("#"+callerName).val()) {
					isError = true;
					promptText += settings.allrules[rules[i]].alertText+"<br />";
				}
			}
		}
		
		/* VALIDATION FUNCTIONS */
		
		function _customRegex(caller,rules,position){		 // VALIDATE REGEX RULES
			customRule = rules[position+1]
			pattern = eval(settings.allrules[customRule].regex)
			
			if(!pattern.test($(caller).attr('value'))){
				isError = true
				promptText += settings.allrules[customRule].alertText+"<br />"
			}
		}
		function _confirm(caller,rules,position){		 // VALIDATE FIELD MATCH
			confirmField = rules[position+1]
			
			if($(caller).attr('value') != $("#"+confirmField).attr('value')){
				isError = true
				promptText += settings.allrules["confirm"].alertText+"<br />"
			}
		}
		function _length(caller,rules,position){    // VALIDATE LENGTH
		
			startLength = eval(rules[position+1])
			endLength = eval(rules[position+2])
			feildLength = $(caller).attr('value').length

			if(feildLength<startLength || feildLength>endLength){
				isError = true
				promptText += settings.allrules["length"].alertText+startLength+settings.allrules["length"].alertText2+endLength+settings.allrules["length"].alertText3+"<br />"
			}
		}
		function _minCheckbox(caller,rules,position){    // VALIDATE CHECKBOX NUMBER
		
			nbCheck = eval(rules[position+1])
			groupname = $(caller).attr("name")
			groupSize = $("input[name="+groupname+"]:checked").size()
			
			if(groupSize > nbCheck){	
				isError = true
				promptText += settings.allrules["minCheckbox"].alertText+"<br />"
			}
		}

		return(isError) ? isError : false;
	};
}

jQuery.fn.validationEngine = function(settings) {
	// Create validation object
	var objValidation = new CValidate();
	// Handle non-checkboxes with onblur
	$(this).not("[type=checkbox]").bind("blur", function(caller){objValidation.loadValidation(this)});
	// Handle checkboxes with click handler
	$(this+"[type=checkbox]").bind("click", function(caller){objValidation.loadValidation(this)})
};

jQuery.fn.validateForm = function(settings) {
	// Create validation object
	var objValidation = new CValidate();
	// Validate all elements on this form
	return !objValidation.submitValidation(this);
};
