/*
 * Inline Form Validation Engine 1.3.9, jQuery plugin
 * 
 * Copyright(c) 2009, Cedric Dugas
 * http://www.position-relative.net
 *	
 * Form validation engine which allow custom regex rules to be added.
 * Licenced under the MIT Licence
 */

jQuery(document).ready(function() {

	// SUCCESS AJAX CALL, replace "success: false," by:     success : function() { callSuccessFunction() }, 
	jQuery("[class^=validate]").validationEngine({
		success :  false,
		failure : function() {}
	})
	jQuery.validationEngine.intercept = false
	//jQuery.validationEngine.buildPrompt("#date","This is an example","error")	 		 // Exterior prompt build example
	//jQuery.validationEngine.closePrompt(".date") 										 // Exterior prompt close example
});
(function(jQuery) {
	jQuery.fn.validationEngine = function(settings) {

	if(jQuery.validationEngineLanguage){					// IS THERE A LANGUAGE LOCALISATION ?
		allRules = jQuery.validationEngineLanguage.allRules
	}else{
		allRules = {"required":{    			  // Add your regex rules here, you can take telephone as an example
							"regex":"/^[a-z][-a-z0-9_ ]{0,49}$/i",
							"alertText":"* This field is required",
							"alertTextCheckboxMultiple":"* Please select an option",
							"alertTextCheckboxe":"* This checkbox is required"},
 						"length":{
							"regex":"none",
							"alertText":"*Between ",
							"alertText2":" and ",
							"alertText3": " characters allowed"},
						"minValue":{
							"regex":"none",
							"alertText":"min value required $"
							 },	
						"maxValue":{
							"regex":"none",
							"alertText":"max value for field is $"
							 },
						"maxPerValue":{
							"regex":"none",
							"alertText":"max value for field is  "
							 },	 
						"minCheckbox":{
							"regex":"none",
							"alertText":"* Checks allowed Exceeded"},	
						"confirm":{
							"regex":"none",
							"alertText":"* Your field is not matching"},
						"captcha":{
							"regex":"none",
							"alertText":"* Please Enter valid security code"},
						"telephone":{
							"regex":"/^[0-9\-\(\)\]+$/",
							"alertText":"* Invalid phone number"},
						"alphanumeric":{
							"regex":" /^[a-zA-Z0-9]+$/",
							"alertText":"* Please enter valid text (only alphabet and number is allowed)"},
						"notfirstspace":{
							"regex":"/^[a-z][-a-z0-9_ ]{0,49}$/i",
							"alertText":"* First character must not a  space."},
						"email":{
							"regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
							"alertText":"* Invalid email address"},	
						"date":{
                             "regex":"/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/",
                             "alertText":"* Invalid date, must be in YYYY-MM-DD format"},
						"onlyNumber":{
							"regex":"/^[0-9\]+$/",
							"alertText":"* Numbers only"},	
						"onlyNumeric":{
							"regex":"/^[0-9.\]+$/",
 							"alertText":"* Numeric Value only i.e(10000.00)"},	
						"noSpecialCaracters":{
							"regex":"/^[0-9a-zA-Z ]+$/",
							"alertText":"* No special characters allowed"},	
						"ajaxUser":{
							"file":"validateUser.php",
							"alertTextOk":"* This Username is available",	
							"alertTextLoad":"* Loading, please wait",
							"alertText":"* This Username is already taken"},
						"ajaxBetacode":{
							"file":"betacode.php",
							"alertTextOk":"* This is valid code",	
							"alertTextLoad":"* Loading, please wait",
							"alertText":"* This is invalid code"},
						"ajaxEmail":{
							"file":"validateemail.php",
							"alertTextOk":"* This Email is available",	
							"alertTextLoad":"* Loading, please wait",
							"alertText":"* This Email is already taken"},	
						"ajaxName":{
							"file":"validateUser.php",
							"alertText":"* This name is already taken",
							"alertTextOk":"* This name is available",	
							"alertTextLoad":"* Loading, please wait"},
						"ajaxRestName":{
							"file":"check_restname.php",
							"alertText":"* This Restaurant name is already taken",
							"alertTextOk":"* This Restaurant is available",	
							"alertTextLoad":"* Loading, please wait"},
						
						
						
						"onlyLetter":{
							"regex":"/^[a-zA-Z\ \']+$/",
							"alertText":"* Letters only"}
					}	
	}

 	settings = jQuery.extend({
		allrules:allRules,
		inlineValidation: true,
		success : false,
		failure : function() {}
	}, settings);	
	jQuery.validationEngine.settings= settings
	
	jQuery.validationEngine.ajaxValidArray = new Array()


	jQuery("form").bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
		jQuery.validationEngine.onSubmitValid = true;
		
		if(jQuery.validationEngine.submitValidation(this) == false){
		 // submitForm()
			
		}else{
			settings.failure && settings.failure(); 
			return false;
		}		
	})
	
	if(settings.inlineValidation == true){ 		// Validating Inline ?
		
		jQuery(this).not("[type=checkbox]").bind("blur", function(caller){	_inlinEvent(this)   })
		//jQuery(this+"[type=checkbox]").bind("click", function(caller){		_inlinEvent(this)   })
		
			function _inlinEvent(caller){
				if(jQuery.validationEngine.intercept == false){		// STOP INLINE VALIDATION THIS TIME ONLY
					jQuery.validationEngine.onSubmitValid=false;
					jQuery.validationEngine.loadValidation(caller); 
				}else{
					jQuery.validationEngine.intercept = false;
				}
			}
	}
};	
jQuery.validationEngine = {
	submitForm : function(){
		if (settings.success){
			settings.success && settings.success(); 
			return false;
		}
	},
	buildPrompt : function(caller,promptText,type,ajaxed) {			// ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR
		var divFormError = document.createElement('div')
		var formErrorContent = document.createElement('div')
		
		jQuery(divFormError).addClass("formError")
		if(type == "pass"){
			jQuery(divFormError).addClass("greenPopup")
		}
		if(type == "load"){
			jQuery(divFormError).addClass("blackPopup")
		}
		if(ajaxed){
			jQuery(divFormError).addClass("ajaxed")
		}
		jQuery(divFormError).addClass(jQuery(caller).attr("id"))
		jQuery(formErrorContent).addClass("formErrorContent")
		
		jQuery("body").append(divFormError)
		jQuery(divFormError).append(formErrorContent)
			
		if(jQuery.validationEngine.showTriangle != false){		// NO TRIANGLE ON MAX CHECKBOX AND RADIO
			var arrow = document.createElement('div')
			jQuery(arrow).addClass("formErrorArrow")
			jQuery(divFormError).append(arrow)
			jQuery(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>');
		}
		
		jQuery(formErrorContent).html(promptText)
	
		callerTopPosition = jQuery(caller).offset().top;
		callerleftPosition = jQuery(caller).offset().left-10;
 		callerWidth =  jQuery(caller).width()
		callerHeight =  jQuery(caller).height()
		inputHeight = jQuery(divFormError).height()

		 
		//callerleftPosition = callerleftPosition +100
		callerleftPosition = callerleftPosition + callerWidth -30
		callerTopPosition = callerTopPosition  -inputHeight -10
		 
		jQuery(divFormError).css({
			top:callerTopPosition,
			left:callerleftPosition,
			opacity:0
		})
		return jQuery(divFormError).animate({"opacity":0.87},function(){return true;});	
	},
	updatePromptText : function(caller,promptText,type,ajaxed) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED
		updateThisPrompt =  jQuery(caller).attr("id")
		updateThisPrompt = "."+updateThisPrompt
		
		if(type == "pass"){
			jQuery(updateThisPrompt).addClass("greenPopup")
		}else{
			jQuery(updateThisPrompt).removeClass("greenPopup")
		}
		if(type == "load"){
			jQuery(updateThisPrompt).addClass("blackPopup")
		}else{
			jQuery(updateThisPrompt).removeClass("blackPopup")
		}
		if(ajaxed){
			jQuery(updateThisPrompt).addClass("ajaxed")
		}else{
			jQuery(updateThisPrompt).removeClass("ajaxed")
		}
		jQuery(updateThisPrompt).find(".formErrorContent").html(promptText)
		callerTopPosition  = jQuery(caller).offset().top;
		inputHeight = jQuery(updateThisPrompt).height()
		
		callerTopPosition = callerTopPosition  -inputHeight -10
		jQuery(updateThisPrompt).animate({
			top:callerTopPosition
		});
	},
	loadValidation : function(caller) {		// GET VALIDATIONS TO BE EXECUTED
		
		rulesParsing = jQuery(caller).attr('class');
		rulesRegExp = /\[(.*)\]/;
		getRules = rulesRegExp.exec(rulesParsing);
		str = getRules[1]
		pattern = /\W+/;
		result= str.split(pattern);	
	
		var validateCalll = jQuery.validationEngine.validateCall(caller,result)
		return validateCalll
	},
	validateCall : function(caller,rules) {	// EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD
		var promptText =""	
		var prompt = jQuery(caller).attr("id");
		var caller = caller;
		ajaxValidate = false
		var callerName = jQuery(caller).attr("name");
		jQuery.validationEngine.isError = false;
		jQuery.validationEngine.showTriangle = true
		callerType = jQuery(caller).attr("type");
		
		for (i=0; i<rules.length;i++){
			switch (rules[i]){
			case "optional": 
				if(!jQuery(caller).val()){
					jQuery.validationEngine.closePrompt(caller)
					return jQuery.validationEngine.isError
				}
			break;
			case "required": 
				_required(caller,rules);
			break;
			case "custom": 
				 _customRegex(caller,rules,i);
			break;
			case "ajax": 
				if(!jQuery.validationEngine.onSubmitValid){
					_ajax(caller,rules,i);	
				}
			break;
			case "length": 
				 _length(caller,rules,i);
			break;
			case "minValue": 
				 _minValue(caller,rules,i);
			break;
			case "maxValue": 
				 _maxValue(caller,rules,i);
			break;
			case "maxPerValue": 
				 _maxPerValue(caller,rules,i);
			break;
			/*case "minCheckbox": 
				 _minCheckbox(caller,rules,i);
			break;*/
			case "confirm": 
				 _confirm(caller,rules,i);
			break;
			case "captcha": 
				 _captcha(caller,rules,i);
			break;
			
			default :;
			};
		};
		if (jQuery.validationEngine.isError == true){
			
			radioHackOpen();
			if (jQuery.validationEngine.isError == true){ // show only one
				(jQuery("div."+prompt).size() ==0) ? jQuery.validationEngine.buildPrompt(caller,promptText,"error")	: jQuery.validationEngine.updatePromptText(caller,promptText);
			}
		}else{
			radioHackClose();
			jQuery.validationEngine.closePrompt(caller);
		}		
		/* UNFORTUNATE RADIO AND CHECKBOX GROUP HACKS */
		/* As my validation is looping input with id's we need a hack for my validation to understand to group these inputs */
		function radioHackOpen(){
			if(jQuery("input[name="+callerName+"]").size()> 1 && callerType == "radio") {		// Hack for radio group button, the validation go the first radio
				caller = jQuery("input[name="+callerName+"]:first");
				jQuery.validationEngine.showTriangle = false;
				var callerId ="."+ jQuery(caller).attr("id");
				if(jQuery(callerId).size()==0){ jQuery.validationEngine.isError = true; }else{ jQuery.validationEngine.isError = false;}
			}
			if(jQuery("input[name="+callerName+"]").size()> 1 && callerType == "checkbox") {		// Hack for checkbox group button, the validation go the first radio
				caller = jQuery("input[name="+callerName+"]:first");
				jQuery.validationEngine.showTriangle = false;
				var callerId ="div."+ jQuery(caller).attr("id");
				if(jQuery(callerId).size()==0){ jQuery.validationEngine.isError = true; }else{ jQuery.validationEngine.isError = false;}
			}
		}
		function radioHackClose(){
			if(jQuery("input[name="+callerName+"]").size()> 1 && callerType == "radio") {		// Hack for radio group button, the validation go the first radio
				caller = jQuery("input[name="+callerName+"]:first");
			}
			if(jQuery("input[name="+callerName+"]").size()> 1 && callerType == "checkbox") {		// Hack for checkbox group button, the validation go the first radio
				caller = jQuery("input[name="+callerName+"]:first");
			}
		}
		/* VALIDATION FUNCTIONS */
		function _required(caller,rules){   // VALIDATE BLANK FIELD
			callerType = jQuery(caller).attr("type");
			if (callerType == "text" || callerType == "password" || callerType == "textarea"){
								
				if(!jQuery(caller).val()){
					jQuery.validationEngine.isError = true;
					promptText += jQuery.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}	
			}	
			if (callerType == "radio" || callerType == "checkbox" ){
				
				callerName = jQuery(caller).attr("name");
		
				if(jQuery("input[name="+callerName+"]:checked").size() == 0) {
					jQuery.validationEngine.isError = true;
					if(jQuery("input[name="+callerName+"]").size() ==1) {
						promptText += jQuery.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe+"<br />"; 
					}else{
						 promptText += jQuery.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple+"<br />";
					}	
				}
			}	
			if (callerType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you
					callerName = jQuery(caller).attr("id");
				
				if(!jQuery("select[name="+callerName+"]").val()) {
					jQuery.validationEngine.isError = true;
					promptText += jQuery.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
			if (callerType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you
					callerName = jQuery(caller).attr("id");
				
				if(!jQuery("#"+callerName).val()) {
					jQuery.validationEngine.isError = true;
					promptText += jQuery.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
		}
		function _customRegex(caller,rules,position){		 // VALIDATE REGEX RULES
			customRule = rules[position+1];
			pattern = eval(jQuery.validationEngine.settings.allrules[customRule].regex);
			
			if(!pattern.test(jQuery(caller).attr('value'))){
				jQuery.validationEngine.isError = true;
				promptText += jQuery.validationEngine.settings.allrules[customRule].alertText+"<br />";
			}
		}
		function _ajax(caller,rules,position){				 // VALIDATE AJAX RULES
			
			customAjaxRule = rules[position+1];
			postfile = jQuery.validationEngine.settings.allrules[customAjaxRule].file;
			fieldValue = jQuery(caller).val();
			ajaxCaller = caller;
			fieldId = jQuery(caller).attr("id");
			ajaxValidate = true;
			ajaxisError = jQuery.validationEngine.isError;
			
			/* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */	
			if(!ajaxisError){
				jQuery.ajax({
				   	type: "POST",
				   	url: postfile,
				   	async: true,
				   	data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule,
				   	beforeSend: function(){		// BUILD A LOADING PROMPT IF LOAD TEXT EXIST		   			
				   		if(jQuery.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){
				   		
				   			if(!jQuery("div."+fieldId)[0]){				   				
	 			 				return jQuery.validationEngine.buildPrompt(ajaxCaller,jQuery.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
	 			 			}else{
	 			 				jQuery.validationEngine.updatePromptText(ajaxCaller,jQuery.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
	 			 			}
			   			}
			  	 	},
					success: function(data){					// GET SUCCESS DATA RETURN JSON
						data = eval( "("+data+")");				// GET JSON DATA FROM PHP AND PARSE IT
						ajaxisError = data.jsonValidateReturn[2];
						customAjaxRule = data.jsonValidateReturn[1];
						ajaxCaller = jQuery("#"+data.jsonValidateReturn[0])[0];
						fieldId = ajaxCaller;
						ajaxErrorLength = jQuery.validationEngine.ajaxValidArray.length
						existInarray = false;
						
			 			 if(ajaxisError == "false"){			// DATA FALSE UPDATE PROMPT WITH ERROR;
			 			 	
			 			 	_checkInArray(false)				// Check if ajax validation alreay used on this field
			 			 	
			 			 	if(!existInarray){		 			// Add ajax error to stop submit		 		
				 			 	jQuery.validationEngine.ajaxValidArray[ajaxErrorLength] =  new Array(2)
				 			 	jQuery.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId
				 			 	jQuery.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false
				 			 	existInarray = false;
			 			 	}
				
			 			 	jQuery.validationEngine.ajaxValid = false;
							promptText += jQuery.validationEngine.settings.allrules[customAjaxRule].alertText+"<br />";
							jQuery.validationEngine.updatePromptText(ajaxCaller,promptText,"",true);				
						 }else{	 
						 	_checkInArray(true)
					
						 	jQuery.validationEngine.ajaxValid = true; 						   
	 			 			if(jQuery.validationEngine.settings.allrules[customAjaxRule].alertTextOk){	// NO OK TEXT MEAN CLOSE PROMPT	 			
	 			 				 				jQuery.validationEngine.updatePromptText(ajaxCaller,jQuery.validationEngine.settings.allrules[customAjaxRule].alertTextOk,"pass",true);
 			 				}else{
				 			 	ajaxValidate = false;		 	
				 			 	jQuery.validationEngine.closePrompt(ajaxCaller);
 			 				}		
			 			 }
				 			function  _checkInArray(validate){
				 				for(x=0;x<ajaxErrorLength;x++){
				 			 		if(jQuery.validationEngine.ajaxValidArray[x][0] == fieldId){
				 			 			jQuery.validationEngine.ajaxValidArray[x][1] = validate
				 			 			existInarray = true;
				 			 		
				 			 		}
				 			 	}
				 			}
			 		}				
				});
			}
		}
		function _confirm(caller,rules,position){		 // VALIDATE FIELD MATCH
			confirmField = rules[position+1];
			
			if(jQuery(caller).attr('value') != jQuery("#"+confirmField).attr('value')){
				jQuery.validationEngine.isError = true;
				promptText += jQuery.validationEngine.settings.allrules["confirm"].alertText+"<br />";
			}
		}
		function _captcha(caller,rules,position){		 // VALIDATE FIELD MATCH
			captchaField = rules[position+1];
			
			if(jQuery(caller).attr('value') != jQuery("#"+captchaField).attr('value')){
				jQuery.validationEngine.isError = true;
				promptText += jQuery.validationEngine.settings.allrules["captcha"].alertText+"<br />";
			}
		}
		function _length(caller,rules,position){    	  // VALIDATE LENGTH
		
			startLength = eval(rules[position+1]);
			endLength = eval(rules[position+2]);
			feildLength = jQuery(caller).attr('value').length;

			if(feildLength<startLength || feildLength>endLength){
				jQuery.validationEngine.isError = true;
				promptText += jQuery.validationEngine.settings.allrules["length"].alertText+startLength+jQuery.validationEngine.settings.allrules["length"].alertText2+endLength+jQuery.validationEngine.settings.allrules["length"].alertText3+"<br />"
			}
		}
		function _minValue(caller,rules,position){    	  // VALIDATE LENGTH
		
 			confirmField = rules[position+1];
			if(confirmField=='')
			confirmField=0;
			var atbValue=jQuery(caller).attr('value');
			if(atbValue.indexOf("$")!=-1)
			atbValue=atbValue.replace("$","");
  			if(!isNaN(atbValue)){
			feildLength = eval(atbValue);
    		}
			else
			feildLength = atbValue;
			if(feildLength<confirmField ){ 
				jQuery.validationEngine.isError = true;
 				promptText += jQuery.validationEngine.settings.allrules["minValue"].alertText+confirmField+"<br />"
 			}
			
		}
		function _maxValue(caller,rules,position){    	  // VALIDATE LENGTH
		
 			confirmField = rules[position+1];
 			
			var atbValue=jQuery(caller).attr('value');
			if(atbValue.indexOf("$")!=-1)
			atbValue=atbValue.replace("$","");
			if(!isNaN(atbValue)){
			feildLength = eval(atbValue);
    		}else
			feildLength = atbValue;
			if(feildLength>confirmField ){
			jQuery.validationEngine.isError = true;
			promptText += jQuery.validationEngine.settings.allrules["maxValue"].alertText+confirmField+"<br />"
			}
		}
		function _maxPerValue(caller,rules,position){    	  // VALIDATE LENGTH
		
 			confirmField = rules[position+1];
 			
			var atbValue=jQuery(caller).attr('value');
			if(atbValue.indexOf("$")!=-1)
			atbValue=atbValue.replace("$","");
			if(!isNaN(atbValue)){
			feildLength = eval(atbValue);
    		}else
			feildLength = atbValue;
			if(feildLength>confirmField ){
			jQuery.validationEngine.isError = true;
			promptText += jQuery.validationEngine.settings.allrules["maxPerValue"].alertText+confirmField+"%<br />"
			}
		}
		function _minCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			nbCheck = eval(rules[position+1]);
			groupname = jQuery(caller).attr("name");
			groupSize = jQuery("input[name="+groupname+"]:checked").size();
			
			if(groupSize > nbCheck){	
				jQuery.validationEngine.isError = true;
				promptText += jQuery.validationEngine.settings.allrules["minCheckbox"].alertText+"<br />";
			}
		}
		return(jQuery.validationEngine.isError) ? jQuery.validationEngine.isError : false;
	},
	closePrompt : function(caller,outside) {						// CLOSE PROMPT WHEN ERROR CORRECTED
		if(outside){
			jQuery(caller).fadeTo("fast",0,function(){
				jQuery(caller).remove();
			});
			return false;
		}
		
		if(!ajaxValidate){
			closingPrompt = jQuery(caller).attr("id");
	
			jQuery("."+closingPrompt).fadeTo("fast",0,function(){
				jQuery("."+closingPrompt).remove();
			});
		}
	},
	submitValidation : function(caller) {					// FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
		var stopForm = false;
		jQuery.validationEngine.ajaxValid = true
		jQuery(caller).find(".formError").remove();
		var toValidateSize = jQuery(caller).find("[class^=validate]").size();
		
		jQuery(caller).find("[class^=validate]").each(function(){
			callerId = jQuery(this).attr("id")
			if(!jQuery("."+callerId).hasClass("ajaxed")){	// DO NOT UPDATE ALREADY AJAXED FIELDS (only happen is no normal errors, don't worry)
				var validationPass = jQuery.validationEngine.loadValidation(this);
				return(validationPass) ? stopForm = true : "";					
			}
		});
		
		ajaxErrorLength = jQuery.validationEngine.ajaxValidArray.length		// LOOK IF SOME AJAX IS NOT VALIDATE
		for(x=0;x<ajaxErrorLength;x++){
	 		if(jQuery.validationEngine.ajaxValidArray[x][1] == false){
	 			jQuery.validationEngine.ajaxValid = false
	 		}
	 	}
		
		
		if(stopForm || !jQuery.validationEngine.ajaxValid){		// GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
			destination = jQuery(".formError:not('.greenPopup'):first").offset().top;
			jQuery("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100);
			return true;
		}else{
			return false
		}
	}
}	
})(jQuery);
