/* ========= BASE PLUGIN FOR FORM VALIDATION  ========= */

/* plugin for form validation, give id to form and initialize plugin on dom load*/

/*$(document).ready(function() {
	$('#formNousContacter').check_form();
});*/



jQuery.fn.check_form = function(){
	
	var form = this;
	var containErrors = [];
	var objectErrors = {
		reqField : "Les champs marqu�s en rouge sont incorrects",
		reqEmail : "L'adresse email saisie est incorrecte",
		confEmail : "Veuillez confirmer votre adresse email",
		reqLetters : "No special characters allowed.",
		confPassword : "Please confirm your password.",
		reqPhone : "Please enter a valid telephone number.",
		prevDate : "The date of birth of your child was more than 9 months ago",
		nextDate : "The due date of you child is more than 3 months from now"
	}
	
	/* ========= CHECK THE RETURN VALUE OF FUNCTION VALIDFORM AND THEN SUBMIT OR NOT ========= */
	
 	form.submit(function(e){
		e.preventDefault();
		if(validForm()){
			//this.submit();
			$.ajax({
				type: "POST",
				url: $(this).attr('name'),
				data: $(this).serialize(),
				contentType: "application/x-www-form-urlencoded",
				dataType: "text",
				success: function() {
					//$("#displayErrors").html('Message Sent');
					$('#overlayFormContainer').hide();     
                    
                    //displayTagConfirmFormContactFicheauto(); // TAGGAGE JS - rollbacked 02/05/2011
					$('#overlayFormThankYou').show();
                    trackingFormFicheAuto(); // TAGGAGE JS
                    
					document.getElementById('reg_form').reset();
				},
				error: function(errormessage) {
					//$("#displayErrors").html(errormessage);
				}
			});
			//for unserialize the jquery serialize use decodeURIComponent()
			//since serialize uses encodeURIComponent()
			
		}
	});
					
	var validForm = function(){
		
		/* ========= REMOVE ERROR CLASSES ON INIT ========= */
		
		form.find('input:visible, select:visible, label').each(function(e){
			$(this).removeClass('errorField');	
			$(this).removeClass('errorLabel');
		});
		
		/* ========= STANDARD REQUIRED VALIDATION FOR INPUT TYPE TEXT, SELECTS, INPUT TYPE CHECKBOX, TEXTAREAS ========= */
		
		form.find('input[type=text]:visible, select:visible, input[type=checkbox]:visible, textarea:visible, input[type=file]:visible').each(function(e){
			
			/* ========= ALL REQUIRED FIELDS HAVE CLASS reqField ========= */
			
			if(($(this).hasClass('reqField'))){
				
				/* ========= REQUIRED VALIDATION FOR INPUT TYPE TEXT ========= */
				
				if(($(this).attr('type') == 'text') && $(this).val() == ''){
					containErrors.push(objectErrors.reqField);
					$(this).addClass('errorField').prev('label').addClass('errorLabel');
				}else{
					
					/* ========= INPUT TYPE TEXT IS NOT EMPTY, GO FOR SPECIFIC VALIDATIONS ========= */
					
					/* ========= EMAIL VALIDATION AND CONFIRM EMAIL VALIDATION ========= */
			
					if(($(this).hasClass('mail'))){	
						var inputValue = String($(this).val());
						if(!inputValue.match(/^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,6}$/i)){
							containErrors.push(objectErrors.reqEmail);
							$(this).addClass('errorField').prev('label').addClass('errorLabel');
						}else{
							//$("#txtEmail").match({match: '#txtConfEmail', error: 'confEmail'});
						}
					}
					
					/* ========= ONLY LETTERS VALIDATION, ALLOW SPACES, ESCAPE CHARS IN UNICODE  ========= */
			
					if(($(this).hasClass('letters'))){	
						var inputValue = String($(this).val());
						/*
						u00E9 - �, u00e8 - �, u00e0 - �, u00e1 - �, u00e7 - �, u00f4 - �, u00f5 - �, u00ee - �, u00e3 - �, u00e2 - � 
						u00C9 - �, u00c8 - �, u00c0 - �, u00c1 - �, u00c7 - �, u00d4 - �, u00d5 - �, u00ce - �, u00c3 - �, u00c2 - �
						*/
						if(!inputValue.match(/^[-\u00E9\u00e8\u00e0\u00e1\u00e7\u00f4\u00f5\u00ee\u00e3\u00e2A-Za-z\s]+$/i)){
							containErrors.push(objectErrors.reqLetters);
							$(this).addClass('errorField').prev('label').addClass('errorLabel');
						}
					}
					
					/* ========= PASSWORD AND CONFIRM PASSWORD VALIDATION ========= */
			
					if(($(this).hasClass('password'))){	
						$("#txtPassword").match({match: '#txtConfPassword', error: 'confPassword'});
					}
					
					/* ========= TELEPHONE VALIDATION ========= */
			
					if(($(this).hasClass('phone'))){	
						var inputValue = String($(this).val());
						if(!inputValue.match(/^[0-9]{9}$/i)){
							containErrors.push(objectErrors.reqPhone);
							$(this).addClass('errorField').prev('label').addClass('errorLabel');
						}
					}
					
				}
				
				/* ========= END OF REQUIRED VALIDATION FOR INPUT TYPE TEXT ========= */
				
				/* ========= REQUIRED VALIDATION FOR SELECT ========= */
				
				if(($(this)[0].tagName.toLowerCase() == 'select') && $(this).val() == 0){
					containErrors.push(objectErrors.reqField);
					$(this).addClass('errorField').prev('label').addClass('errorLabel');
				}
				
				/* ========= REQUIRED VALIDATION FOR INPUT TYPE CHECKBOX ========= */
				
				if(($(this).attr('type') == 'checkbox') && $(this).attr('checked') != true){
					containErrors.push(objectErrors.reqField);
					$(this).parent().next().find('label').addClass('errorLabel');
				}
				
				/* ========= REQUIRED VALIDATION FOR TEXTAREA ========= */
				
				if(($(this)[0].tagName.toLowerCase() == 'textarea') && $(this).val() == ''){
					containErrors.push(objectErrors.reqField);
					$(this).addClass('errorField').prev('label').addClass('errorLabel');
				}
				
				/* ========= REQUIRED VALIDATION INPUT TYPE FILE EXTENSION ========= */
				
				if(($(this).attr('type') == 'file')){
					if(!$(this).validateFileExtension()){
						$(this).parent().prev('input').addClass('errorField')
						containErrors.push(objectErrors.reqField);
					}	
				}
				
			}
			
		});
		
		/* ========= REQUIRED VALIDATION FOR INPUT TYPE RADIO  ========= */
		
		var radio_groups = {}
		$("input[type=radio]:visible").each(function(){
    		if(($(this).hasClass('reqField'))){
				radio_groups[this.name] = true;
			}
		});
		for(group in radio_groups){
			if_checked = !!$(":radio[name="+group+"]:checked").length;
			if(!if_checked){
				containErrors.push(objectErrors.reqField);
				$('input[name='+ group+']').addClass('errorField').parent().parent().find('label:first').addClass('errorLabel');
			}
		}
		
		/* ========= SPECIFIC VALIDATIONS  ========= */
		
		/* ========= REQUIRED VALIDATION FOR INPUT TYPE FILE  ========= */
		
		/*if($('input.file').length){
			$('input.file').each(function(){
				if(!$(this).validateFileExtension()){
					$(this).addClass('errorField')
					containErrors.push(objectErrors.reqField);
				}				  
			});
		}*/
		
		/* ========= CHECK FOR FORM ERRORS ========= */
		
		if(containErrors.length > 0){
			writeErrors();
			return false;
		}else{
			/*var dataString = form.serialize();
			console.log(dataString);
			console.log(decodeURIComponent(dataString));*/
			return true;
		}
	};
	
	/* ========= FUNCTION TO WRITE ERRORS  ========= */
	
	var writeErrors = function(){
		containErrors = containErrors.unique();
		//console.log(containErrors);
		var errorContainer = $(".errorMsg");
		errorContainer.html('');
		var html = '<ul>';
		for(var i = 0; i < containErrors.length; i++){
			html += '<li>'+ containErrors[i] +'</li>'
		}
		html += '</ul>';
		errorContainer.append(html);
		containErrors = [];
	};
	
	/* ========= FUNCTION TO MATCH 2 INPUTS VALUE ========= */
	
	$.fn.match = function(m) {
		if($(this).val() == $(m.match).val()) {
          
        } else {
          containErrors.push(objectErrors[m.error]);
		  $(this).addClass('errorField').parent().prev().find('label').addClass('errorLabel');
		  $(m.match).addClass('errorField').parent().prev().find('label').addClass('errorLabel');
        };
	};
	

	
	
}





