error_yet=0;
$(document).ready(function() {
	$(".error").hide();
	$("#confirm_b").click(function() { go(); });
	
	$('input[type=text]').keyup(function(e) {
		if(e.keyCode == 13) {
			go();
		} else {
			if (error_yet==1) {
				update_errors();
			}
		}
	});	
});
function result(msg, style) {
	if (style=="error") {
		error_yet=1;
	}
	if (!$(".result").hasClass(style)) {
		$(".result").attr("class","result " + style);
	}
	$(".r_list").text(msg);
	$(".result").fadeIn(); 
}
function update_errors() {
	n=$("#r_name").val();
	e=$("#r_email").val();
	p1=$("#r_pass").val();
	p2=$("#r_pass2").val();
	$("input[type=text], input[type=password]").each(function() {
		$(this).css("color","#565656"); 
	});
	if (n.length<4) { result("Username too short.", "error"); $("#r_name").css("color","red"); return false; }
	if (n.length>16) { result("Username too long.", "error"); $("#r_name").css("color","red"); return false; }
	if (p1.length<4) { result("Password too short.", "error"); $("#r_pass").css("color","red"); return false; }
	if (p1!=p2) { result("Passwords must match.", "error"); $("#r_pass").css("color","red");  $("#r_pass2").css("color","red"); return false; }
	if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(e)==false) { $("#r_email").css("color","red"); result("Email must be valid.", "error"); return false; }
	$(".result").fadeOut();
	return true;
}

function go() {
	if (update_errors()==true) {
		$.get("ajax.php",{action: "register", user:$("#r_name").val(), email:$("#r_email").val(), pass:SHA1(SHA1($("#r_pass").val()))}, function(r) {
			r=eval("(" + r + ")");
			if (r['error']==0) {
				 result("Registration successful, redirecting...", "success");
				 setTimeout(function() { window.location="/thanks"; }, 1500);
			} else {	
				 result(r['message']);	
			}
		});
	}
}