// JavaScript Document
$(document).ready(function(){  
	var verifEmail=    /^[a-zA-Z0-9_-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,3}$/; /*regular expression */
	var isPhone=	/^[0-9+() .-]{8,}$/;
	var errMsg="";
	var nbErr=0;
	$('#ContactForm #Send').click( function(){ 
		errMsg = "";
		nbErr = 0;
		//verify if the form is well fill out.
		$('.required').each( function(){
			if( $(this).val() == "" ){
				$(this).css({background: "#FFFF33"});
				errMsg = errMsg + "- " + $(this).attr("name") + "\n";
				nbErr++;
			}else{
				 /* Verify the email address format */
				if( $(this).attr("name") == "email" ){
					var Emailvalue = $(this).val();						
					if( verifEmail.exec( Emailvalue )== null ){
						$(this).css({background: "#FFFF33"});
						errMsg = errMsg + "- Email format is incorrect\n";
						nbErr++;
					}
				}else{
					$(this).css({background: "#FFFFFF"});
				}
			}
		});	
		//Verify the phone number isPhone
		if( $("#ContactForm :input[name='phone']").val() != "" ){
				var phoneValue = $("#ContactForm :input[name='phone']").val();
				if( isPhone.exec( phoneValue )== null ){
					$("#ContactForm :input[name='phone']").css({background: "#FFFF33"});
					errMsg = errMsg + "- Phone format is incorrect\n";
					nbErr++;
				}
			}else{
				$("#ContactForm :input[name='phone']").css({background: "#FFFFFF"});
			}	
		
		//Verify the secret code
		var attr = $('#code').attr('src');
		attr = attr.substr(attr.indexOf('=')+1, attr.length);		
		$.post('inc/code.php', {'id': attr.toString()}, function(data) { 
				if( $('#ContactForm .verify').val() != data ){
					$('#ContactForm .verify').css({background: "#FFFFBB"});
					errMsg = errMsg + "- Code is different\n";
					nbErr++;
				}else{
					$('#ContactForm .verify').css({background: "#FFFFFF"});
				}
				
				if( nbErr ){
					jAlert("Please correct errors with the following "+ nbErr + " fields :\n" + errMsg,"Warnings");
					return false;
				}else{
					$('#ContactForm').prepend('<img id="loader" src="http://www.connexions.org/Graphics/img/loader.gif" alt="loader" />');
					$('#loader').css({'left':$('#ContactForm').width()/2, 'top':$('#ContactForm').height()/2,'position': 'absolute'})
								.ajaxStart( function(){ $(this).show(); })
								.ajaxStop( function(){ $(this).hide(); });
					$('#ContactForm').submit();
				}
		});			
	});		
	
});
