var mail_reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

$(document).ready(function() {
	$("#LaunchNotificationName").focus(function(){ if ($(this).val()=="Name"){$(this).val("");}});
	$("#LaunchNotificationEmail").focus(function(){ if ($(this).val()=="E-Mail") {$(this).val("");}});
	$("#LaunchNotificationName").blur(function(){if ($(this).val().length==0) {$(this).val("Name");}});
	$("#LaunchNotificationEmail").blur(function(){if ($(this).val().length==0) {$(this).val("E-Mail");}});
	
	$("form").live("submit", function(){
		var error = false;
		
		var user_name = $("#LaunchNotificationName").val();
		var user_mail = $("#LaunchNotificationEmail").val();
		
		if ( user_name.length < 3 || user_name == "Name" ) {
			$("#LaunchNotificationName").addClass("error");
			$("label[for='LaunchNotificationName']").addClass("error").text("Gib einen Namen mit mind. 3 Zeichen ein").fadeIn();
			error = true;
		} else {
			$("#LaunchNotificationName").removeClass("error");
			$("label[for='LaunchNotificationName']").fadeOut();
		}
		
		if ( mail_reg.test(user_mail) == false || user_name == "E-Mail" ) {
			$("#LaunchNotificationEmail").addClass("error");
			$("label[for='LaunchNotificationEmail']").addClass("error").text("Gib eine gültige E-Mail Adresse ein").fadeIn();
			error = true;
		} else {
			$("#LaunchNotificationEmail").removeClass("error");
			$("label[for='LaunchNotificationEmail']").fadeOut();
		}
		
		if ( error == false ) {
			$("#formular").addClass("load");
			$.post('/launch/index', $("form").serialize(), function(data) {
				if ( data === 'true' ) {
					$("#formular").removeClass("load").addClass("success").find("form").replaceWith("<h2>Vielen Dank, " +
							user_name + "</h2><p>Damit hast du dir auf jeden Fall einen Platz als einer der ersten Besucher erspielt.</p>");
				} else {
					$("#formular").removeClass("load").addClass("failed").find("form").replaceWith("<h2>Entschuldigung</h2><p>Leider ist etwas schief gelaufen. Bitte versuche es nochmal.</p>");
				}
			});
		}
		
		return false;
	});
});
