$(document).ready(function() {
	$("#user_firstname").blur(function() {
		makeUsername();
	});
	$("#user_lastname").blur(function() {
		makeUsername();
	});
	$("#user_login").blur(function() {
		checkLoginAvailability();
	});
});

//Autopopulate the username with entire firstname and last initial unless user has created custom one
function makeUsername() {
	var initials = "";
	if ($('#user_firstname').val().length > 1) {
		initials += $('#user_firstname').val();
	}
	//This will prevent this function from overwriting a custom username
	if ($('#user_login').val().length > 3 && $('#user_login').val() != initials.toLowerCase()) {
		return;
	}
	if ($('#user_lastname').val().length > 1) {
		initials += $('#user_lastname').val().substring(0,1);
	}
	$('#user_login').val(initials.toLowerCase());
    checkLoginAvailability();
}

function checkLoginAvailability() {
  var login = $('#user_login').val();
    $.ajax({		
          url: "/users/login_available",
          dataType: "json",
          type: "GET",
          data: { login: login },					
          beforeSend: function(xhr) {
              xhr.setRequestHeader("Accept", "text/html");				
          },
          success: function(json) {	
            if (json == "Y") {
              $('#login_status').show();
            }
          }
      });			
}