$(document).ready(function() {
	
	$('.error').hide();
	
	var $rand_num1 = Math.ceil(Math.random()*10);
	var $rand_num2 = Math.ceil(Math.random()*10);
	
	var $yhteensa = $rand_num1 + $rand_num2;
	
	$('#random').text($rand_num1 + ' + ' + $rand_num2);
		
	$(".button").click(function()
	{
	
    	$('.error').hide();
  	  	var name = $.trim($("input#name").val());
	  	if (name == "")
  		{
        	$("#name_error").show();
        	$("input#name").focus();
        	return false;
      	}
      	
      	var email = $("input#email").val();
  		if (email == "")
  		{
  			$('#email_error').text('Tarkista sähköpostiosoitteesi').show();
        	$("input#email").focus();
        	return false;
      	}
      	
      	if (!isValidEmailAddress(email))
      	{
      		$('#email_error').show();
        	$("input#email").focus();
        	return false;
      	}
  		var comment = $.trim($("textarea#comment").val());
  		
  		if (comment == "")
  		{
	        $("#comment_error").show();
	        $("textarea#comment").focus();
	        return false;
      	}
      	
      	var numbers = $("input#rand_num").val();
  		
  		if (numbers == "" || numbers != $yhteensa)
  		{
	        $("#num_error").show();
	        $(numbers).focus();
	        return false;
      	}
      
      var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment;
		//alert (dataString);return false;
		
		$.ajax({
      			type: "POST",
      			url: "../inc/mailPost.php",
      			data: dataString,
      			success: function() {
      				$('#contactMe').html("<div id='message'></div>");
        $('#message').html("<h2>Kiitos palautteesta!</h2>")
        .hide()
        .fadeIn(1500);
       }
     });
    	return false;
	});	
});

function isValidEmailAddress(emailAddress)
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}
