$(document).ready(function() {
	jQuery("input#fName").val("Name");
	jQuery("input#lName").val("Last Name");
	jQuery("input#email").val("E-Mail");
	
	function input_out(element) {
		if (element.val() == "") {
			if (element.attr("id") == "fName")  element.val("Name");
			else if (element.attr("id") == "lName") element.val("Last Name");
			else if (element.attr("id") == "email") element.val("E-Mail");
		}
	}
	
	function input_in(element) {
		if (element.attr("name") != "submit")
			element.val("");
	}
	
	jQuery("input").click(function() {
		input_in(jQuery(this))
	});
	jQuery("input").blur(function(e) {
		input_out(jQuery(this));
	});
	var submiter = function(form) {
		var str = $('form#home-newsletter-form').serialize();
		$.ajax({
			type: "POST",
			url: "inc/newsletter.php",
			data: str,
			success: function(msg){
				$("#note").ajaxComplete(function(event, request, settings) {
					msg = msg.replace(/^(\s|\&nbsp;)*|(\s|\&nbsp;)*$/g,"");
					if(msg == "ok") {// Message Sent? Show the 'Thank You' message and hide the form
						result = '';
						$("form#home-newsletter-form").hide();
						alert('Thank you for registering.', 'Registration Succesful');
						$(this).html('Thank you for registering.');
					} else if (msg == "2"){
						$("form#home-newsletter-form").hide();
						$(this).css('color', '#FAA954');
						$(this).html('Your email is already on our database.');
						alert('Your email is already registered.', 'Registration Failure');
					} else {
						result = msg;
						$("form#home-newsletter-form").hide();
						$(this).css('color', '#FAA954');
						$(this).html('Could not register: ' + result);
						alert('Could not register.', 'Registration Failure');
					}
					$(this).show();
				});
			},
			failure: function(msg) {
				alert('Registration error', 'Error');
			}
		});
		return false;
	}	
	
	//Valida el formulario.
	$('form#home-newsletter-form').validate({
		invalidHandler: function (){
			alert('You must complete all the marked as (*) fields', 'Please complete all the fields');
		},
		focusInvalid: true,
		focusCleanup: true,
		submitHandler: function() {
			if (jQuery("input#fName").val() != "Name" && jQuery("input#lName").val() != "Last Name" && jQuery("input#email").val() != "E-Mail")
				submiter(this);
			else 
				alert("You must complete all the fields", "Default Fields");
		},
		messages: {
	    	fName: "<span style='color:#ff634d'>*</span>",
	    	lName: "<span style='color:#ff634d'>*</span>",
	    	email: {
	        	required: "<span style='color:#ff634d'>*</span>",
	        	email: "<span style='color:#ff634d'>*</span>"
	     	},
	     	enquiry: "<span style='color:#ff634d;margin-bottom:20px'>*</span>"
	   }
	});
});
