$(document)
		.ready(
				function() {
					
				
					var showUserText = true;
					var showNameText = true;
					var showEmailText = true;
					
					var showPasswordText = true;
					var showConfirmPasswordText = true;
					
					var agreeChecked = false;
					var userText = "Escribe tu nombre de usuario";
					var userExistErrorText = "El nombre de usuario ya existe";
					var userErrorText = "Escribe un nombre de usuario";
					var userLengthErrorText = "Tu usuario de ser mayor a 3 caracteres";
					var userInvalidErrorText = "Sólo letras, números, '_' y '.'";
					var nameText = "¿Cuál es tu nombre completo?";
					var nameErrorText = "Necesitamos tu nombre completo";
					var nameInvalidErrorText = "Sólo letras, números y espacios";
					var emailText = "Te mandaremos una confirmación a tu correo";
					var emailErrorText = "Por favor, escribe un Email válido";
					var agreeErrorText = "Debes de aceptar";

					var passwordText = "Escribe tu contraseña de más de 8 caracteres";
					var passwordConfirmText = "Confirma tu contraseña";
					var passwordErrorText = "Debe de ser de al menos 8 caracteres";
					var passwordConfirmErrorText = "Debe ser igual a la contraseña";
					var passwordInvalidErrorText = "No uses espacios en blanco en tu contraseña";
					
					
					var form = $("#customForm");
					var send = $("#send");
					var user = $("#user");
					var userInfo = $("#userInfo");
					var name = $("#fullname");
					var nameInfo = $("#nombreInfo");
					var email = $("#email");
					var emailInfo = $("#emailInfo");
					var agree = $("#agree");
					var agreeInfo = $("#agreeInfo");
					
					var password = $("#password");
					var passwordInfo = $("#passwordInfo");
					var confirmPassword = $("#confirmPassword");
					var confirmPasswordInfo = $("#confirmPasswordInfo");

					
					var userRegex = /^[a-z0-9_.]+$/i;
					var userValidChars = /[a-z0-9_.]/i;
					var nameRegex = /^[a-z0-9 ñáéíóú]+$/i;
					var nameValidChars = /[a-z0-9 ñáéíóú]/i;
					var emailRegex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/;
					var emailValidChars = /[a-z0-9@_.-]/i;
					
					var passwordRegex = /^[^\s]*$/;
					
					configureInput(user, userValidChars, 20);
					user.attr("style", "text-transform:lowercase");
					configureInput(name, nameValidChars, 200);
					configureInput(email, emailValidChars, 200);
					function configureInput(input, regex, maxLength){
						input.attr("maxlength", maxLength);
						input.keypress(function(e) 
						{ 	
							var charCode = (e.which) ? e.which : window.event.keyCode;  
							if (charCode <= 13 || (charCode >= 37 && charCode <= 40)) 
							{ 
								return true; 
							} else 
							{ 
								return regex.test(String.fromCharCode(charCode)); 
							} 
						});
					}
					user.focus( function() {
						if (showUserText) {
							showInfo(user, userInfo, userText);
						}
					});
					name.focus( function() {
						if (showNameText) {
							showInfo(name, nameInfo, nameText);
						}
					});
					email.focus( function() {
						if (showEmailText) {
							showInfo(email, emailInfo, emailText);
						}
					});
					
					password.focus( function() {
						if (showPasswordText) {
							showInfo(password, passwordInfo, passwordText);
						}
					});
					password.blur(validatePassword);
					confirmPassword.blur(validateConfirmPassword);

					
					email.blur(validateEmail);
					user.blur(function(){
						validateUser(false);
					});
					name.blur(validateName);
					agree.click(function(){
						agreeChecked = this.checked; 
						if(agreeChecked){
							hideError(agree, agreeInfo);
						} else {
							showError(agree, agreeInfo, agreeErrorText);
						}
					});

					send.click(processForm);
					
					function showInfo(field, fieldInfo, infoText){
						fieldInfo.text(infoText);
						fieldInfo.addClass("info");
					}
					
					function showError(field, fieldInfo, errorText){
						field.addClass("error");
						fieldInfo.text(errorText);
						fieldInfo.removeClass("info");
						fieldInfo.removeClass("valid");
						fieldInfo.addClass("error");
					}
					
					
					
					function removeMessage(field, fieldInfo){
						field.removeClass("error");
						fieldInfo.text("");
						fieldInfo.removeClass("info");
						fieldInfo.removeClass("error");
					}

					function hideError(field, fieldInfo){
						removeMessage(field, fieldInfo);
						fieldInfo.addClass("valid");
					}


					function validateAgreement(){
						if(agreeChecked){
							hideError(agree, agreeInfo);
							return true;
						} else{
							showError(agree, agreeInfo, agreeErrorText);
							return false;
						}
					}

					function validateEmail() {
						showEmailText = false;
						if (emailRegex.test(email.val())) {
							hideError(email, emailInfo);
							return true;
						} else {
							showError(email, emailInfo, emailErrorText);
							return false;
						}
					}
					

					function validateUser(validateAll) {
						user.val($.trim(user.val().toLowerCase()));
						if (user.val().length > 0) {
							if(user.val().length > 3){
								if (userRegex.test(user.val())) {
									//$.get('http://localhost:8080/com.tralix.misfacturas.registro/regVal', {
									$.get('../misfacturas.net/registration', {
										user : user.val(),
										service : 'validate'
									}, function(data) {
										showUserText = false;
										if (data == 'true') {
											showUserError(validateAll, userExistErrorText);
											return false;
										} else {
											hideError(user, userInfo);
											if(validateAll){
												if(validateName() & validateEmail() & validateAgreement() & validatePassword() & validateConfirmPassword()){
													form.submit();
													return true;
												} else {
													return false;
												}
											} else {
												return true;
											}
										}
									});
								} else{
									showUserError(validateAll, userInvalidErrorText);
									return false;
								}
							} else {
								showUserError(validateAll, userLengthErrorText);
								return false;
							}
						} else {
							showUserError(validateAll, userErrorText);
							return false;
						}
					}
					
					function showUserError(validateAll, errorText){
						showError(user, userInfo, errorText);
						showUserText = false;
						if(validateAll){
							validateName();
							validateEmail();
							validateAgreement();
							validatePassword();
							validateConfirmPassword();
						}
					}

					function validateName() {
						showNameText = false;
						name.val($.trim(name.val()));
						if(name.val().length > 0){
							if (nameRegex.test(name.val())) {
								hideError(name, nameInfo);
								return true;
							} else {
								showError(name, nameInfo, nameInvalidErrorText);
								return false;
							}
						} else{
							showError(name, nameInfo, nameErrorText);
								return false;
						}
					}
					
					
					function validatePassword(){
						showPasswordText = false;
						if(password.val().length >= 8){
							validateConfirmPassword();
							if (passwordRegex.test(password.val())) {
								hideError(password, passwordInfo);
								return true;
							} else {
								removeMessage(confirmPassword, confirmPasswordInfo);
								showError(password, passwordInfo, passwordInvalidErrorText);
								return false;
							}
						} else{
							removeMessage(confirmPassword, confirmPasswordInfo);
							showError(password, passwordInfo, passwordErrorText);
							return false;
						}						
					}
					
					function validateConfirmPassword(){
						removeMessage(confirmPassword, confirmPasswordInfo);
						showConfirmPasswordText = false;
						if (confirmPassword.val().length > 0 && password.val().length >= 8){
							if (password.val() == confirmPassword.val()) {
								hideError(confirmPassword, confirmPasswordInfo);
								return true;
							} else {
								showError(confirmPassword, confirmPasswordInfo, passwordConfirmErrorText);
								return false;
							}
						}
						removeMessage(confirmPassword, confirmPasswordInfo);
						return false;
					}

					function processForm() {
						var vectorNombre = name.val().split(" ");
						var numCampos = vectorNombre.length;

						var nombre = "";
						var aPaterno = "";
						var aMaterno = "";

						switch (numCampos) {
						case 1:
							nombre = vectorNombre[0];
							break;
						case 2:
							nombre = vectorNombre[0];
							aPaterno = vectorNombre[1];
							break;
						case 3:
							nombre = vectorNombre[0];
							aPaterno = vectorNombre[1];
							aMaterno = vectorNombre[2];
							break;
						case 4:
							nombre = vectorNombre[0] + " " + vectorNombre[1];
							aPaterno = vectorNombre[2];
							aMaterno = vectorNombre[3];
							break;
						default:
							nombre = vectorNombre[0] + " " + vectorNombre[1];
							aPaterno = vectorNombre[2];
							aMaterno = vectorNombre[3];
							for ( var i = 4; i < numCampos; i++) {
								aMaterno += " " + vectorNombre[i];
							}
						}
						$("#nombre").val(nombre);
						$("#apaterno").val(aPaterno);
						$("#amaterno").val(aMaterno);
						if(!validateUser(true)){
							return false;
						} 
					}
				});
								
/* POPUP BEGIN */				
function popup(mylink, windowname) {
	if (! window.focus)return true;
		var href;
		if (typeof(mylink) == 'string')
		   href=mylink;
	else
	   href=mylink.href;
	
	var sw = screen.width;
	var sh = screen.height
	var pw = 550;
	var ph = 450;
	
	window.open(href, windowname, 'width='+pw+',height='+ph+',scrollbars=yes,top='+(sh/2-pw/2)+',left='+(sw/2-ph/2));
	return false;
}
/* POPUP END */

