// Form Plugin written by Zoltan Radics


jQuery.fn.formManager = function (formMessages) {
	return this.each (function (formMessages) {
		// Submit the form
		var formId = "#"+this.id;
		$('#submit', this).click(function() {
			var formData = $(formId).serialize();
			if ( checkForm() ) {
				sendMail(formData);
			}
			return false;
		});
		
		// Check the form
		function checkForm() {
			var valid = true;
			$(formId+" .req").each(function (i) {
				if (this.value == "") {
					$(this).addClass('redborder');
					setTimeout(function(){ $('.redborder').removeClass('redborder') }, 3000);
					errorMessage("KÉRJÜK MINDEN SZÜKSÉGES MEZŐT TÖLTSÖN KI!");
					valid = false;
				} else if (validemail() == false) {
					errorMessage('ADJON MEG ÉRVÉNYES E-MAILCÍMET!');		
					valid = false;
				}
			});
			return valid;
		}
		
		// Validate email address!
		function validemail() {
			var valid = true;
			var emailVal = $(formId+" #email").val();
			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			if (!emailReg.test(emailVal)) {
				valid = false;
			}
			return valid;
		}
		
		// Show error message
		function errorMessage(errorText) {
			var showmessage = 5000;
			// Send message for the user.
			$('.message').text(errorText);
			// Service message show / hide animation
			$('.message').slideDown('slow', function() {
				setTimeout(function() {
					$('.message').slideUp('slow');
					}, showmessage); 
				});
		}
		
		// Emtpy the form
		function emptyForm() {
			$('#name').val('');
			$('#phone').val('');
			$('#email').val('');
			$('#company').val('');
			$('#msg').val('');
		}
		
		// Post the data to the script
		function sendMail(formData) {
			$.post('/wp-content/plugins/desztinaciomarketing/ajax.php', { formdata: formData }, 
			function(data){
				errorMessage('ÜZENETÉT ELKÜLDTÜK!');
				emptyForm();
			});	
		}
		
		
	});
}
