$.fn.ajaxSubmit = function(normal) {
	var variable = [];
	parametre=this.buildPOST(variable);
	if(parametre){

		if(normal!=undefined && normal!="vrai"){$('#'+normal).html("<img src='"+domaine+"/partoutil/image_gestion/indicator.gif' />");	}

		//alert("Résultat : "+parametre[0]+" \n\n"+parametre[1]+" \n\n"+parametre[2]);
		if(normal==undefined){
			$.ajax({type: 'POST', url:parametre[1], data:"xa="+parametre[2]+"&"+parametre[0],dataType:'script',success:function(msg) {}	});
		}else if(normal=="vrai"){
			return $.ajax({type: 'POST', url:parametre[1], data:"xa="+parametre[2]+"&"+parametre[0],async: false }).responseText;
			//if(retour==1){ return true; }else{  return false; }
		}else{
			$.ajax({type: 'POST', url:parametre[1], data:"xa="+parametre[2]+"&"+parametre[0],success:function(msg) {
					$('#'+normal).html(msg);
					if(normal=="contenu_popup"){
						this.cycleTimeout = 0;	this.cycleTimeout = setTimeout(function() { continu();	}, 500);
						function continu(){	$("#pseudo_popup").centerInClient({ container: window, forceAbsolute: true });	clearTimeout(this.cycleTimeout);	}
					}
				}
			});
		}
	
	}
	 return false;
}

function isdefined( variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}


$.fn.buildPOST = function(variable) { 
	var qs = '';
    var form = this[0];
    var els = form.elements;
    if (!els) return;
	
	//var allRules = allRules ? allRules : new Array();


	if(typeof(allRules) != 'undefined'){
		options = jQuery.extend({	allrules:allRules	}, allRules);
		
		var buildPrompt = function(caller,promptText,champ) {			// ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR
			var divFormError = document.createElement('div')
			var formErrorContent = document.createElement('div')
			var arrow = document.createElement('div')

			$(divFormError).addClass("formError")
			$(divFormError).addClass(champ)
		    $(formErrorContent).addClass("formErrorContent")
			$(arrow).addClass("formErrorArrow")
	
			$("body").append(divFormError)
			$(divFormError).append(arrow)
			$(divFormError).append(formErrorContent);

			minitab=false;	
			if ($(caller).parent().css('display')=="none"){
				caller= $("#a_"+caller.name);
				minitab=true;
			}

			$(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)
				
			callerTopPosition = $(caller).offset().top;
			callerleftPosition = $(caller).offset().left;
			callerWidth =  $(caller).width()
			callerHeight =  $(caller).height()
			inputHeight = $(divFormError).height()

			if((caller.type=="radio" || caller.type=="checkbox") || minitab){
				callerleftPosition = callerleftPosition + callerWidth-30;
				callerTopPosition = callerTopPosition  -inputHeight-10
			}else{
				callerleftPosition = callerleftPosition + callerWidth -100;
				callerTopPosition = callerTopPosition  -inputHeight	-5
			}
				
			$(divFormError).css({top:callerTopPosition,left:callerleftPosition,opacity:0})
			$(divFormError).fadeTo("fast",0.9);
		};

		var updatePromptText = function(caller,promptText,champ) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED
			$("."+champ).find(".formErrorContent").html(promptText)
			callerTopPosition  = $(caller).offset().top;
			inputHeight = $("."+champ).height()
			if (caller.type!="radio" && caller.type!="checkbox"){
				callerTopPosition = callerTopPosition  -inputHeight	-5
				$("."+champ).animate({	top:callerTopPosition	});
			}else{
				callerTopPosition = callerTopPosition -inputHeight-10
			}
		};
		
		var loadValidation = function(caller) {		// GET VALIDATIONS TO BE EXECUTED
			rulesParsing = $(caller).attr('class');
			rulesRegExp = /\[(.*)\]/;
			getRules = rulesRegExp.exec(rulesParsing);
			
			if(getRules){
				str = getRules[1];
				pattern = /\W+/;
				var result= str.split(pattern);	
				var validateCalll = validateCall(caller,result);
				
				if(validateCalll){
					//Permet de remonter vers l'erreur------------------------------
					//destination = $(".formError:first").offset().top;
					//$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100);
				}
				
				$(caller).blur(function() { validateCall(caller,result);  }); //Ajoute sur la perte de focus
				return validateCalll;
			}
		};
		
		var validateCall = function(caller,rules) {	// EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FILED
			var promptText =""	
			var isError = false
			var prompt = $(caller).attr("name");

			// Pour les tableau (checkbox...)
			var reg1=new RegExp("[\[\]]","g");
			if(prompt.match(reg1)){	prompt=prompt.substring(0,(prompt.length-2));}
			
			var caller = caller
			callerType = $(caller).attr("type")
			
			for (i=0; i<rules.length;i++){
				switch (rules[i]){
					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){
				($("."+prompt).size()==0) ? buildPrompt(caller,promptText,prompt)	: updatePromptText(caller,promptText,prompt);
			}else{
				closePrompt(prompt);
			}		
		
			/* VALIDATION FUNCTIONS */
			function _required(caller,rules){   // VALIDATE BLANK FIELD
				callerType = $(caller).attr("type")
				if (callerType == "text" || callerType == "password" || callerType == "textarea"){
					if(!$(caller).val()){
						isError = true
						promptText += options.allrules[rules[i]].alertText+"<br />"
					}	
				}
				
				if (callerType == "radio" || callerType == "checkbox" ){
					callerName = $(caller).attr("name")
					
					// Pour les tableau (checkbox...)
					var reg1=new RegExp("[\[\]]","g");
					if(callerName.match(reg1)){	
						callerName=callerName.substring(0,(callerName.length-2));
						if( $("input[name="+callerName+"\[\]]:checked").size() == 0) {
							isError = true
							if($("input[name="+callerName+"\[\]]").size() ==1) {
								promptText += options.allrules[rules[i]].alertTextCheckboxe+"<br />" 
							}else{
								promptText += options.allrules[rules[i]].alertTextCheckboxMultiple+"<br />"
							}	
						}
					}else {
						if($("input[name="+callerName+"]:checked").size() == 0) {
							isError = true
							if($("input[name="+callerName+"]").size()==1) {//
								promptText += options.allrules[rules[i]].alertTextCheckboxe+"<br />" 
							}else{
								promptText += options.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 += options.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 += options.allrules[rules[i]].alertText+"<br />";
					}
				}
			}

			function _customRegex(caller,rules,position){		 // VALIDATE REGEX RULES
				customRule = rules[position+1]
				pattern = eval(options.allrules[customRule].regex)
				if(!pattern.test($(caller).attr('value'))){
					isError = true
					promptText += options.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 += options.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(endLength=="" && (feildLength<startLength || feildLength>startLength)){
					isError = true
					promptText += startLength+options.allrules["length"].alertText3+"<br />"
				}else if(feildLength<startLength || (endLength && feildLength>endLength)){
					isError = true
					promptText += options.allrules["length"].alertText+startLength+options.allrules["length"].alertText2+endLength+options.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 += options.allrules["minCheckbox"].alertText+"<br />"
				}
			}
			return(isError) ? isError : false;
		};

		var closePrompt = function(caller) {	// CLOSE PROMPT WHEN ERROR CORRECTED
			$("."+caller).fadeTo("fast",0,function(){ $("."+caller).remove() });
		};
	}
	
	

	var stopForm = false
	$(".formError").remove();
	var xp=xa='';
	for(var z=0, max=els.length; z < max; z++) {
        var el = els[z];
        if (el.name!='' && !el.disabled) {
		    var name = el.name;	
			if(el.type && el.type!="hidden"){ 
				if(typeof(allRules) != 'undefined') (loadValidation(el)) ? stopForm = true : "";	
			}
			if(el.type=="text" || el.type=="textarea" || el.type=="hidden" || el.type=="password") {
				switch (name){
					case "xp": xp=el.value; break; //Page demande pour le traitement
					case "xa": xa=el.value; break; //Action a faire
					default : qs+='&'+name+'='+encodeURIComponent(el.value); break;
				}
			}else if(el.type=="select-one"){
				qs+='&'+ name+'='+el.options[el.selectedIndex].value; 
			}else if((el.type=="radio" || el.type=="checkbox") && el.checked){
				qs+='&'+ name+'='+el.value;
			}
       }
   }
   if (xp=='' || xa==''){ alert('Parametre [hidden] xp (page) ou xa (fonction) manquant'); return false;}
   if(!stopForm) return Array(qs,xp,xa);
}






/*
encodeURI(URIstring)

Note: The encodeURI() function encodes special characters, with the exception of:
, / ? : @ & = + $ #. Use the encodeURIComponent() function to encode these characters.

*/



