$(function() {
  $('.errorNews').hide();
  $('.success').hide();

			$('#mailingBtn').click(function(e){

				e.preventDefault();
				/* Variables */
				var error = false;
				var email = $('#emailMailing').val();
				var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

				/* Variables check */
				if (!filter.test(email)) {
					var error = true;
					$('#newsletter_error').fadeOut(500);
					$('#newsletter_error').fadeIn(500);
					$('#emailMailing').focus();
				}else{
					$('#newsletter_error').fadeOut(500);
				}
				if(error == false){
					//disable the submit button to avoid spamming
					//and change the button text to Sending...
					$('#mailingBtn').attr({'disabled' : 'true', 'value' : 'Sending...' });

					$.post("php/newsletter.php", $("#mailing").serialize(),function(result){
						if(result == 'sent'){
							//if the mail is sent remove the submit paragraph
							 $('#mailingBtn').remove();
							//and show the mail success div with fadeIn
							$('#newsletter_success').stop().fadeIn(500);
						}
						else if(result == 'exist'){
							$('#mailingBtn').remove();
							$('#newsletter_exist').stop().fadeIn(500);
							
						}
						else{
							//show the mail failed div
							$('#newsletter_fail').fadeIn(500);
							//reenable the submit button by removing attribute disabled and change the text back to Send The Message
							$('#mailingBtn').removeAttr('disabled').attr('value', 'Subscribe');
						}
					});
				}
			});    
		});
