$(document).ready(function() {
	var messages = {
		"missing": {
			"en": "Please fill in the fields marked in red.",
			"it": "Per favore, riempi i campi marcati in rosso."
		},
		
		"wait": {
			"en": "Please wait while your inquiry is sent...",
			"it": "Attendi, il tuo messaggio &egrave; in fase di trasmissione..."
		},
		
		"ok": {
			"en": "Your message has been sent. Please allow up to 48 hours for a reply before attempting to send it again.",
			"it": "Il tuo messaggio &egrave; stato inviato. Riceverai una risposta entro 48 ore."
		},
		
		"ko": {
			"en": "There was an error during the transmission. Perchance a hamster chewed on a network wire.<br />Please try again or use an alternate means of communication.",
			"it": "Si &egrave; verificato un errore durante la trasmissione. Forse un criceto ha morso un cavo di rete.<br />Riprova o usa un altro mezzo di comunicazione."
		}
	};

	function reverse(s)
	{
		var output = "";
		
		for (var i = s.length - 1; i >= 0; i--)
		{
			output += s[i];
		}

		return output;
	}



	$(".rev").each(function(i, e) {
		$(this).html( reverse($(this).html()) );
	});
	
	$("form").submit(function(e) {
		e.preventDefault();

		var ok = true;
		var okColor = "#446797";
		var koColor = "#ce0221";
		
		var name = $.trim($("input[name=name]").val());
		var email = $.trim($("input[name=email]").val());
		var phone = $.trim($("input[name=phone]").val());
		var message = $.trim($("textarea[name=message]").val());
		var lang = $.trim($("input[name=lang]").val());
		
		if (lang == "" || (lang != "en" && lang != "it"))
		{
			lang = "en";
		}
		
		console.log(lang);
		
		if (name == "")
		{
			$("li#name label").css("color", koColor);
			ok = false;
		}
		else
		{
			$("li#name label").css("color", okColor);
		}


		if (email == "" || email.indexOf("@") == -1)
		{
			$("li#email label").css("color", koColor);
			ok = false;
		}
		else
		{
			$("li#email label").css("color", okColor);
		}
	
		if (message == "")
		{
			$("li#message label").css("color", koColor);
			ok = false;
		}
		else
		{
			$("li#message label").css("color", okColor);
		}
		
		$("#status").fadeIn(1000);
		if (!ok)
		{
			$("#status").html(messages.missing[lang]);
		}
		else
		{
			$("#status").html(messages.wait[lang]);
			$.post(
				"/sendmail",
				$(this).serialize(),
				function(response) {
					if (response == "ok")
					{
						$("#status").html(messages.ok[lang]);
					}
					else
					{
						$("#status").html(messages.ko[lang]);
					}
				},
				"text"
			);
		}
	});
	
});
